r1673: *** 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.9 2002/03/27 08:09:25 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 (defconstant +crypt-library+ "/usr/lib/libcrypt.so"
223   "Name of the shared library to load in order to access the crypt
224 function named by `*crypt-function-name*'.")
225
226 (defvar *crypt-library-loaded* nil)
227
228 (defun crypt-password (password salt)
229   "Encrypt a password for transmission to a PostgreSQL server."
230   (unless *crypt-library-loaded*
231     (uffi:load-foreign-library +crypt-library+ :supporting-libaries '("c"))
232     (eval (uffi:def-function "crypt" 
233               ((key :cstring)
234                (salt :cstring))
235             :returning :cstring))
236     (setq *crypt-library-loaded* t))
237    (uffi:with-cstring (password-cstring password)
238      (uffi:with-cstring (salt-cstring salt)
239        (uffi:convert-from-cstring (crypt password-cstring salt-cstring)))))
240 ;;; Condition hierarchy
241
242 (define-condition postgresql-condition (condition)
243   ((connection :initarg :connection :reader postgresql-condition-connection)
244    (message :initarg :message :reader postgresql-condition-message))
245   (:report
246    (lambda (c stream)
247      (format stream "~@<~A occurred on connection ~A. ~:@_Reason: ~A~:@>"
248              (type-of c)
249              (postgresql-condition-connection c)
250              (postgresql-condition-message c)))))
251
252 (define-condition postgresql-error (error postgresql-condition)
253   ())
254
255 (define-condition postgresql-fatal-error (postgresql-error)
256   ())
257
258 (define-condition postgresql-login-error (postgresql-fatal-error)
259   ())
260
261 (define-condition postgresql-warning (warning postgresql-condition)
262   ())
263
264 (define-condition postgresql-notification (postgresql-condition)
265   ()
266   (:report
267    (lambda (c stream)
268      (format stream "~@<Asynchronous notification on connection ~A: ~:@_~A~:@>"
269              (postgresql-condition-connection c)
270              (postgresql-condition-message c)))))
271
272 ;;; Structures
273
274 (defstruct postgresql-connection
275   host
276   port
277   database
278   user
279   password
280   options
281   tty
282   socket
283   pid
284   key)
285
286 (defstruct postgresql-cursor
287   connection
288   name
289   fields)
290
291 ;;; Socket stuff
292
293 (defconstant +postgresql-server-default-port+ 5432
294   "Default port of PostgreSQL server.")
295
296 (defvar *postgresql-server-socket-timeout* 60
297   "Timeout in seconds for reads from the PostgreSQL server.")
298
299
300 #+cmu
301 (defun open-postgresql-socket (host port)
302   (etypecase host
303     (pathname
304      ;; Directory to unix-domain socket
305      (ext:connect-to-unix-socket
306       (namestring
307        (make-pathname :name ".s.PGSQL" :type (princ-to-string port)
308                       :defaults host))))
309     (string
310      (ext:connect-to-inet-socket host port))))
311
312 #+cmu
313 (defun open-postgresql-socket-stream (host port)
314   (system:make-fd-stream
315    (open-postgresql-socket host port)
316    :input t :output t :element-type '(unsigned-byte 8)
317    :buffering :none
318    :timeout *postgresql-server-socket-timeout*))
319
320 #+allegro
321 (defun open-postgresql-socket-stream (host port)
322   (etypecase host
323     (pathname
324      (let ((path (namestring
325                   (make-pathname :name ".s.PGSQL" :type (princ-to-string port)
326                                  :defaults host))))
327        (socket:make-socket :type :stream :address-family :file
328                            :connect :active
329                            :remote-filename path :local-filename path)))
330     (string
331      (socket:with-pending-connect
332          (mp:with-timeout (*postgresql-server-socket-timeout* (error "connect failed"))
333            (socket:make-socket :type :stream :address-family :internet
334                                :remote-port port :remote-host host
335                                :connect :active :nodelay t))))
336     ))
337
338 #+lispworks
339 (defun open-postgresql-socket-stream (host port)
340   (etypecase host
341     (pathname
342      (error "File sockets not supported on Lispworks."))
343     (string
344      (comm:open-tcp-stream host port :direction :io :element-type '(unsigned-byte 8)
345                            :read-timeout *postgresql-server-socket-timeout*))
346     ))
347
348 ;;; Interface Functions
349
350 (defun open-postgresql-connection (&key (host (cmucl-compat:required-argument))
351                                         (port +postgresql-server-default-port+)
352                                         (database (cmucl-compat:required-argument))
353                                         (user (cmucl-compat:required-argument))
354                                         options tty password)
355   "Open a connection to a PostgreSQL server with the given parameters.
356 Note that host, database and user arguments must be supplied.
357
358 If host is a pathname, it is assumed to name a directory containing
359 the local unix-domain sockets of the server, with port selecting which
360 of those sockets to open.  If host is a string, it is assumed to be
361 the name of the host running the PostgreSQL server.  In that case a
362 TCP connection to the given port on that host is opened in order to
363 communicate with the server.  In either case the port argument
364 defaults to `+postgresql-server-default-port+'.
365
366 Password is the clear-text password to be passed in the authentication
367 phase to the server.  Depending on the server set-up, it is either
368 passed in the clear, or encrypted via crypt and a server-supplied
369 salt.  In that case the alien function specified by `*crypt-library*'
370 and `*crypt-function-name*' is used for encryption.
371
372 Note that all the arguments (including the clear-text password
373 argument) are stored in the `postgresql-connection' structure, in
374 order to facilitate automatic reconnection in case of communication
375 troubles."
376   (reopen-postgresql-connection
377    (make-postgresql-connection :host host :port port
378                                :options (or options "") :tty (or tty "")
379                                :database database :user user
380                                :password (or password ""))))
381
382 (defun reopen-postgresql-connection (connection)
383   "Reopen the given PostgreSQL connection.  Closes any existing
384 connection, if it is still open."
385   (when (postgresql-connection-open-p connection)
386     (close-postgresql-connection connection))
387   (let ((socket (open-postgresql-socket-stream 
388                   (postgresql-connection-host connection)
389                   (postgresql-connection-port connection))))
390     (unwind-protect
391          (progn
392            (setf (postgresql-connection-socket connection) socket)
393            (send-startup-message socket
394                                  (postgresql-connection-database connection)
395                                  (postgresql-connection-user connection)
396                                  (postgresql-connection-options connection)
397                                  (postgresql-connection-tty connection))
398            (force-output socket)
399            (loop
400                (case (read-socket-value 'int8 socket)
401                  (#.+authentication-message+
402                   (case (read-socket-value 'int32 socket)
403                     (0 (return))
404                     ((1 2)
405                      (error 'postgresql-login-error
406                             :connection connection
407                             :message
408                             "Postmaster expects unsupported Kerberos authentication."))
409                     (3
410                      (send-unencrypted-password-message
411                       socket
412                       (postgresql-connection-password connection)))
413                     (4
414                      (let ((salt (make-string 2)))
415                        (read-socket-sequence salt socket)
416                        (send-encrypted-password-message
417                         socket
418                         (crypt-password
419                          (postgresql-connection-password connection) salt))))
420                     (t
421                      (error 'postgresql-login-error
422                             :connection connection
423                             :message
424                             "Postmaster expects unknown authentication method."))))
425                  (#.+error-response-message+
426                   (let ((message (read-socket-value 'string socket)))
427                     (error 'postgresql-login-error
428                            :connection connection :message message)))
429                  (t
430                   (error 'postgresql-login-error
431                          :connection connection
432                          :message
433                          "Received garbled message from Postmaster"))))
434            ;; Start backend communication
435            (force-output socket)
436            (loop
437                (case (read-socket-value 'int8 socket)
438                  (#.+backend-key-message+
439                   (setf (postgresql-connection-pid connection)
440                         (read-socket-value 'int32 socket)
441                         (postgresql-connection-key connection)
442                         (read-socket-value 'int32 socket)))
443                  (#.+ready-for-query-message+
444                   (setq socket nil)
445                   (return connection))
446                  (#.+error-response-message+
447                   (let ((message (read-socket-value 'string socket)))
448                     (error 'postgresql-login-error
449                            :connection connection
450                            :message message)))
451                  (#.+notice-response-message+
452                   (let ((message (read-socket-value 'string socket)))
453                     (warn 'postgresql-warning :connection connection
454                           :message message)))
455                  (t
456                   (error 'postgresql-login-error
457                          :connection connection
458                          :message
459                          "Received garbled message from Postmaster")))))
460       (when socket
461         (close socket)))))
462
463 (defun close-postgresql-connection (connection &optional abort)
464   (unless abort
465     (ignore-errors
466       (send-terminate-message (postgresql-connection-socket connection))))
467   (close (postgresql-connection-socket connection)))
468
469 (defun postgresql-connection-open-p (connection)
470   (let ((socket (postgresql-connection-socket connection)))
471     (and socket (streamp socket) (open-stream-p socket))))
472
473 (defun ensure-open-postgresql-connection (connection)
474   (unless (postgresql-connection-open-p connection)
475     (reopen-postgresql-connection connection)))
476
477 (defun process-async-messages (connection)
478   (assert (postgresql-connection-open-p connection))
479   ;; Process any asnychronous messages
480   (loop with socket = (postgresql-connection-socket connection)
481         while (listen socket)
482         do
483         (case (read-socket-value 'int8 socket)
484           (#.+notice-response-message+
485            (let ((message (read-socket-value 'string socket)))
486              (warn 'postgresql-warning :connection connection
487                    :message message)))
488           (#.+notification-response-message+
489            (let ((pid (read-socket-value 'int32 socket))
490                  (message (read-socket-value 'string socket)))
491              (when (= pid (postgresql-connection-pid connection))
492                (signal 'postgresql-notification :connection connection
493                        :message message))))
494           (t
495            (close-postgresql-connection connection)
496            (error 'postgresql-fatal-error :connection connection
497                   :message "Received garbled message from backend")))))
498
499 (defun start-query-execution (connection query)
500   (ensure-open-postgresql-connection connection)
501   (process-async-messages connection)
502   (send-query-message (postgresql-connection-socket connection) query)
503   (force-output (postgresql-connection-socket connection)))
504
505 (defun wait-for-query-results (connection)
506   (assert (postgresql-connection-open-p connection))
507   (let ((socket (postgresql-connection-socket connection))
508         (cursor-name nil)
509         (error nil))
510     (loop
511         (case (read-socket-value 'int8 socket)
512           (#.+completed-response-message+
513            (return (values :completed (read-socket-value 'string socket))))
514           (#.+cursor-response-message+
515            (setq cursor-name (read-socket-value 'string socket)))
516           (#.+row-description-message+
517            (let* ((count (read-socket-value 'int16 socket))
518                   (fields
519                    (loop repeat count
520                      collect
521                      (list
522                       (read-socket-value 'string socket)
523                       (read-socket-value 'int32 socket)
524                       (read-socket-value 'int16 socket)
525                       (read-socket-value 'int32 socket)))))
526              (return
527                (values :cursor
528                        (make-postgresql-cursor :connection connection
529                                                :name cursor-name
530                                                :fields fields)))))
531           (#.+copy-in-response-message+
532            (return :copy-in))
533           (#.+copy-out-response-message+
534            (return :copy-out))
535           (#.+ready-for-query-message+
536            (when error
537              (error error))
538            (return nil))
539           (#.+error-response-message+
540            (let ((message (read-socket-value 'string socket)))
541              (setq error
542                    (make-condition 'postgresql-error
543                                    :connection connection :message message))))
544           (#.+notice-response-message+
545            (let ((message (read-socket-value 'string socket)))
546              (warn 'postgresql-warning
547                    :connection connection :message message)))
548           (#.+notification-response-message+
549            (let ((pid (read-socket-value 'int32 socket))
550                  (message (read-socket-value 'string socket)))
551              (when (= pid (postgresql-connection-pid connection))
552                (signal 'postgresql-notification :connection connection
553                        :message message))))
554           (t
555            (close-postgresql-connection connection)
556            (error 'postgresql-fatal-error :connection connection
557                   :message "Received garbled message from backend"))))))
558
559 (defun read-null-bit-vector (socket count)
560   (let ((result (make-array count :element-type 'bit)))
561     (dotimes (offset (ceiling count 8))
562       (loop with byte = (read-byte socket)
563             for index from (* offset 8) below (min count (* (1+ offset) 8))
564             for weight downfrom 7
565             do (setf (aref result index) (ldb (byte 1 weight) byte))))
566     result))
567
568
569 (defun read-field (socket type)
570   (let ((length (- (read-socket-value 'int32 socket) 4)))
571     (case type
572       ((:int :long :longlong)
573        (read-integer-from-socket socket length))
574       (:double
575        (read-double-from-socket socket length))
576       (t
577        (let ((result (make-string length)))
578          (read-socket-sequence result socket)
579          result)))))
580
581 (uffi:def-constant +char-code-zero+ (char-code #\0))
582 (uffi:def-constant +char-code-minus+ (char-code #\-))
583 (uffi:def-constant +char-code-plus+ (char-code #\+))
584 (uffi:def-constant +char-code-period+ (char-code #\.))
585 (uffi:def-constant +char-code-lower-e+ (char-code #\e))
586 (uffi:def-constant +char-code-upper-e+ (char-code #\E))
587
588 (defun read-integer-from-socket (socket length)
589   (let ((val 0)
590         (first-char (read-byte socket))
591         (minusp nil))
592     (declare (fixnum first-char))
593     (if (zerop length)
594         nil
595         (progn
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           (dotimes (i (1- length))
604             (declare (fixnum i))
605             (setq val (+
606                        (* 10 val)
607                        (- (read-byte socket) +char-code-zero+))))
608           (if minusp
609               (- val)
610               val)))))
611
612 (defmacro ascii-digit (int)
613   (let ((offset (gensym)))
614     `(let ((,offset (- ,int +char-code-zero+)))
615       (declare (fixnum ,int ,offset))
616       (if (and (>= ,offset 0)
617                (< ,offset 10))
618           ,offset
619           nil))))
620       
621 (defun read-double-from-socket (socket length)
622   (let ((before-decimal 0)
623         (after-decimal 0)
624         (decimal-count 0)
625         (exponent 0)
626         (decimalp nil)
627         (minusp nil)
628         (result nil)
629         (char (read-byte socket)))
630     (declare (fixnum char))
631     (decf length) ;; already read first character
632     (cond
633       ((= char +char-code-minus+)
634        (setq minusp t)
635        (setq char (read-byte socket))
636        (decf length))
637       ((= char +char-code-plus+)
638        (setq char (read-byte socket))
639        (decf length)))
640     
641     (dotimes (i length)
642       (let ((weight (ascii-digit char)))
643         (cond 
644           ((and weight (not decimalp)) ;; before decimal point
645            (setq before-decimal (+ weight (* 10 before-decimal)))
646            (setq char (read-byte socket)))
647           ((and weight decimalp) ;; after decimal point
648            (setq after-decimal (+ weight (* 10 after-decimal)))
649            (incf decimal-count)
650            (setq char (read-byte socket)))
651           ((and (= char +char-code-period+))
652            (setq decimalp t)
653            (setq char (read-byte socket)))
654           ((or (= char +char-code-lower-e+)           ;; E is for exponent
655                (= char +char-code-upper-e+))
656            (setq exponent (read-integer-from-socket socket (- length i)))
657            (setq exponent (or exponent 0))
658            (setq i length))
659           (t 
660            (break "Unexpected value"))
661           )
662         ))
663     (setq result (* (+ (coerce before-decimal 'double-float)
664                        (* after-decimal 
665                           (expt 10 (- decimal-count))))
666                     (expt 10 exponent)))
667     (if minusp
668         (- result)
669         result)))
670         
671       
672 #+ignore
673 (defun read-double-from-socket (socket length)
674   (let ((result (make-string length)))
675     (read-socket-sequence result socket)
676     (let ((*read-default-float-format* 'double-float))
677       (read-from-string result))))
678
679 (defun read-cursor-row (cursor types)
680   (let* ((connection (postgresql-cursor-connection cursor))
681          (socket (postgresql-connection-socket connection))
682          (fields (postgresql-cursor-fields cursor)))
683     (assert (postgresql-connection-open-p connection))
684     (loop
685         (let ((code (read-socket-value 'int8 socket)))
686           (case code
687             (#.+ascii-row-message+
688              (return
689                (loop with count = (length fields)
690                      with null-vector = (read-null-bit-vector socket count)
691                      repeat count
692                      for null-bit across null-vector
693                      for i from 0
694                      for null-p = (zerop null-bit)
695                      if null-p
696                      collect nil
697                      else
698                      collect
699                      (read-field socket (nth i types)))))
700             (#.+binary-row-message+
701              (error "NYI"))
702             (#.+completed-response-message+
703              (return (values nil (read-socket-value 'string socket))))
704             (#.+error-response-message+
705              (let ((message (read-socket-value 'string socket)))
706                (error 'postgresql-error
707                       :connection connection :message message)))
708             (#.+notice-response-message+
709              (let ((message (read-socket-value 'string socket)))
710                (warn 'postgresql-warning
711                      :connection connection :message message)))
712             (#.+notification-response-message+
713              (let ((pid (read-socket-value 'int32 socket))
714                    (message (read-socket-value 'string socket)))
715                (when (= pid (postgresql-connection-pid connection))
716                  (signal 'postgresql-notification :connection connection
717                          :message message))))
718             (t
719              (close-postgresql-connection connection)
720              (error 'postgresql-fatal-error :connection connection
721                     :message "Received garbled message from backend")))))))
722
723 (defun map-into-indexed (result-seq func seq)
724   (dotimes (i (length seq))
725     (declare (fixnum i))
726     (setf (elt result-seq i)
727           (funcall func (elt seq i) i)))
728   result-seq)
729
730 (defun copy-cursor-row (cursor sequence types)
731   (let* ((connection (postgresql-cursor-connection cursor))
732          (socket (postgresql-connection-socket connection))
733          (fields (postgresql-cursor-fields cursor)))
734     (assert (= (length fields) (length sequence)))
735     (loop
736         (let ((code (read-socket-value 'int8 socket)))
737           (case code
738             (#.+ascii-row-message+
739              (return
740                #+ignore
741                (let* ((count (length sequence))
742                       (null-vector (read-null-bit-vector socket count)))
743                  (dotimes (i count)
744                    (declare (fixnum i))
745                    (if (zerop (elt null-vector i))
746                        (setf (elt sequence i) nil)
747                        (let ((value (read-field socket (nth i types))))
748                          (setf (elt sequence i) value)))))
749                (map-into-indexed
750                 sequence
751                 #'(lambda (null-bit i)
752                     (if (zerop null-bit)
753                         nil
754                         (read-field socket (nth i types))))
755                 (read-null-bit-vector socket (length sequence)))))
756             (#.+binary-row-message+
757              (error "NYI"))
758             (#.+completed-response-message+
759              (return (values nil (read-socket-value 'string socket))))
760             (#.+error-response-message+
761              (let ((message (read-socket-value 'string socket)))
762                (error 'postgresql-error
763                       :connection connection :message message)))
764             (#.+notice-response-message+
765              (let ((message (read-socket-value 'string socket)))
766                (warn 'postgresql-warning
767                      :connection connection :message message)))
768             (#.+notification-response-message+
769              (let ((pid (read-socket-value 'int32 socket))
770                    (message (read-socket-value 'string socket)))
771                (when (= pid (postgresql-connection-pid connection))
772                  (signal 'postgresql-notification :connection connection
773                          :message message))))
774             (t
775              (close-postgresql-connection connection)
776              (error 'postgresql-fatal-error :connection connection
777                     :message "Received garbled message from backend")))))))
778
779 (defun skip-cursor-row (cursor)
780   (let* ((connection (postgresql-cursor-connection cursor))
781          (socket (postgresql-connection-socket connection))
782          (fields (postgresql-cursor-fields cursor)))
783     (loop
784         (let ((code (read-socket-value 'int8 socket)))
785           (case code
786             (#.+ascii-row-message+
787              (loop for null-bit across
788                    (read-null-bit-vector socket (length fields))
789                    do
790                    (unless (zerop null-bit)
791                      (let* ((length (read-socket-value 'int32 socket)))
792                        (loop repeat (- length 4) do (read-byte socket)))))
793              (return t))
794             (#.+binary-row-message+
795              (error "NYI"))
796             (#.+completed-response-message+
797              (return (values nil (read-socket-value 'string socket))))
798             (#.+error-response-message+
799              (let ((message (read-socket-value 'string socket)))
800                (error 'postgresql-error
801                       :connection connection :message message)))
802             (#.+notice-response-message+
803              (let ((message (read-socket-value 'string socket)))
804                (warn 'postgresql-warning
805                      :connection connection :message message)))
806             (#.+notification-response-message+
807              (let ((pid (read-socket-value 'int32 socket))
808                    (message (read-socket-value 'string socket)))
809                (when (= pid (postgresql-connection-pid connection))
810                  (signal 'postgresql-notification :connection connection
811                          :message message))))
812             (t
813              (close-postgresql-connection connection)
814              (error 'postgresql-fatal-error :connection connection
815                     :message "Received garbled message from backend")))))))
816
817 (defun run-query (connection query &optional (types nil))
818   (start-query-execution connection query)
819   (multiple-value-bind (status cursor)
820       (wait-for-query-results connection)
821     (assert (eq status :cursor))
822     (loop for row = (read-cursor-row cursor types)
823           while row
824           collect row
825           finally
826           (wait-for-query-results connection))))