r1749: *** empty log message ***
[clsql.git] / interfaces / postgresql-socket / postgresql-socket-api.cl
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          postgresql-socket.cl
6 ;;;; Purpose:       Low-level PostgreSQL interface using sockets
7 ;;;; Programmers:   Kevin M. Rosenberg based on
8 ;;;;                Original code by Pierre R. Mai 
9 ;;;;                
10 ;;;; Date Started:  Feb 2002
11 ;;;;
12 ;;;; $Id: postgresql-socket-api.cl,v 1.13 2002/04/06 23:23:47 kevin Exp $
13 ;;;;
14 ;;;; This file, part of CLSQL, is Copyright (c) 2002 by Kevin M. Rosenberg
15 ;;;; and Copyright (c) 1999-2001 by Pierre R. Mai
16 ;;;;
17 ;;;; CLSQL users are granted the rights to distribute and use this software
18 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
19 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
20 ;;;; *************************************************************************
21
22
23 ;;;; Changes by Kevin Rosenberg
24 ;;;;  - Added socket open functions for Allegro and Lispworks
25 ;;;;  - Changed CMUCL FFI to UFFI
26 ;;;;  - Added necessary (force-output) for socket streams on 
27 ;;;;     Allegro and Lispworks
28 ;;;;  - Added initialization variable
29 ;;;;  - Added field type processing
30
31  
32 (declaim (optimize (debug 3) (speed 3) (safety 1) (compilation-speed 0)))
33 (in-package :postgresql-socket)
34
35 (uffi:def-enum pgsql-ftype
36     ((:bytea 17)
37      (:int2 21)
38      (:int4 23)
39      (:int8 20)
40      (:float4 700)
41      (:float8 701)))
42
43 (defmethod database-type-library-loaded ((database-type
44                                           (eql :postgresql-socket)))
45   "T if foreign library was able to be loaded successfully. Always true for
46 socket interface"
47   t)
48                                       
49
50 ;;; Message I/O stuff
51
52 (defmacro define-message-constants (description &rest clauses)
53   (assert (evenp (length clauses)))
54   (loop with seen-characters = nil
55         for (name char) on clauses by #'cddr
56         for char-code = (char-code char)
57         for doc-string = (format nil "~A (~:C): ~A" description char name)
58         if (member char seen-characters)
59         do (error "Duplicate message type ~@C for group ~A" char description)
60         else
61         collect
62         `(defconstant ,name ,char-code ,doc-string)
63         into result-clauses
64         and do (push char seen-characters)
65       finally
66         (return `(progn ,@result-clauses))))
67
68 (eval-when (:compile-toplevel :load-toplevel :execute)
69 (define-message-constants "Backend Message Constants"
70   +ascii-row-message+ #\D
71   +authentication-message+ #\R
72   +backend-key-message+ #\K
73   +binary-row-message+ #\B
74   +completed-response-message+ #\C
75   +copy-in-response-message+ #\G
76   +copy-out-response-message+ #\H
77   +cursor-response-message+ #\P
78   +empty-query-response-message+ #\I
79   +error-response-message+ #\E
80   +function-response-message+ #\V
81   +notice-response-message+ #\N
82   +notification-response-message+ #\A
83   +ready-for-query-message+ #\Z
84   +row-description-message+ #\T))
85
86 (defgeneric send-socket-value (type socket value))
87
88 (defmethod send-socket-value ((type (eql 'int32)) socket (value integer))
89   (write-byte (ldb (byte 8 24) value) socket)
90   (write-byte (ldb (byte 8 16) value) socket)
91   (write-byte (ldb (byte 8 8) value) socket)
92   (write-byte (ldb (byte 8 0) value) socket))
93
94 (defmethod send-socket-value ((type (eql 'int16)) socket (value integer))
95   (write-byte (ldb (byte 8 8) value) socket)
96   (write-byte (ldb (byte 8 0) value) socket))
97
98 (defmethod send-socket-value ((type (eql 'int8)) socket (value integer))
99   (write-byte (ldb (byte 8 0) value) socket))
100
101 (defmethod send-socket-value ((type (eql 'string)) socket (value string))
102   (loop for char across value
103         for code = (char-code char)
104         do (write-byte code socket)
105         finally (write-byte 0 socket)))
106
107 (defmethod send-socket-value ((type (eql 'limstring)) socket (value string))
108   (loop for char across value
109         for code = (char-code char)
110         do (write-byte code socket)))
111
112 (defmethod send-socket-value ((type (eql 'byte)) socket (value integer))
113   (write-byte value socket))
114
115 (defmethod send-socket-value ((type (eql 'byte)) socket (value character))
116   (write-byte (char-code value) socket))
117
118 (defmethod send-socket-value ((type (eql 'byte)) socket value)
119   (write-sequence value socket))
120
121 (defgeneric read-socket-value (type socket))
122
123 (defmethod read-socket-value ((type (eql 'int32)) socket)
124   (let ((result 0))
125     (setf (ldb (byte 8 24) result) (read-byte socket))
126     (setf (ldb (byte 8 16) result) (read-byte socket))
127     (setf (ldb (byte 8 8) result) (read-byte socket))
128     (setf (ldb (byte 8 0) result) (read-byte socket))
129     result))
130
131 (defmethod read-socket-value ((type (eql 'int16)) socket)
132   (let ((result 0))
133     (setf (ldb (byte 8 8) result) (read-byte socket))
134     (setf (ldb (byte 8 0) result) (read-byte socket))
135     result))
136
137 (defmethod read-socket-value ((type (eql 'int8)) socket)
138   (read-byte socket))
139
140 (defmethod read-socket-value ((type (eql 'string)) socket)
141   (with-output-to-string (out)
142     (loop for code = (read-byte socket)
143           until (zerop code)
144           do (write-char (code-char code) out))))
145
146 (defgeneric skip-socket-value (type socket))
147
148 (defmethod skip-socket-value ((type (eql 'int32)) socket)
149   (dotimes (i 4) (read-byte socket)))
150
151 (defmethod skip-socket-value ((type (eql 'int16)) socket)
152   (dotimes (i 2) (read-byte socket)))
153
154 (defmethod skip-socket-value ((type (eql 'int8)) socket)
155   (read-byte socket))
156
157 (defmethod skip-socket-value ((type (eql 'string)) socket)
158   (loop until (zerop (read-byte socket))))
159
160 (defmacro define-message-sender (name (&rest args) &rest clauses)
161   (loop with socket-var = (gensym)
162         for (type value) in clauses
163         collect
164         `(send-socket-value ',type ,socket-var ,value)
165         into body
166       finally
167         (return
168           `(defun ,name (,socket-var ,@args)
169              ,@body))))
170
171 (defun pad-limstring (string limit)
172   (let ((result (make-string limit :initial-element #\NULL)))
173     (loop for char across string
174           for index from 0 below limit
175           do (setf (char result index) char))
176     result))
177
178 (define-message-sender send-startup-message
179     (database user &optional (command-line "") (backend-tty ""))
180   (int32 296)                           ; Length
181   (int32 #x00020000)                    ; Version 2.0
182   (limstring (pad-limstring database 64))
183   (limstring (pad-limstring user 32))
184   (limstring (pad-limstring command-line 64))
185   (limstring (pad-limstring "" 64))     ; Unused
186   (limstring (pad-limstring backend-tty 64)))
187
188 (define-message-sender send-terminate-message ()
189   (byte #\X))
190
191 (define-message-sender send-unencrypted-password-message (password)
192   (int32 (+ 5 (length password)))
193   (string password))
194
195 (define-message-sender send-query-message (query)
196   (byte #\Q)
197   (string query))
198
199 (define-message-sender send-encrypted-password-message (crypted-password)
200   (int32 (+ 5 (length crypted-password)))
201   (string crypted-password))
202
203 (define-message-sender send-cancel-request (pid key)
204   (int32 16)                            ; Length
205   (int32 80877102)                      ; Magic
206   (int32 pid)
207   (int32 key))
208
209
210 (defun read-socket-sequence (string stream)
211 "KMR -- Added to support reading from binary stream into a string"
212   (declare (optimize (speed 3) (safety 0))
213            (string string))
214   (dotimes (i (length string))
215     (declare (fixnum i))
216     (setf (char string i) (code-char (read-byte stream))))
217   string)
218
219
220 ;;; Support for encrypted password transmission
221
222 (defvar *crypt-library-loaded* nil)
223
224 (defun crypt-password (password salt)
225   "Encrypt a password for transmission to a PostgreSQL server."
226   (unless *crypt-library-loaded*
227     (uffi:load-foreign-library 
228      (find-foreign-library "libcrypt"
229                            '("/usr/lib/" "/usr/local/lib/" "/lib/"))
230      :supporting-libaries '("c"))
231     (eval '(uffi:def-function "crypt" 
232             ((key :cstring)
233              (salt :cstring))
234             :returning :cstring))
235     (setq *crypt-library-loaded* t))
236    (uffi:with-cstring (password-cstring password)
237      (uffi:with-cstring (salt-cstring salt)
238        (uffi:convert-from-cstring (crypt password-cstring salt-cstring)))))
239 ;;; Condition hierarchy
240
241 (define-condition postgresql-condition (condition)
242   ((connection :initarg :connection :reader postgresql-condition-connection)
243    (message :initarg :message :reader postgresql-condition-message))
244   (:report
245    (lambda (c stream)
246      (format stream "~@<~A occurred on connection ~A. ~:@_Reason: ~A~:@>"
247              (type-of c)
248              (postgresql-condition-connection c)
249              (postgresql-condition-message c)))))
250
251 (define-condition postgresql-error (error postgresql-condition)
252   ())
253
254 (define-condition postgresql-fatal-error (postgresql-error)
255   ())
256
257 (define-condition postgresql-login-error (postgresql-fatal-error)
258   ())
259
260 (define-condition postgresql-warning (warning postgresql-condition)
261   ())
262
263 (define-condition postgresql-notification (postgresql-condition)
264   ()
265   (:report
266    (lambda (c stream)
267      (format stream "~@<Asynchronous notification on connection ~A: ~:@_~A~:@>"
268              (postgresql-condition-connection c)
269              (postgresql-condition-message c)))))
270
271 ;;; Structures
272
273 (defstruct postgresql-connection
274   host
275   port
276   database
277   user
278   password
279   options
280   tty
281   socket
282   pid
283   key)
284
285 (defstruct postgresql-cursor
286   connection
287   name
288   fields)
289
290 ;;; Socket stuff
291
292 (defconstant +postgresql-server-default-port+ 5432
293   "Default port of PostgreSQL server.")
294
295 (defvar *postgresql-server-socket-timeout* 60
296   "Timeout in seconds for reads from the PostgreSQL server.")
297
298
299 #+cmu
300 (defun open-postgresql-socket (host port)
301   (etypecase host
302     (pathname
303      ;; Directory to unix-domain socket
304      (ext:connect-to-unix-socket
305       (namestring
306        (make-pathname :name ".s.PGSQL" :type (princ-to-string port)
307                       :defaults host))))
308     (string
309      (ext:connect-to-inet-socket host port))))
310
311 #+cmu
312 (defun open-postgresql-socket-stream (host port)
313   (system:make-fd-stream
314    (open-postgresql-socket host port)
315    :input t :output t :element-type '(unsigned-byte 8)
316    :buffering :none
317    :timeout *postgresql-server-socket-timeout*))
318
319 #+allegro
320 (defun open-postgresql-socket-stream (host port)
321   (etypecase host
322     (pathname
323      (let ((path (namestring
324                   (make-pathname :name ".s.PGSQL" :type (princ-to-string port)
325                                  :defaults host))))
326        (socket:make-socket :type :stream :address-family :file
327                            :connect :active
328                            :remote-filename path :local-filename path)))
329     (string
330      (socket:with-pending-connect
331          (mp:with-timeout (*postgresql-server-socket-timeout* (error "connect failed"))
332            (socket:make-socket :type :stream :address-family :internet
333                                :remote-port port :remote-host host
334                                :connect :active :nodelay t))))
335     ))
336
337 #+lispworks
338 (defun open-postgresql-socket-stream (host port)
339   (etypecase host
340     (pathname
341      (error "File sockets not supported on Lispworks."))
342     (string
343      (comm:open-tcp-stream host port :direction :io :element-type '(unsigned-byte 8)
344                            :read-timeout *postgresql-server-socket-timeout*))
345     ))
346
347 ;;; Interface Functions
348
349 (defun open-postgresql-connection (&key (host (cmucl-compat:required-argument))
350                                         (port +postgresql-server-default-port+)
351                                         (database (cmucl-compat:required-argument))
352                                         (user (cmucl-compat:required-argument))
353                                         options tty password)
354   "Open a connection to a PostgreSQL server with the given parameters.
355 Note that host, database and user arguments must be supplied.
356
357 If host is a pathname, it is assumed to name a directory containing
358 the local unix-domain sockets of the server, with port selecting which
359 of those sockets to open.  If host is a string, it is assumed to be
360 the name of the host running the PostgreSQL server.  In that case a
361 TCP connection to the given port on that host is opened in order to
362 communicate with the server.  In either case the port argument
363 defaults to `+postgresql-server-default-port+'.
364
365 Password is the clear-text password to be passed in the authentication
366 phase to the server.  Depending on the server set-up, it is either
367 passed in the clear, or encrypted via crypt and a server-supplied
368 salt.  In that case the alien function specified by `*crypt-library*'
369 and `*crypt-function-name*' is used for encryption.
370
371 Note that all the arguments (including the clear-text password
372 argument) are stored in the `postgresql-connection' structure, in
373 order to facilitate automatic reconnection in case of communication
374 troubles."
375   (reopen-postgresql-connection
376    (make-postgresql-connection :host host :port port
377                                :options (or options "") :tty (or tty "")
378                                :database database :user user
379                                :password (or password ""))))
380
381 (defun reopen-postgresql-connection (connection)
382   "Reopen the given PostgreSQL connection.  Closes any existing
383 connection, if it is still open."
384   (when (postgresql-connection-open-p connection)
385     (close-postgresql-connection connection))
386   (let ((socket (open-postgresql-socket-stream 
387                   (postgresql-connection-host connection)
388                   (postgresql-connection-port connection))))
389     (unwind-protect
390          (progn
391            (setf (postgresql-connection-socket connection) socket)
392            (send-startup-message socket
393                                  (postgresql-connection-database connection)
394                                  (postgresql-connection-user connection)
395                                  (postgresql-connection-options connection)
396                                  (postgresql-connection-tty connection))
397            (force-output socket)
398            (loop
399                (case (read-socket-value 'int8 socket)
400                  (#.+authentication-message+
401                   (case (read-socket-value 'int32 socket)
402                     (0 (return))
403                     ((1 2)
404                      (error 'postgresql-login-error
405                             :connection connection
406                             :message
407                             "Postmaster expects unsupported Kerberos authentication."))
408                     (3
409                      (send-unencrypted-password-message
410                       socket
411                       (postgresql-connection-password connection)))
412                     (4
413                      (let ((salt (make-string 2)))
414                        (read-socket-sequence salt socket)
415                        (send-encrypted-password-message
416                         socket
417                         (crypt-password
418                          (postgresql-connection-password connection) salt))))
419                     (t
420                      (error 'postgresql-login-error
421                             :connection connection
422                             :message
423                             "Postmaster expects unknown authentication method."))))
424                  (#.+error-response-message+
425                   (let ((message (read-socket-value 'string socket)))
426                     (error 'postgresql-login-error
427                            :connection connection :message message)))
428                  (t
429                   (error 'postgresql-login-error
430                          :connection connection
431                          :message
432                          "Received garbled message from Postmaster"))))
433            ;; Start backend communication
434            (force-output socket)
435            (loop
436                (case (read-socket-value 'int8 socket)
437                  (#.+backend-key-message+
438                   (setf (postgresql-connection-pid connection)
439                         (read-socket-value 'int32 socket)
440                         (postgresql-connection-key connection)
441                         (read-socket-value 'int32 socket)))
442                  (#.+ready-for-query-message+
443                   (setq socket nil)
444                   (return connection))
445                  (#.+error-response-message+
446                   (let ((message (read-socket-value 'string socket)))
447                     (error 'postgresql-login-error
448                            :connection connection
449                            :message message)))
450                  (#.+notice-response-message+
451                   (let ((message (read-socket-value 'string socket)))
452                     (warn 'postgresql-warning :connection connection
453                           :message message)))
454                  (t
455                   (error 'postgresql-login-error
456                          :connection connection
457                          :message
458                          "Received garbled message from Postmaster")))))
459       (when socket
460         (close socket)))))
461
462 (defun close-postgresql-connection (connection &optional abort)
463   (unless abort
464     (ignore-errors
465       (send-terminate-message (postgresql-connection-socket connection))))
466   (close (postgresql-connection-socket connection)))
467
468 (defun postgresql-connection-open-p (connection)
469   (let ((socket (postgresql-connection-socket connection)))
470     (and socket (streamp socket) (open-stream-p socket))))
471
472 (defun ensure-open-postgresql-connection (connection)
473   (unless (postgresql-connection-open-p connection)
474     (reopen-postgresql-connection connection)))
475
476 (defun process-async-messages (connection)
477   (assert (postgresql-connection-open-p connection))
478   ;; Process any asnychronous messages
479   (loop with socket = (postgresql-connection-socket connection)
480         while (listen socket)
481         do
482         (case (read-socket-value 'int8 socket)
483           (#.+notice-response-message+
484            (let ((message (read-socket-value 'string socket)))
485              (warn 'postgresql-warning :connection connection
486                    :message message)))
487           (#.+notification-response-message+
488            (let ((pid (read-socket-value 'int32 socket))
489                  (message (read-socket-value 'string socket)))
490              (when (= pid (postgresql-connection-pid connection))
491                (signal 'postgresql-notification :connection connection
492                        :message message))))
493           (t
494            (close-postgresql-connection connection)
495            (error 'postgresql-fatal-error :connection connection
496                   :message "Received garbled message from backend")))))
497
498 (defun start-query-execution (connection query)
499   (ensure-open-postgresql-connection connection)
500   (process-async-messages connection)
501   (send-query-message (postgresql-connection-socket connection) query)
502   (force-output (postgresql-connection-socket connection)))
503
504 (defun wait-for-query-results (connection)
505   (assert (postgresql-connection-open-p connection))
506   (let ((socket (postgresql-connection-socket connection))
507         (cursor-name nil)
508         (error nil))
509     (loop
510         (case (read-socket-value 'int8 socket)
511           (#.+completed-response-message+
512            (return (values :completed (read-socket-value 'string socket))))
513           (#.+cursor-response-message+
514            (setq cursor-name (read-socket-value 'string socket)))
515           (#.+row-description-message+
516            (let* ((count (read-socket-value 'int16 socket))
517                   (fields
518                    (loop repeat count
519                      collect
520                      (list
521                       (read-socket-value 'string socket)
522                       (read-socket-value 'int32 socket)
523                       (read-socket-value 'int16 socket)
524                       (read-socket-value 'int32 socket)))))
525              (return
526                (values :cursor
527                        (make-postgresql-cursor :connection connection
528                                                :name cursor-name
529                                                :fields fields)))))
530           (#.+copy-in-response-message+
531            (return :copy-in))
532           (#.+copy-out-response-message+
533            (return :copy-out))
534           (#.+ready-for-query-message+
535            (when error
536              (error error))
537            (return nil))
538           (#.+error-response-message+
539            (let ((message (read-socket-value 'string socket)))
540              (setq error
541                    (make-condition 'postgresql-error
542                                    :connection connection :message message))))
543           (#.+notice-response-message+
544            (let ((message (read-socket-value 'string socket)))
545              (warn 'postgresql-warning
546                    :connection connection :message message)))
547           (#.+notification-response-message+
548            (let ((pid (read-socket-value 'int32 socket))
549                  (message (read-socket-value 'string socket)))
550              (when (= pid (postgresql-connection-pid connection))
551                (signal 'postgresql-notification :connection connection
552                        :message message))))
553           (t
554            (close-postgresql-connection connection)
555            (error 'postgresql-fatal-error :connection connection
556                   :message "Received garbled message from backend"))))))
557
558 (defun read-null-bit-vector (socket count)
559   (let ((result (make-array count :element-type 'bit)))
560     (dotimes (offset (ceiling count 8))
561       (loop with byte = (read-byte socket)
562             for index from (* offset 8) below (min count (* (1+ offset) 8))
563             for weight downfrom 7
564             do (setf (aref result index) (ldb (byte 1 weight) byte))))
565     result))
566
567
568 (defun read-field (socket type)
569   (let ((length (- (read-socket-value 'int32 socket) 4)))
570     (case type
571       ((:int32 :int64)
572        (read-integer-from-socket socket length))
573       (:double
574        (read-double-from-socket socket length))
575       (t
576        (let ((result (make-string length)))
577          (read-socket-sequence result socket)
578          result)))))
579
580 (uffi:def-constant +char-code-zero+ (char-code #\0))
581 (uffi:def-constant +char-code-minus+ (char-code #\-))
582 (uffi:def-constant +char-code-plus+ (char-code #\+))
583 (uffi:def-constant +char-code-period+ (char-code #\.))
584 (uffi:def-constant +char-code-lower-e+ (char-code #\e))
585 (uffi:def-constant +char-code-upper-e+ (char-code #\E))
586
587 (defun read-integer-from-socket (socket length)
588   (declare (fixnum length))
589   (if (zerop length)
590       nil
591     (let ((val 0)
592           (first-char (read-byte socket))
593           (minusp nil))
594       (declare (fixnum first-char))
595       (decf length) ;; read first char
596       (cond
597        ((= first-char +char-code-minus+)
598         (setq minusp t))
599        ((= first-char +char-code-plus+)
600         )               ;; nothing to do
601        (t
602         (setq val (- first-char +char-code-zero+))))
603       
604       (dotimes (i length)
605         (declare (fixnum i))
606         (setq val (+
607                    (* 10 val)
608                    (- (read-byte socket) +char-code-zero+))))
609       (if minusp
610           (- val)
611         val))))
612
613 (defmacro ascii-digit (int)
614   (let ((offset (gensym)))
615     `(let ((,offset (- ,int +char-code-zero+)))
616       (declare (fixnum ,int ,offset))
617       (if (and (>= ,offset 0)
618                (< ,offset 10))
619           ,offset
620           nil))))
621       
622 (defun read-double-from-socket (socket length)
623   (declare (fixnum length))
624   (let ((before-decimal 0)
625         (after-decimal 0)
626         (decimal-count 0)
627         (exponent 0)
628         (decimalp nil)
629         (minusp nil)
630         (result nil)
631         (char (read-byte socket)))
632     (declare (fixnum char exponent decimal-count))
633     (decf length) ;; already read first character
634     (cond
635       ((= char +char-code-minus+)
636        (setq minusp t))
637       ((= char +char-code-plus+)
638        )
639       ((= char +char-code-period+)
640        (setq decimalp t))
641       (t
642        (setq before-decimal (ascii-digit char))
643        (unless before-decimal
644          (error "Unexpected value"))))
645     
646     (block loop
647       (dotimes (i length)
648         (setq char (read-byte socket))
649         ;;      (format t "~&len:~D, i:~D, char:~D, minusp:~A, decimalp:~A" length i char minusp decimalp)
650         (let ((weight (ascii-digit char)))
651           (cond 
652            ((and weight (not decimalp)) ;; before decimal point
653             (setq before-decimal (+ weight (* 10 before-decimal))))
654            ((and weight decimalp) ;; after decimal point
655             (setq after-decimal (+ weight (* 10 after-decimal)))
656             (incf decimal-count))
657            ((and (= char +char-code-period+))
658             (setq decimalp t))
659            ((or (= char +char-code-lower-e+)          ;; E is for exponent
660                 (= char +char-code-upper-e+))
661             (setq exponent (read-integer-from-socket socket (- length i 1)))
662             (setq exponent (or exponent 0))
663             (return-from loop))
664           (t 
665            (break "Unexpected value"))
666           )
667         )))
668     (setq result (* (+ (coerce before-decimal 'double-float)
669                        (* after-decimal 
670                           (expt 10 (- decimal-count))))
671                     (expt 10 exponent)))
672     (if minusp
673         (- result)
674         result)))
675         
676       
677 #+ignore
678 (defun read-double-from-socket (socket length)
679   (let ((result (make-string length)))
680     (read-socket-sequence result socket)
681     (let ((*read-default-float-format* 'double-float))
682       (read-from-string result))))
683
684 (defun read-cursor-row (cursor types)
685   (let* ((connection (postgresql-cursor-connection cursor))
686          (socket (postgresql-connection-socket connection))
687          (fields (postgresql-cursor-fields cursor)))
688     (assert (postgresql-connection-open-p connection))
689     (loop
690         (let ((code (read-socket-value 'int8 socket)))
691           (case code
692             (#.+ascii-row-message+
693              (return
694                (loop with count = (length fields)
695                      with null-vector = (read-null-bit-vector socket count)
696                      repeat count
697                      for null-bit across null-vector
698                      for i from 0
699                      for null-p = (zerop null-bit)
700                      if null-p
701                      collect nil
702                      else
703                      collect
704                      (read-field socket (nth i types)))))
705             (#.+binary-row-message+
706              (error "NYI"))
707             (#.+completed-response-message+
708              (return (values nil (read-socket-value 'string socket))))
709             (#.+error-response-message+
710              (let ((message (read-socket-value 'string socket)))
711                (error 'postgresql-error
712                       :connection connection :message message)))
713             (#.+notice-response-message+
714              (let ((message (read-socket-value 'string socket)))
715                (warn 'postgresql-warning
716                      :connection connection :message message)))
717             (#.+notification-response-message+
718              (let ((pid (read-socket-value 'int32 socket))
719                    (message (read-socket-value 'string socket)))
720                (when (= pid (postgresql-connection-pid connection))
721                  (signal 'postgresql-notification :connection connection
722                          :message message))))
723             (t
724              (close-postgresql-connection connection)
725              (error 'postgresql-fatal-error :connection connection
726                     :message "Received garbled message from backend")))))))
727
728 (defun map-into-indexed (result-seq func seq)
729   (dotimes (i (length seq))
730     (declare (fixnum i))
731     (setf (elt result-seq i)
732           (funcall func (elt seq i) i)))
733   result-seq)
734
735 (defun copy-cursor-row (cursor sequence types)
736   (let* ((connection (postgresql-cursor-connection cursor))
737          (socket (postgresql-connection-socket connection))
738          (fields (postgresql-cursor-fields cursor)))
739     (assert (= (length fields) (length sequence)))
740     (loop
741         (let ((code (read-socket-value 'int8 socket)))
742           (case code
743             (#.+ascii-row-message+
744              (return
745                #+ignore
746                (let* ((count (length sequence))
747                       (null-vector (read-null-bit-vector socket count)))
748                  (dotimes (i count)
749                    (declare (fixnum i))
750                    (if (zerop (elt null-vector i))
751                        (setf (elt sequence i) nil)
752                        (let ((value (read-field socket (nth i types))))
753                          (setf (elt sequence i) value)))))
754                (map-into-indexed
755                 sequence
756                 #'(lambda (null-bit i)
757                     (if (zerop null-bit)
758                         nil
759                         (read-field socket (nth i types))))
760                 (read-null-bit-vector socket (length sequence)))))
761             (#.+binary-row-message+
762              (error "NYI"))
763             (#.+completed-response-message+
764              (return (values nil (read-socket-value 'string socket))))
765             (#.+error-response-message+
766              (let ((message (read-socket-value 'string socket)))
767                (error 'postgresql-error
768                       :connection connection :message message)))
769             (#.+notice-response-message+
770              (let ((message (read-socket-value 'string socket)))
771                (warn 'postgresql-warning
772                      :connection connection :message message)))
773             (#.+notification-response-message+
774              (let ((pid (read-socket-value 'int32 socket))
775                    (message (read-socket-value 'string socket)))
776                (when (= pid (postgresql-connection-pid connection))
777                  (signal 'postgresql-notification :connection connection
778                          :message message))))
779             (t
780              (close-postgresql-connection connection)
781              (error 'postgresql-fatal-error :connection connection
782                     :message "Received garbled message from backend")))))))
783
784 (defun skip-cursor-row (cursor)
785   (let* ((connection (postgresql-cursor-connection cursor))
786          (socket (postgresql-connection-socket connection))
787          (fields (postgresql-cursor-fields cursor)))
788     (loop
789         (let ((code (read-socket-value 'int8 socket)))
790           (case code
791             (#.+ascii-row-message+
792              (loop for null-bit across
793                    (read-null-bit-vector socket (length fields))
794                    do
795                    (unless (zerop null-bit)
796                      (let* ((length (read-socket-value 'int32 socket)))
797                        (loop repeat (- length 4) do (read-byte socket)))))
798              (return t))
799             (#.+binary-row-message+
800              (error "NYI"))
801             (#.+completed-response-message+
802              (return (values nil (read-socket-value 'string socket))))
803             (#.+error-response-message+
804              (let ((message (read-socket-value 'string socket)))
805                (error 'postgresql-error
806                       :connection connection :message message)))
807             (#.+notice-response-message+
808              (let ((message (read-socket-value 'string socket)))
809                (warn 'postgresql-warning
810                      :connection connection :message message)))
811             (#.+notification-response-message+
812              (let ((pid (read-socket-value 'int32 socket))
813                    (message (read-socket-value 'string socket)))
814                (when (= pid (postgresql-connection-pid connection))
815                  (signal 'postgresql-notification :connection connection
816                          :message message))))
817             (t
818              (close-postgresql-connection connection)
819              (error 'postgresql-fatal-error :connection connection
820                     :message "Received garbled message from backend")))))))
821
822 (defun run-query (connection query &optional (types nil))
823   (start-query-execution connection query)
824   (multiple-value-bind (status cursor)
825       (wait-for-query-results connection)
826     (assert (eq status :cursor))
827     (loop for row = (read-cursor-row cursor types)
828           while row
829           collect row
830           finally
831           (wait-for-query-results connection))))