r1662: field type optimizations
[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.6 2002/03/26 14:12:12 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      (:float4 700)
40      (:float8 701)))
41
42 (defmethod database-type-library-loaded ((database-type
43                                           (eql :postgresql-socket)))
44   "T if foreign library was able to be loaded successfully. Always true for
45 socket interface"
46   t)
47                                       
48
49 ;;; Message I/O stuff
50
51 (defmacro define-message-constants (description &rest clauses)
52   (assert (evenp (length clauses)))
53   (loop with seen-characters = nil
54         for (name char) on clauses by #'cddr
55         for char-code = (char-code char)
56         for doc-string = (format nil "~A (~:C): ~A" description char name)
57         if (member char seen-characters)
58         do (error "Duplicate message type ~@C for group ~A" char description)
59         else
60         collect
61         `(defconstant ,name ,char-code ,doc-string)
62         into result-clauses
63         and do (push char seen-characters)
64       finally
65         (return `(progn ,@result-clauses))))
66
67 (eval-when (:compile-toplevel :load-toplevel :execute)
68 (define-message-constants "Backend Message Constants"
69   +ascii-row-message+ #\D
70   +authentication-message+ #\R
71   +backend-key-message+ #\K
72   +binary-row-message+ #\B
73   +completed-response-message+ #\C
74   +copy-in-response-message+ #\G
75   +copy-out-response-message+ #\H
76   +cursor-response-message+ #\P
77   +empty-query-response-message+ #\I
78   +error-response-message+ #\E
79   +function-response-message+ #\V
80   +notice-response-message+ #\N
81   +notification-response-message+ #\A
82   +ready-for-query-message+ #\Z
83   +row-description-message+ #\T))
84
85 (defgeneric send-socket-value (type socket value))
86
87 (defmethod send-socket-value ((type (eql 'int32)) socket (value integer))
88   (write-byte (ldb (byte 8 24) value) socket)
89   (write-byte (ldb (byte 8 16) value) socket)
90   (write-byte (ldb (byte 8 8) value) socket)
91   (write-byte (ldb (byte 8 0) value) socket))
92
93 (defmethod send-socket-value ((type (eql 'int16)) socket (value integer))
94   (write-byte (ldb (byte 8 8) value) socket)
95   (write-byte (ldb (byte 8 0) value) socket))
96
97 (defmethod send-socket-value ((type (eql 'int8)) socket (value integer))
98   (write-byte (ldb (byte 8 0) value) socket))
99
100 (defmethod send-socket-value ((type (eql 'string)) socket (value string))
101   (loop for char across value
102         for code = (char-code char)
103         do (write-byte code socket)
104         finally (write-byte 0 socket)))
105
106 (defmethod send-socket-value ((type (eql 'limstring)) socket (value string))
107   (loop for char across value
108         for code = (char-code char)
109         do (write-byte code socket)))
110
111 (defmethod send-socket-value ((type (eql 'byte)) socket (value integer))
112   (write-byte value socket))
113
114 (defmethod send-socket-value ((type (eql 'byte)) socket (value character))
115   (write-byte (char-code value) socket))
116
117 (defmethod send-socket-value ((type (eql 'byte)) socket value)
118   (write-sequence value socket))
119
120 (defgeneric read-socket-value (type socket))
121
122 (defmethod read-socket-value ((type (eql 'int32)) socket)
123   (let ((result 0))
124     (setf (ldb (byte 8 24) result) (read-byte socket))
125     (setf (ldb (byte 8 16) result) (read-byte socket))
126     (setf (ldb (byte 8 8) result) (read-byte socket))
127     (setf (ldb (byte 8 0) result) (read-byte socket))
128     result))
129
130 (defmethod read-socket-value ((type (eql 'int16)) socket)
131   (let ((result 0))
132     (setf (ldb (byte 8 8) result) (read-byte socket))
133     (setf (ldb (byte 8 0) result) (read-byte socket))
134     result))
135
136 (defmethod read-socket-value ((type (eql 'int8)) socket)
137   (read-byte socket))
138
139 (defmethod read-socket-value ((type (eql 'string)) socket)
140   (with-output-to-string (out)
141     (loop for code = (read-byte socket)
142           until (zerop code)
143           do (write-char (code-char code) out))))
144
145 (defgeneric skip-socket-value (type socket))
146
147 (defmethod skip-socket-value ((type (eql 'int32)) socket)
148   (dotimes (i 4) (read-byte socket)))
149
150 (defmethod skip-socket-value ((type (eql 'int16)) socket)
151   (dotimes (i 2) (read-byte socket)))
152
153 (defmethod skip-socket-value ((type (eql 'int8)) socket)
154   (read-byte socket))
155
156 (defmethod skip-socket-value ((type (eql 'string)) socket)
157   (loop until (zerop (read-byte socket))))
158
159 (defmacro define-message-sender (name (&rest args) &rest clauses)
160   (loop with socket-var = (gensym)
161         for (type value) in clauses
162         collect
163         `(send-socket-value ',type ,socket-var ,value)
164         into body
165       finally
166         (return
167           `(defun ,name (,socket-var ,@args)
168              ,@body))))
169
170 (defun pad-limstring (string limit)
171   (let ((result (make-string limit :initial-element #\NULL)))
172     (loop for char across string
173           for index from 0 below limit
174           do (setf (char result index) char))
175     result))
176
177 (define-message-sender send-startup-message
178     (database user &optional (command-line "") (backend-tty ""))
179   (int32 296)                           ; Length
180   (int32 #x00020000)                    ; Version 2.0
181   (limstring (pad-limstring database 64))
182   (limstring (pad-limstring user 32))
183   (limstring (pad-limstring command-line 64))
184   (limstring (pad-limstring "" 64))     ; Unused
185   (limstring (pad-limstring backend-tty 64)))
186
187 (define-message-sender send-terminate-message ()
188   (byte #\X))
189
190 (define-message-sender send-unencrypted-password-message (password)
191   (int32 (+ 5 (length password)))
192   (string password))
193
194 (define-message-sender send-query-message (query)
195   (byte #\Q)
196   (string query))
197
198 (define-message-sender send-encrypted-password-message (crypted-password)
199   (int32 (+ 5 (length crypted-password)))
200   (string crypted-password))
201
202 (define-message-sender send-cancel-request (pid key)
203   (int32 16)                            ; Length
204   (int32 80877102)                      ; Magic
205   (int32 pid)
206   (int32 key))
207
208
209 (defun read-socket-sequence (string stream)
210 "KMR -- Added to support reading from binary stream into a string"
211   (declare (optimize (speed 3) (safety 0))
212            (string string))
213   (dotimes (i (length string))
214     (declare (fixnum i))
215     (setf (char string i) (code-char (read-byte stream))))
216   string)
217
218
219 ;;; Support for encrypted password transmission
220
221 (defconstant +crypt-library+ "/usr/lib/libcrypt.so"
222   "Name of the shared library to load in order to access the crypt
223 function named by `*crypt-function-name*'.")
224
225 (defvar *crypt-library-loaded* nil)
226
227 (defun crypt-password (password salt)
228   "Encrypt a password for transmission to a PostgreSQL server."
229   (unless *crypt-library-loaded*
230     (uffi:load-foreign-library +crypt-library+ :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       (:int
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
585 (defun read-integer-from-socket (socket length)
586   (let ((val 0)
587         (first-char (read-byte socket))
588         (minusp nil))
589     (declare (fixnum first-char))
590     (if (eql first-char +char-code-minus+)
591         (setq minusp t)
592         (setq val (- first-char +char-code-zero+)))
593     (dotimes (i (1- length))
594       (declare (fixnum i))
595       (setq val (+
596                  (* 10 val)
597                  (- (read-byte socket) +char-code-zero+))))
598     (if minusp
599         (- 0 val)
600         val)))
601
602 (defmacro ascii-digit (int)
603   (let ((offset (gensym)))
604     `(let ((,offset (- ,int +char-code-zero+)))
605       (declare (fixnum ,int ,offset))
606       (if (and (plusp ,offset)
607                (< ,offset 10))
608           ,offset
609           nil))))
610       
611 #+ignore
612 (defun read-double-from-socket (socket length)
613   (let ((before-decimal 0)
614         (after-decimal 0)
615         (decimal-count 0)
616         (exponent 0)
617         (char (read-byte socket))
618         (decimalp nil)
619         (minusp nil))
620     (declare (fixnum first-char))
621     (cond
622       ((eql char +char-code-minus+)
623        (setq minusp t)
624        (setq char (read-byte socket))
625        (decf length))
626       ((eql char +char-code-plus+)
627        (setq char (read-byte socket))
628        (decf length)))
629     
630     (dotimes (i (1- length))
631       (let ((weight (ascii-digit char)))
632         (cond 
633           ((and weight (not decimalp)) ;; before decimal point
634            (setq before-decimal (+ weight (* 10 before-decimal))))
635           ((and weight decimalp) ;; after decimal point
636            (setq after-decimal (+ weight (* 10 after-decimal)))
637            (incf decimal-count))
638           ((and (eql char +char-code-period+) decimalp)
639            (setq decimalp t))
640           ((or (eql char +char-code-e+)               ;; E is for exponent
641                (eql char +char-code-upper-e+))
642            (multiple-value-bind (num idx) 
643                (parse-integer string :start (1+ index) :end end
644                               :radix radix :junk-allowed junk-allowed)
645              (setq exponent (or num 0)
646                    index idx)
647              (when (= index end) (return nil))))
648           )
649         (setq char (read-byte socket))))
650
651           
652
653                
654       ))
655         
656       
657 (defun read-double-from-socket (socket length)
658   (let ((result (make-string length)))
659     (read-socket-sequence result socket)
660     (let ((*read-default-float-format* 'double-float))
661       (read-from-string result))))
662
663 (defun read-cursor-row (cursor types)
664   (let* ((connection (postgresql-cursor-connection cursor))
665          (socket (postgresql-connection-socket connection))
666          (fields (postgresql-cursor-fields cursor)))
667     (assert (postgresql-connection-open-p connection))
668     (loop
669         (let ((code (read-socket-value 'int8 socket)))
670           (case code
671             (#.+ascii-row-message+
672              (return
673                (loop with count = (length fields)
674                      with null-vector = (read-null-bit-vector socket count)
675                      repeat count
676                      for null-bit across null-vector
677                      for i from 0
678                      for null-p = (zerop null-bit)
679                      if null-p
680                      collect nil
681                      else
682                      collect
683                      (read-field socket (nth i types)))))
684             (#.+binary-row-message+
685              (error "NYI"))
686             (#.+completed-response-message+
687              (return (values nil (read-socket-value 'string socket))))
688             (#.+error-response-message+
689              (let ((message (read-socket-value 'string socket)))
690                (error 'postgresql-error
691                       :connection connection :message message)))
692             (#.+notice-response-message+
693              (let ((message (read-socket-value 'string socket)))
694                (warn 'postgresql-warning
695                      :connection connection :message message)))
696             (#.+notification-response-message+
697              (let ((pid (read-socket-value 'int32 socket))
698                    (message (read-socket-value 'string socket)))
699                (when (= pid (postgresql-connection-pid connection))
700                  (signal 'postgresql-notification :connection connection
701                          :message message))))
702             (t
703              (close-postgresql-connection connection)
704              (error 'postgresql-fatal-error :connection connection
705                     :message "Received garbled message from backend")))))))
706
707 (defun map-into-indexed (result-seq func seq)
708   (dotimes (i (length seq))
709     (declare (fixnum i))
710     (setf (elt result-seq i)
711           (funcall func (elt seq i) i)))
712   result-seq)
713
714 (defun copy-cursor-row (cursor sequence types)
715   (let* ((connection (postgresql-cursor-connection cursor))
716          (socket (postgresql-connection-socket connection))
717          (fields (postgresql-cursor-fields cursor)))
718     (assert (= (length fields) (length sequence)))
719     (loop
720         (let ((code (read-socket-value 'int8 socket)))
721           (case code
722             (#.+ascii-row-message+
723              (return
724                #+ignore
725                (let* ((count (length sequence))
726                       (null-vector (read-null-bit-vector socket count)))
727                  (dotimes (i count)
728                    (declare (fixnum i))
729                    (if (zerop (elt null-vector i))
730                        (setf (elt sequence i) nil)
731                        (let ((value (read-field socket (nth i types))))
732                          (setf (elt sequence i) value)))))
733                (map-into-indexed
734                 sequence
735                 #'(lambda (null-bit i)
736                     (if (zerop null-bit)
737                         nil
738                         (read-field socket (nth i types))))
739                 (read-null-bit-vector socket (length sequence)))))
740             (#.+binary-row-message+
741              (error "NYI"))
742             (#.+completed-response-message+
743              (return (values nil (read-socket-value 'string socket))))
744             (#.+error-response-message+
745              (let ((message (read-socket-value 'string socket)))
746                (error 'postgresql-error
747                       :connection connection :message message)))
748             (#.+notice-response-message+
749              (let ((message (read-socket-value 'string socket)))
750                (warn 'postgresql-warning
751                      :connection connection :message message)))
752             (#.+notification-response-message+
753              (let ((pid (read-socket-value 'int32 socket))
754                    (message (read-socket-value 'string socket)))
755                (when (= pid (postgresql-connection-pid connection))
756                  (signal 'postgresql-notification :connection connection
757                          :message message))))
758             (t
759              (close-postgresql-connection connection)
760              (error 'postgresql-fatal-error :connection connection
761                     :message "Received garbled message from backend")))))))
762
763 (defun skip-cursor-row (cursor)
764   (let* ((connection (postgresql-cursor-connection cursor))
765          (socket (postgresql-connection-socket connection))
766          (fields (postgresql-cursor-fields cursor)))
767     (loop
768         (let ((code (read-socket-value 'int8 socket)))
769           (case code
770             (#.+ascii-row-message+
771              (loop for null-bit across
772                    (read-null-bit-vector socket (length fields))
773                    do
774                    (unless (zerop null-bit)
775                      (let* ((length (read-socket-value 'int32 socket)))
776                        (loop repeat (- length 4) do (read-byte socket)))))
777              (return t))
778             (#.+binary-row-message+
779              (error "NYI"))
780             (#.+completed-response-message+
781              (return (values nil (read-socket-value 'string socket))))
782             (#.+error-response-message+
783              (let ((message (read-socket-value 'string socket)))
784                (error 'postgresql-error
785                       :connection connection :message message)))
786             (#.+notice-response-message+
787              (let ((message (read-socket-value 'string socket)))
788                (warn 'postgresql-warning
789                      :connection connection :message message)))
790             (#.+notification-response-message+
791              (let ((pid (read-socket-value 'int32 socket))
792                    (message (read-socket-value 'string socket)))
793                (when (= pid (postgresql-connection-pid connection))
794                  (signal 'postgresql-notification :connection connection
795                          :message message))))
796             (t
797              (close-postgresql-connection connection)
798              (error 'postgresql-fatal-error :connection connection
799                     :message "Received garbled message from backend")))))))
800
801 (defun run-query (connection query &optional (types nil))
802   (start-query-execution connection query)
803   (multiple-value-bind (status cursor)
804       (wait-for-query-results connection)
805     (assert (eq status :cursor))
806     (loop for row = (read-cursor-row cursor types)
807           while row
808           collect row
809           finally
810           (wait-for-query-results connection))))