summaryrefslogtreecommitdiff
path: root/db/conn.rkt
blob: e083d940f40bf4891eeaace239f2d1f9b639410b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#lang racket

(require db)

(provide current-conn
         connect!
         disconnect!
         with-db
         with-tx)

(define current-conn (make-parameter #f))

(define (connect! #:path [path 'memory])
  (cond
    [(connection? (current-conn))
     (printf "Database connection already exists: ~e\n" (current-conn))]
    [else
     (current-conn (sqlite3-connect #:database path
                                    #:mode 'create))
     (printf "Created database connection at path: ~a\n" path)]))

(define (disconnect!)
  (disconnect (current-conn))
  (printf "Closing database connection: ~e\n" (current-conn))
  (current-conn #f))

(define-syntax-rule (with-db body ...)
  (begin (connect!) body ...))

(define-syntax-rule (with-tx body ...)
  (call-with-transaction (current-conn) (λ () body ...)))

(module+ test
  (require rackunit)
  (check-equal? (current-conn) #f)
  (connect!)
  (check-true (connection? (current-conn)))
  (disconnect!)
  (check-equal? (current-conn) #f)
  (with-db
    (check-true (connection? (current-conn)))))
Copyright 2019--2025 Marius PETER