summaryrefslogtreecommitdiff
path: root/db/conn.rkt
blob: 02194508ad3fe23d684c9f0cded4b11f8f93e12f (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
42
43
44
#lang racket

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

(require db
         "../debug.rkt")

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

(define (connect! #:path [path 'memory])
  (if (connection? (current-conn))
      (debug-log (format "Connection already instantiated: ~a" (current-conn)))
      (begin
        (current-conn (sqlite3-connect #:database path #:mode 'create))
        (query-exec (current-conn) "PRAGMA foreign_keys = ON")
        (debug-log (format "Connection instantiated: ~a" (current-conn))))))

(define (disconnect!)
  (disconnect (current-conn))
  (current-conn #f)
  (debug-log "Connection disconnected."))

(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--2026 Marius PETER