summaryrefslogtreecommitdiff
path: root/lisp/test/psql-2.lsp
blob: 011512cb0bbcd1dd7a010270598f83a13a2ba81d (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
;; Postgresql C library interface, example program 2, using the xedit
;; lisp interface

;;  Test of the asynchronous notification interface
;;
;; Start this program, then from psql in another window do
;;   NOTIFY TBL2;
;;
;; Or, if you want to get fancy, try this:
;; Populate a database with the following:
;;
;;   CREATE TABLE TBL1 (i int4);
;;
;;   CREATE TABLE TBL2 (i int4);
;;
;;   CREATE RULE r1 AS ON INSERT TO TBL1 DO
;;     (INSERT INTO TBL2 values (new.i); NOTIFY TBL2);
;;
;; and do
;;
;;   INSERT INTO TBL1 values (10);
(require "psql")

(defun exit-nicely (conn)
    (pq-finish conn)
    (quit 1)
)

;; begin, by setting the parameters for a backend connection if the
;; parameters are null, then the system will try to use reasonable
;; defaults by looking up environment variables or, failing that,
;; using hardwired constants
(setq pghost nil)		; host name of the backend server
(setq pgport nil)		; port of the backend server
(setq pgoptions nil)		; special options to start up the backend server
(setq pgtty nil)		; debugging tty for the backend server
(setq pgdbname "test")		; change this to the name of your test database
				;; XXX Note: getenv not yet implemented in the
				 ; lisp interpreter

;; make a connection to the database
(setq conn (pq-setdb pghost pgport pgoptions pgtty pgdbname))

;; check to see that the backend connection was successfully made
(when (= (pq-status conn) pg-connection-bad)
    (format t "Connection to database '~A' failed.~%" pgdbname)
    (format t "~A" (pq-error-message conn))
    (exit-nicely conn))

(setq res (pq-exec conn "LISTEN TBL2"))
(when (= (pq-status conn) pg-connection-bad)
    (format t "LISTEN command failed~%")
    (format t "~A" (pq-error-message conn))
    (exit-nicely conn))

;; Should PQclear PGresult whenever it is no longer needed to avoid memory leaks
(pq-clear res)

(loop
    ;; wait a little bit between checks; waiting with select()
    ;; would be more efficient.
	;; XXX Note: sleep not yet implemented in the lisp interpreter

    ;; collect any asynchronous backend messages
    (pq-consume-input conn)

    ;; check for asynchronous notify messages
    (when (setq notifies (pq-notifies conn))
	(format t "ASYNC NOTIFY of '~A' from backend pid '~D' received~%"
	 (pg-notify-relname notifies) (pg-notify-be-pid notifies))
    )
)

(pq-finish conn)