2 @c This is part of the SXEmacs Lisp Reference Manual.
3 @c Copyright (C) 2000 Electrotechnical Laboratory, JAPAN
4 @c Copyright (C) 2005 Sebastian Freundt
5 @c See the file lispref.texi for copying conditions.
6 @c Thank you Oscar Figueiredo! This file was shamelessly cloned from
8 @setfilename ../../info/postgresql.info
10 @node PostgreSQL Support, OpenSSL Support, LDAP Support, top
11 @chapter PostgreSQL Support
14 SXEmacs can be linked with PostgreSQL libpq run-time support to provide
15 relational database access from Emacs Lisp code.
17 This implementation has been successfully tested with PostgreSQL versions
21 * Building SXEmacs with PostgreSQL support::
22 * SXEmacs PostgreSQL libpq API::
23 * SXEmacs PostgreSQL libpq Examples::
27 @node Building SXEmacs with PostgreSQL support, SXEmacs PostgreSQL libpq API, ,PostgreSQL Support
28 @comment node-name, next, previous, up
29 @section Building SXEmacs with PostgreSQL support
31 SXEmacs PostgreSQL support requires linking to the PostgreSQL libpq
32 library. We have copied the short version of how to build and setup
41 mkdir /usr/local/pgsql/data
42 chown postgres /usr/local/pgsql/data
44 /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
45 /usr/local/pgsql/bin/postmaster -D /usr/local/pgsql/data >logfile 2>&1 &
48 With this installation you can try to create a database @samp{test}:
51 /usr/local/pgsql/bin/createdb test
52 /usr/local/pgsql/bin/psql test
56 If you have installed SXEmacs from one of the binary kits on
57 (@url{ftp://ftp.sxemacs.org/}), or are using an SXEmacs binary from
58 your favourite distributor, you may have SXEmacs PostgreSQL support
59 by default. @code{M-x describe-installation} will tell you if you do.
61 If you are building SXEmacs from source, you need to install PostgreSQL
62 first (see above example). On some systems, PostgreSQL will come
63 pre-installed in /usr or /usr/local. In this case, it should be
64 autodetected when you run configure.
66 If PostgreSQL is installed into its default location (for example when
67 passing no @samp{--prefix} to the configure; @file{/usr/local/pgsql} is
68 default) you must specify @code{--site-prefixes=/usr/local/pgsql} when
69 you run configure. If PostgreSQL is installed into another location,
70 use that instead of @file{/usr/local/pgsql} when specifying
71 @code{--site-prefixes}.
73 All versions of SXEmacs have been reported to work with PostgreSQL
74 versions 6.5, 7.x, and 8.x. SXEmacs Lisp support for V7.x and V8.x is
75 somewhat more extensive than support for V6.5. In particular,
76 asynchronous queries are supported.
79 @node SXEmacs PostgreSQL libpq API, SXEmacs PostgreSQL libpq Examples, Building SXEmacs with PostgreSQL support, PostgreSQL Support
80 @comment node-name, next, previous, up
81 @section SXEmacs PostgreSQL libpq API
83 The SXEmacs PostgreSQL API is intended to be a policy-free, low-level
84 binding to libpq. That is to provide all the basic functionality
85 and then let high level Lisp code decide its own policies.
87 This documentation assumes that the reader has knowledge of SQL, but
88 requires no prior knowledge of libpq.
90 There are many examples in this manual and some setup will be required.
91 In order to run most of the following examples, the following code needs
92 to be executed. The first example establishes a database connection and
93 then creates a table @samp{sxemacs_codenames} in your default database.
95 It may happen for you that this code fails. The code heavily depends
96 on your settings in @file{pg_hba.conf} (host-based access controls). On
97 the other hand, nearly all of the examples during this documentation will
98 assume that the free variable @code{P} refers to the database
103 ;; @r{establish a connection to @samp{$PGDATABASE} as @samp{$PGUSER}}
104 ;; @r{on @samp{$PGHOST} at port @samp{$PGPORT}}
105 (setq P (pq-connectdb ""))
106 @result{} #<PGconn kantdb:5432 freundt/freundt>
110 ;; @r{establish a connection to a password-protected db}
111 (setq P (pq-connectdb "password=foo234bar"))
112 @result{} #<PGconn kantdb:5432 freundt/freundt>
116 ;; @r{now create a test table}
117 (pq-exec P (concat "CREATE TABLE sxemacs_codenames"
118 " (id int, version text, codename text);"))
119 @result{} #<PGresult PGRES_COMMAND_OK - CREATE TABLE>
123 Now we transfer following data to the table created.
128 (pq-exec P "COPY sxemacs_codenames FROM stdin;")
129 (pq-put-line P "1\t22.1.0\tAlfa Romeo\n")
130 (pq-put-line P "2\t22.1.1\tAston Martin\n")
131 (pq-put-line P "3\t22.1.2\tAudi\n")
132 (pq-put-line P "4\t22.1.3\tBMW\n")
133 (pq-put-line P "5\t22.1.4\tBentley Turbo\n")
134 (pq-put-line P "\\.\n")
141 * libpq Lisp Variables::
142 * libpq Lisp Symbols and DataTypes::
143 * Synchronous Interface Functions::
144 * Asynchronous Interface Functions::
145 * Large Object Support::
146 * Other libpq Functions::
147 * Unimplemented libpq Functions::
151 @node libpq Lisp Variables, libpq Lisp Symbols and DataTypes, SXEmacs PostgreSQL libpq API, SXEmacs PostgreSQL libpq API
152 @comment node-name, next, previous, up
153 @subsection libpq Lisp Variables
155 Various Unix environment variables are used by libpq to provide defaults
156 to the many different parameters. In the SXEmacs Lisp API, these
157 environment variables are bound to Lisp variables to provide more
158 convenient access to Lisp Code. These variables are passed to the
159 backend database server during the establishment of a database
160 connection and when the @code{pq-setenv} call is made.
163 Initialized from the @code{PGHOST} environment variable. The default
168 Initialized from the @code{PGUSER} environment variable. The default
173 Initialized from the @code{PGOPTIONS} environment variable. Default
174 additional server options.
178 Initialized from the @code{PGPORT} environment variable. The default
179 TCP port to connect to.
183 Initialized from the @code{PGTTY} environment variable. The default
186 Compatibility note: Debugging TTYs are turned off in the SXEmacs Lisp
191 Initialized from the @code{PGDATABASE} environment variable. The
192 default database to connect to.
196 Initialized from the @code{PGREALM} environment variable. The default
200 @defvar pg:client-encoding
201 Initialized from the @code{PGCLIENTENCODING} environment variable. The
202 default client encoding.
204 Compatibility note: This variable is not present in non-Mule SXEmacsen.
205 This variable is not present in versions of libpq prior to 7.0.
206 In the current implementation, client encoding is equivalent to the
207 @code{file-name-coding-system} format.
212 Initialized from the @code{PGAUTHTYPE} environment variable. The
213 default authentication scheme used.
215 Compatibility note: This variable is unused in versions of libpq after
216 6.5. It is not implemented at all in the SXEmacs Lisp binding.
220 Initialized from the @code{PGGEQO} environment variable. Genetic
224 @defvar pg:cost-index
225 Initialized from the @code{PGCOSTINDEX} environment variable. Cost
230 Initialized from the @code{PGCOSTHEAP} environment variable. Cost heap
235 Initialized from the @code{PGTZ} environment variable. Default
239 @defvar pg:date-style
240 Initialized from the @code{PGDATESTYLE} environment variable. Default
241 date style in returned date objects.
244 @defvar pg-coding-system
245 This is a variable controlling which coding system is used to encode
246 non-ASCII strings sent to the database.
248 Compatibility Note: This variable is not present in InfoDock.
252 @node libpq Lisp Symbols and DataTypes, Synchronous Interface Functions, libpq Lisp Variables, SXEmacs PostgreSQL libpq API
253 @comment node-name, next, previous, up
254 @subsection libpq Lisp Symbols and Datatypes
256 The following set of symbols are used to represent the intermediate
257 states involved in the asynchronous interface.
259 @defvr {Symbol} pgres::polling-failed
260 Undocumented. A fatal error has occurred during processing of an
261 asynchronous operation.
264 @defvr {Symbol} pgres::polling-reading
265 An intermediate status return during an asynchronous operation. It
266 indicates that one may use @code{select} before polling again.
269 @defvr {Symbol} pgres::polling-writing
270 An intermediate status return during an asynchronous operation. It
271 indicates that one may use @code{select} before polling again.
274 @defvr {Symbol} pgres::polling-ok
275 An asynchronous operation has successfully completed.
278 @defvr {Symbol} pgres::polling-active
279 An intermediate status return during an asynchronous operation. One can
280 call the poll function again immediately.
283 @defun pq-pgconn conn field
284 @var{conn} A database connection object.
285 @var{field} A symbol indicating which field of PGconn to fetch. Possible
286 values are shown in the following table.
293 Database user's password
295 Hostname database server is running on
297 TCP port number used in the connection
301 Compatibility note: Debugging TTYs are not used in the SXEmacs Lisp API.
303 Additional server options
305 Connection status. Possible return values are shown in the following
308 @item pg::connection-ok
309 The normal, connected status.
310 @item pg::connection-bad
311 The connection is not open and the PGconn object needs to be deleted by
313 @item pg::connection-started
314 An asynchronous connection has been started, but is not yet complete.
315 @item pg::connection-made
316 An asynchronous connect has been made, and there is data waiting to be sent.
317 @item pg::connection-awaiting-response
318 Awaiting data from the backend during an asynchronous connection.
319 @item pg::connection-auth-ok
320 Received authentication, waiting for the backend to start up.
321 @item pg::connection-setenv
322 Negotiating environment during an asynchronous connection.
324 @item pq::error-message
325 The last error message that was delivered to this connection.
326 @item pq::backend-pid
327 The process ID of the backend database server.
329 The SSL session of the database connection, @code{nil} for none.
333 The @code{PGresult} object is used by libpq to encapsulate the results
334 of queries. The printed representation takes on four forms. When the
335 PGresult object contains tuples from an SQL @code{SELECT} it will look
339 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
340 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
343 The number in brackets indicates how many rows of data are available.
344 When the PGresult object is the result of a command query that doesn't
345 return anything, it will look like:
348 (pq-exec P "CREATE TABLE a_new_table (i int);")
349 @result{} #<PGresult PGRES_COMMAND_OK - CREATE>
352 When either the query is a command-type query that can affect a number
353 of different rows, but doesn't return any of them it will look like:
357 (pq-exec P "INSERT INTO a_new_table VALUES (1);")
358 (pq-exec P "INSERT INTO a_new_table VALUES (2);")
359 (pq-exec P "INSERT INTO a_new_table VALUES (3);")
360 (setq R (pq-exec P "DELETE FROM a_new_table;")))
361 @result{} #<PGresult PGRES_COMMAND_OK[3] - DELETE 3>
364 Lastly, when the underlying PGresult object has been deallocated
365 directly by @code{pq-clear} the printed representation will look like:
369 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
372 @result{} #<PGresult DEAD>
375 The following set of functions are accessors to various data in the PGresult
378 @defun pq-result-status result
379 Return status of a query result.
380 @var{result} is a PGresult object. The return value is one of the
381 symbols in the following table.
383 @item pgres::empty-query
384 A query contained no text. This is usually the result of a recoverable
385 error, or a minor programming error.
386 @item pgres::command-ok
387 A query command that doesn't return anything was executed properly by
389 @item pgres::tuples-ok
390 A query command that returns tuples was executed properly by the
392 @item pgres::copy-out
393 Copy Out data transfer is in progress.
395 Copy In data transfer is in progress.
396 @item pgres::bad-response
397 An unexpected response was received from the backend.
398 @item pgres::nonfatal-error
399 Undocumented. This value is returned when the libpq function
400 @code{PQresultStatus} is called with a @code{NULL} pointer.
401 @item pgres::fatal-error
402 Undocumented. An error has occurred in processing the query and the
403 operation was not completed.
407 @defun pq-res-status result
408 Return the query result status as a string, not a symbol.
409 @var{result} is a PGresult object.
412 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
413 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
415 @result{} "PGRES_TUPLES_OK"
419 @defun pq-result-error-message result
420 Return an error message generated by the query, if any.
421 @var{result} is a PGresult object.
424 (setq R (pq-exec P "SELECT * FROM sxemacs-codenames;"))
425 @result{} <A fatal error is signaled in the echo area>
426 (pq-result-error-message R)
427 @result{} "ERROR: parser: parse error at or near \"-\""
431 @defun pq-ntuples result
432 Return the number of tuples in the query result.
433 @var{result} is a PGresult object.
436 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
437 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
443 @defun pq-nfields result
444 Return the number of fields in each tuple of the query result.
445 @var{result} is a PGresult object.
448 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
449 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
455 @defun pq-binary-tuples result
456 Returns t if binary tuples are present in the results, nil otherwise.
457 @var{result} is a PGresult object.
460 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
461 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
467 @defun pq-fname result field-index
468 Returns the name of a specific field.
469 @var{result} is a PGresult object.
470 @var{field-index} is the number of the column to select from. The first
471 column is number zero.
475 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
476 (setq i (pq-nfields R))
477 (while (>= (decf i) 0)
478 (push (pq-fname R i) l))
480 @result{} ("id" "version" "codename")
484 @defun pq-fnumber result field-name
485 Return the field number corresponding to the given field name.
486 -1 is returned on a bad field name.
487 @var{result} is a PGresult object.
488 @var{field-name} is a string representing the field name to find.
490 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
491 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
494 (pq-fnumber R "Not a field")
499 @defun pq-ftype result field-num
500 Return an integer code representing the data type of the specified column.
501 @var{result} is a PGresult object.
502 @var{field-num} is the field number.
504 The return value of this function is the Object ID (Oid) in the database
505 of the type. Further queries need to be made to various system tables
506 in order to convert this value into something useful.
509 @defun pq-fmod result field-num
510 Return the type modifier code associated with a field. Field numbers
512 @var{result} is a PGresult object.
513 @var{field-index} selects which field to use.
516 @defun pq-fsize result field-index
517 Return size of the given field.
518 @var{result} is a PGresult object.
519 @var{field-index} selects which field to use.
523 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
524 (setq i (pq-nfields R))
525 (while (>= (decf i) 0)
526 (push (list (pq-ftype R i) (pq-fsize R i)) l))
528 @result{} ((23 23) (25 25) (25 25))
532 @defun pq-get-value result tup-num field-num
533 Retrieve a return value.
534 @var{result} is a PGresult object.
535 @var{tup-num} selects which tuple to fetch from.
536 @var{field-num} selects which field to fetch from.
538 Both tuples and fields are numbered from zero.
541 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
542 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
548 @result{} "Aston Martin"
552 @defun pq-get-length result tup-num field-num
553 Return the length of a specific value.
554 @var{result} is a PGresult object.
555 @var{tup-num} selects which tuple to fetch from.
556 @var{field-num} selects which field to fetch from.
559 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;"))
560 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
561 (pq-get-length R 0 1)
563 (pq-get-length R 1 1)
565 (pq-get-length R 1 2)
570 @defun pq-get-is-null result tup-num field-num
571 Return t if the specific value is the SQL @code{NULL}.
572 @var{result} is a PGresult object.
573 @var{tup-num} selects which tuple to fetch from.
574 @var{field-num} selects which field to fetch from.
577 @defun pq-cmd-status result
578 Return a summary string from the query.
579 @var{result} is a PGresult object.
581 @comment This example was written on day 3 of the 2000 Haru Basho.
582 (setq R (pq-exec P "INSERT INTO sxemacs_codenames
583 VALUES (6, '22.1.5', 'Bugatto');"))
584 @result{} #<PGresult PGRES_COMMAND_OK[1] - INSERT 542086 1>
586 @result{} "INSERT 2069411 1"
587 (setq R (pq-exec P "UPDATE sxemacs_codenames SET codename='Bugatti'
588 WHERE version='22.1.5';"))
589 @result{} #<PGresult PGRES_COMMAND_OK[1] - UPDATE 1>
594 Note that the first number returned from an insertion, like in the
595 example, is an object ID number and will almost certainly vary from
596 system to system since object ID numbers in Postgres must be unique
597 across all databases.
600 @defun pq-cmd-tuples result
601 Return the number of tuples if the last command was an INSERT/UPDATE/DELETE.
602 If the last command was something else, the empty string is returned.
603 @var{result} is a PGresult object.
606 (setq R (pq-exec P "INSERT INTO sxemacs_codenames VALUES
607 (7, '22.1.6', 'Cadillac');"))
608 @result{} #<PGresult PGRES_COMMAND_OK[1] - INSERT 38688 1>
611 (setq R (pq-exec P "SELECT * from sxemacs_codenames;"))
612 @result{} #<PGresult PGRES_TUPLES_OK[7] - SELECT>
615 (setq R (pq-exec P "DELETE FROM sxemacs_codenames
616 WHERE codename LIKE '%urbo';"))
617 @result{} #<PGresult PGRES_COMMAND_OK[1] - DELETE 1>
623 @defun pq-oid-value result
624 Return the object id of the insertion if the last command was an INSERT.
625 0 is returned if the last command was not an insertion.
626 @var{result} is a PGresult object.
628 In the first example, the numbers you will see on your local system will
629 almost certainly be different, however the second number from the right
630 in the unprintable PGresult object and the number returned by
631 @code{pq-oid-value} should match.
633 (setq R (pq-exec P "INSERT INTO sxemacs_codenames VALUES
634 (8, '22.1.7', 'Celica');"))
635 @result{} #<PGresult PGRES_COMMAND_OK[1] - INSERT 542089 1>
638 (setq R (pq-exec P "SELECT version FROM sxemacs_codenames
639 WHERE codename='Bugatti';"))
640 @result{} #<PGresult PGRES_TUPLES_OK[1] - SELECT>
646 @defun pq-make-empty-pgresult conn status
647 Create an empty pgresult with the given status.
648 @var{conn} a database connection object
649 @var{status} a value that can be returned by @code{pq-result-status}.
651 The caller is responsible for making sure the return value gets properly
656 @node Synchronous Interface Functions, Asynchronous Interface Functions, libpq Lisp Symbols and DataTypes, SXEmacs PostgreSQL libpq API
657 @comment node-name, next, previous, up
658 @subsection Synchronous Interface Functions
660 @defun pq-connectdb conninfo
661 Establish a (synchronous) database connection.
662 @var{conninfo} A string of blank separated options. Options are of the
663 form ``@var{option} = @var{value}''. If @var{value} contains blanks, it
664 must be single quoted. Blanks around the equal sign are optional.
665 Multiple option assignments are blank separated.
667 (pq-connectdb "dbname=kantdb port=5432")
668 @result{} #<PGconn kantdb:5432 freundt/freundt>
670 The printed representation of a database connection object has four
671 fields. The first field is the hostname where the database server is
672 running (in this case localhost), the second field is the port number,
673 the third field is the database user name, and the fourth field is the
674 name of the database.
676 Database connection objects which have been disconnected and will
677 generate an immediate error if they are used look like:
681 Bad connections can be reestablished with @code{pq-reset}, or deleted
682 entirely with @code{pq-finish}.
684 A database connection object that has been deleted looks like:
686 (let ((P1 (pq-connectdb "")))
689 @result{} #<PGconn DEAD>
692 Note that database connection objects are the most heavy weight objects
693 in SXEmacs Lisp at this writing, usually representing as much as several
694 megabytes of virtual memory on the machine the database server is
695 running on. It is wisest to explicitly delete them when you are
696 finished with them, rather than letting garbage collection do it. An
700 (let ((P (pq-connectiondb "")))
703 (...)) ; access database here
707 The following options are available in the options string:
710 Authentication type. Same as @code{PGAUTHTYPE}. This is no longer used.
712 Database user name. Same as @code{PGUSER}.
716 Database name. Same as @code{PGDATABASE}
718 Symbolic hostname. Same as @code{PGHOST}.
720 Host address as four octets (eg. like 192.168.1.1).
722 TCP port to connect to. Same as @code{PGPORT}.
724 Debugging TTY. Same as @code{PGTTY}. This value is suppressed in the
727 Extra backend database options. Same as @code{PGOPTIONS}.
729 A database connection object is returned regardless of whether a
730 connection was established or not.
734 Reestablish database connection.
735 @var{conn} A database connection object.
737 This function reestablishes a database connection using the original
738 connection parameters. This is useful if something has happened to the
739 TCP link and it has become broken.
742 @defun pq-exec conn query
743 Make a synchronous database query.
744 @var{conn} A database connection object.
745 @var{query} A string containing an SQL query.
746 A PGresult object is returned, which in turn may be queried by its many
747 accessor functions to retrieve state out of it. If the query string
748 contains multiple SQL commands, only results from the final command are
752 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames;
753 DELETE FROM sxemacs_codenames WHERE id=8;"))
754 @result{} #<PGresult PGRES_COMMAND_OK[1] - DELETE 1>
758 @defun pq-notifies conn
759 Return the latest async notification that has not yet been handled.
760 @var{conn} A database connection object.
761 If there has been a notification, then a list of two elements will be returned.
762 The first element contains the relation name being notified, the second
763 element contains the backend process ID number. nil is returned if there
764 aren't any notifications to process.
768 Synchronous transfer of environment variables to a backend
769 @var{conn} A database connection object.
771 Environment variable transfer is done as a normal part of database
774 Compatibility note: This function was present but not documented in versions
775 of libpq prior to 7.0.
779 @node Asynchronous Interface Functions, Large Object Support, Synchronous Interface Functions, SXEmacs PostgreSQL libpq API
780 @comment node-name, next, previous, up
781 @subsection Asynchronous Interface Functions
783 Making command by command examples is too complex with the asynchronous
784 interface functions. See the examples section for complete calling
787 @defun pq-connect-start conninfo
788 Begin establishing an asynchronous database connection.
789 @var{conninfo} A string containing the connection options. See the
790 documentation of @code{pq-connectdb} for a listing of all the available
794 @defun pq-connect-poll conn
795 An intermediate function to be called during an asynchronous database
797 @var{conn} A database connection object.
798 The result codes are documented in a previous section.
801 @defun pq-is-busy conn
802 Returns t if @code{pq-get-result} would block waiting for input.
803 @var{conn} A database connection object.
806 @defun pq-consume-input conn
807 Consume any available input from the backend.
808 @var{conn} A database connection object.
810 Nil is returned if anything bad happens.
813 @defun pq-reset-start conn
814 Reset connection to the backend asynchronously.
815 @var{conn} A database connection object.
818 @defun pq-reset-poll conn
819 Poll an asynchronous reset for completion
820 @var{conn} A database connection object.
823 @defun pq-reset-cancel conn
824 Attempt to request cancellation of the current operation.
825 @var{conn} A database connection object.
827 The return value is t if the cancel request was successfully
828 dispatched, nil if not (in which case conn->errorMessage is set).
829 Note: successful dispatch is no guarantee that there will be any effect at
830 the backend. The application must read the operation result as usual.
833 @defun pq-send-query conn query
834 Submit a query to Postgres and don't wait for the result.
835 @var{conn} A database connection object.
836 Returns: t if successfully submitted
837 nil if error (conn->errorMessage is set)
840 @defun pq-get-result conn
841 Retrieve an asynchronous result from a query.
842 @var{conn} A database connection object.
844 @code{nil} is returned when no more query work remains.
847 @defun pq-set-nonblocking conn arg
848 Sets the PGconn's database connection non-blocking if the arg is TRUE
849 or makes it non-blocking if the arg is FALSE, this will not protect
850 you from PQexec(), you'll only be safe when using the non-blocking API.
851 @var{conn} A database connection object.
854 @defun pq-is-nonblocking conn
855 Return the blocking status of the database connection
856 @var{conn} A database connection object.
860 Force the write buffer to be written (or at least try)
861 @var{conn} A database connection object.
864 @defun PQsetenvStart conn
865 Start asynchronously passing environment variables to a backend.
866 @var{conn} A database connection object.
868 Compatibility note: this function is only available with libpq-7.0.
871 @defun PQsetenvPoll conn
872 Check an asynchronous environment variables transfer for completion.
873 @var{conn} A database connection object.
875 Compatibility note: this function is only available with libpq-7.0.
878 @defun PQsetenvAbort conn
879 Attempt to terminate an asynchronous environment variables transfer.
880 @var{conn} A database connection object.
882 Compatibility note: this function is only available with libpq-7.0.
886 @node Large Object Support, Other libpq Functions, Asynchronous Interface Functions, SXEmacs PostgreSQL libpq API
887 @comment node-name, next, previous, up
888 @subsection Large Object Support
890 @defun pq-lo-import conn filename
891 Import a file as a large object into the database.
892 @var{conn} a database connection object
893 @var{filename} filename to import
895 On success, the object id is returned.
898 @defun pq-lo-export conn oid filename
899 Copy a large object in the database into a file.
900 @var{conn} a database connection object.
901 @var{oid} object id number of a large object.
902 @var{filename} filename to export to.
906 @node Other libpq Functions, Unimplemented libpq Functions, Large Object Support, SXEmacs PostgreSQL libpq API
907 @comment node-name, next, previous, up
908 @subsection Other libpq Functions
910 @defun pq-finish conn
911 Destroy a database connection object by calling free on it.
912 @var{conn} a database connection object
914 It is possible to not call this routine because the usual SXEmacs garbage
915 collection mechanism will call the underlying libpq routine whenever it
916 is releasing stale @code{PGconn} objects. However, this routine is
917 useful in @code{unwind-protect} clauses to make connections go away
918 quickly when unrecoverable errors have occurred.
920 After calling this routine, the printed representation of the SXEmacs
921 wrapper object will contain the string ``DEAD''.
924 @defun pq-client-encoding conn
925 Return the client encoding as an integer code.
926 @var{conn} a database connection object
929 (pq-client-encoding P)
933 Compatibility note: This function did not exist prior to libpq-7.0 and
934 does not exist in a non-Mule SXEmacs.
937 @defun pq-set-client-encoding conn encoding
938 Set client coding system.
939 @var{conn} a database connection object
940 @var{encoding} a string representing the desired coding system
943 (pq-set-client-encoding P "EUC_JP")
947 The current idiom for ensuring proper coding system conversion is the
948 following (illustrated for EUC Japanese encoding):
950 (setq P (pq-connectdb "..."))
951 (let ((file-name-coding-system 'euc-jp)
952 (pg-coding-system 'euc-jp))
953 (pq-set-client-encoding "EUC_JP")
957 Compatibility note: This function did not exist prior to libpq-7.0 and
958 does not exist in a non-Mule SXEmacs.
961 @defun pq-env-2-encoding
962 Return the integer code representing the coding system in
963 @code{PGCLIENTENCODING}.
969 Compatibility note: This function did not exist prior to libpq-7.0 and
970 does not exist in a non-Mule SXEmacs.
974 Destroy a query result object by calling free() on it.
975 @var{res} a query result object
977 Note: The memory allocation systems of libpq and SXEmacs are different.
978 The SXEmacs representation of a query result object will have both the
979 SXEmacs version and the libpq version freed at the next garbage collection
980 when the object is no longer being referenced. Calling this function does
981 not release the SXEmacs object, it is still subject to the usual rules for
982 Lisp objects. The printed representation of the SXEmacs object will contain
983 the string ``DEAD'' after this routine is called indicating that it is no
984 longer useful for anything.
987 @defun pq-conn-defaults
988 Return a data structure that represents the connection defaults.
989 The data is returned as a list of lists, where each sublist contains
990 info regarding a single option.
994 @node Unimplemented libpq Functions, , Other libpq Functions, SXEmacs PostgreSQL libpq API
995 @comment node-name, next, previous, up
996 @subsection Unimplemented libpq Functions
998 @deftypefn {Unimplemented Function} PGconn *PQsetdbLogin (char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName, char *login, char *pwd)
999 Synchronous database connection.
1000 @var{pghost} is the hostname of the PostgreSQL backend to connect to.
1001 @var{pgport} is the TCP port number to use.
1002 @var{pgoptions} specifies other backend options.
1003 @var{pgtty} specifies the debugging tty to use.
1004 @var{dbName} specifies the database name to use.
1005 @var{login} specifies the database user name.
1006 @var{pwd} specifies the database user's password.
1008 This routine is deprecated as of libpq-7.0, and its functionality can be
1009 replaced by external Lisp code if needed.
1012 @deftypefn {Unimplemented Function} PGconn *PQsetdb (char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName)
1013 Synchronous database connection.
1014 @var{pghost} is the hostname of the PostgreSQL backend to connect to.
1015 @var{pgport} is the TCP port number to use.
1016 @var{pgoptions} specifies other backend options.
1017 @var{pgtty} specifies the debugging tty to use.
1018 @var{dbName} specifies the database name to use.
1020 This routine was deprecated in libpq-6.5.
1023 @deftypefn {Unimplemented Function} int PQsocket (PGconn *conn)
1024 Return socket file descriptor to a backend database process.
1025 @var{conn} database connection object.
1028 @deftypefn {Unimplemented Function} void PQprint (FILE *fout, PGresult *res, PGprintOpt *ps)
1029 Print out the results of a query to a designated C stream.
1030 @var{fout} C stream to print to
1031 @var{res} the query result object to print
1032 @var{ps} the print options structure.
1034 This routine is deprecated as of libpq-7.0 and cannot be sensibly exported
1038 @deftypefn {Unimplemented Function} void PQdisplayTuples (PGresult *res, FILE *fp, int fillAlign, char *fieldSep, int printHeader, int quiet)
1039 @var{res} query result object to print
1040 @var{fp} C stream to print to
1041 @var{fillAlign} pad the fields with spaces
1042 @var{fieldSep} field separator
1043 @var{printHeader} display headers?
1046 This routine was deprecated in libpq-6.5.
1049 @deftypefn {Unimplemented Function} void PQprintTuples (PGresult *res, FILE *fout, int printAttName, int terseOutput, int width)
1050 @var{res} query result object to print
1051 @var{fout} C stream to print to
1052 @var{printAttName} print attribute names
1053 @var{terseOutput} delimiter bars
1054 @var{width} width of column, if 0, use variable width
1056 This routine was deprecated in libpq-6.5.
1059 @deftypefn {Unimplemented Function} int PQmblen (char *s, int encoding)
1060 Determine length of a multibyte encoded char at @code{*s}.
1061 @var{s} encoded string
1062 @var{encoding} type of encoding
1064 Compatibility note: This function was introduced in libpq-7.0.
1067 @deftypefn {Unimplemented Function} void PQtrace (PGconn *conn, FILE *debug_port)
1068 Enable tracing on @code{debug_port}.
1069 @var{conn} database connection object.
1070 @var{debug_port} C output stream to use.
1073 @deftypefn {Unimplemented Function} void PQuntrace (PGconn *conn)
1075 @var{conn} database connection object.
1078 @deftypefn {Unimplemented Function} char *PQoidStatus (PGconn *conn)
1079 Return the object id as a string of the last tuple inserted.
1080 @var{conn} database connection object.
1082 Compatibility note: This function is deprecated since libpq-7.0, however it
1083 is used internally by the SXEmacs binding code when linked against versions
1087 @deftypefn {Unimplemented Function} PGresult *PQfn (PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, PQArgBlock *args, int nargs)
1088 ``Fast path'' interface --- not really recommended for application use
1089 @var{conn} A database connection object.
1098 The following set of very low level large object functions aren't
1099 appropriate to be exported to Lisp.
1101 @deftypefn {Unimplemented Function} int pq-lo-open (PGconn *conn, int lobjid, int mode)
1102 @var{conn} a database connection object.
1103 @var{lobjid} a large object ID.
1104 @var{mode} opening modes.
1107 @deftypefn {Unimplemented Function} int pq-lo-close (PGconn *conn, int fd)
1108 @var{conn} a database connection object.
1109 @var{fd} a large object file descriptor
1112 @deftypefn {Unimplemented Function} int pq-lo-read (PGconn *conn, int fd, char *buf, int len)
1113 @var{conn} a database connection object.
1114 @var{fd} a large object file descriptor.
1115 @var{buf} buffer to read into.
1116 @var{len} size of buffer.
1119 @deftypefn {Unimplemented Function} int pq-lo-write (PGconn *conn, int fd, char *buf, size_t len)
1120 @var{conn} a database connection object.
1121 @var{fd} a large object file descriptor.
1122 @var{buf} buffer to write from.
1123 @var{len} size of buffer.
1126 @deftypefn {Unimplemented Function} int pq-lo-lseek (PGconn *conn, int fd, int offset, int whence)
1127 @var{conn} a database connection object.
1128 @var{fd} a large object file descriptor.
1133 @deftypefn {Unimplemented Function} int pq-lo-creat (PGconn *conn, int mode)
1134 @var{conn} a database connection object.
1135 @var{mode} opening modes.
1138 @deftypefn {Unimplemented Function} int pq-lo-tell (PGconn *conn, int fd)
1139 @var{conn} a database connection object.
1140 @var{fd} a large object file descriptor.
1143 @deftypefn {Unimplemented Function} int pq-lo-unlink (PGconn *conn, int lobjid)
1144 @var{conn} a database connection object.
1145 @var{lbojid} a large object ID.
1149 @node SXEmacs PostgreSQL libpq Examples, , SXEmacs PostgreSQL libpq API, PostgreSQL Support
1150 @comment node-name, next, previous, up
1151 @section SXEmacs PostgreSQL libpq Examples
1153 This is an example of one method of establishing an asynchronous
1157 (defun database-poller (P)
1158 (message "%S before poll" (pq-pgconn P 'pq::status))
1160 (message "%S after poll" (pq-pgconn P 'pq::status))
1161 (if (eq (pq-pgconn P 'pq::status) 'pg::connection-ok)
1163 (add-timeout .1 'database-poller P)))
1164 @result{} database-poller
1166 (setq P (pq-connect-start ""))
1167 (add-timeout .1 'database-poller P))
1168 @result{} pg::connection-started before poll
1169 @result{} pg::connection-made after poll
1170 @result{} pg::connection-made before poll
1171 @result{} pg::connection-awaiting-response after poll
1172 @result{} pg::connection-awaiting-response before poll
1173 @result{} pg::connection-auth-ok after poll
1174 @result{} pg::connection-auth-ok before poll
1175 @result{} pg::connection-setenv after poll
1176 @result{} pg::connection-setenv before poll
1177 @result{} pg::connection-ok after poll
1180 @result{} #<PGconn kantdb:5432 freundt/freundt>
1183 Here is an example of one method of doing an asynchronous reset.
1186 (defun database-poller (P)
1188 (message "%S before poll" (pq-pgconn P 'pq::status))
1189 (setq PS (pq-reset-poll P))
1190 (message "%S after poll [%S]" (pq-pgconn P 'pq::status) PS)
1191 (if (eq (pq-pgconn P 'pq::status) 'pg::connection-ok)
1193 (add-timeout .1 'database-poller P))))
1194 @result{} database-poller
1197 (add-timeout .1 'database-poller P))
1198 @result{} pg::connection-started before poll
1199 @result{} pg::connection-made after poll [pgres::polling-writing]
1200 @result{} pg::connection-made before poll
1201 @result{} pg::connection-awaiting-response after poll [pgres::polling-reading]
1202 @result{} pg::connection-awaiting-response before poll
1203 @result{} pg::connection-setenv after poll [pgres::polling-reading]
1204 @result{} pg::connection-setenv before poll
1205 @result{} pg::connection-ok after poll [pgres::polling-ok]
1208 @result{} #<PGconn kantdb:5432 freundt/freundt>
1211 And finally, an asynchronous query.
1214 (defun database-poller (P)
1216 (pq-consume-input P)
1218 (add-timeout .1 'database-poller P)
1219 (setq R (pq-get-result P))
1222 (push R result-list)
1223 (add-timeout .1 'database-poller P))))))
1224 @result{} database-poller
1225 (when (pq-send-query P "SELECT * FROM sxemacs_codenames;")
1226 (setq result-list nil)
1227 (add-timeout .1 'database-poller P))
1231 @result{} (#<PGresult PGRES_TUPLES_OK[7] - SELECT>)
1234 Here is an example showing how multiple SQL statements in a single query
1235 can have all their results collected.
1237 ;; Using the same @code{database-poller} function from the previous example
1238 (when (pq-send-query P "SELECT * FROM sxemacs_codenames;
1239 SELECT * FROM pg_database;
1240 SELECT * FROM pg_user;")
1241 (setq result-list nil)
1242 (add-timeout .1 'database-poller P))
1246 @result{} (#<PGresult PGRES_TUPLES_OK[8] - SELECT> #<PGresult PGRES_TUPLES_OK[10] - SELECT> #<PGresult PGRES_TUPLES_OK[7] - SELECT>)
1249 Here is an example which illustrates collecting all data from a query,
1250 including the field names.
1253 (defun pg-util-query-results (results)
1254 "Retrieve results of last SQL query into a list structure."
1255 (let ((i (1- (pq-ntuples R)))
1258 (setq j (1- (pq-nfields R)))
1261 (push (pq-get-value R i j) l2)
1265 (setq j (1- (pq-nfields R)))
1268 (push (pq-fname R j) l2)
1272 @result{} pg-util-query-results
1273 (setq R (pq-exec P "SELECT * FROM sxemacs_codenames ORDER BY codename DESC;"))
1274 @result{} #<PGresult PGRES_TUPLES_OK[7] - SELECT>
1275 (pg-util-query-results R)
1276 @result{} (("id" "version" "codename") ("8" "22.1.7" "Celica") ("7" "22.1.6" "Cadillac") ("6" "22.1.5" "Bugatti") ("4" "22.1.3" "BMW") ("3" "22.1.2" "Audi") ("2" "22.1.1" "Aston Martin") ("1" "22.1.0" "Alfa Romeo"))
1279 Here is an example of a query that uses a database cursor.
1283 (setq R (pq-exec P "BEGIN;"))
1284 (setq R (pq-exec P "DECLARE k_cursor CURSOR FOR SELECT * FROM sxemacs_codenames ORDER BY version DESC;"))
1286 (setq R (pq-exec P "FETCH k_cursor;"))
1287 (while (eq (pq-ntuples R) 1)
1288 (push (list (pq-get-value R 0 0) (pq-get-value R 0 1)) data)
1289 (setq R (pq-exec P "FETCH k_cursor;")))
1290 (setq R (pq-exec P "END;"))
1292 @result{} (("1" "22.1.0") ("2" "22.1.1") ("3" "22.1.2") ("4" "22.1.3") ("6" "22.1.5") ("7" "22.1.6") ("8" "22.1.7"))
1295 Here's another example of cursors, this time with a Lisp macro to
1296 implement a mapping function over a table.
1299 (defmacro map-db (P table condition callout)
1301 (pq-exec ,P "BEGIN;")
1302 (pq-exec ,P (concat "DECLARE k_cursor CURSOR FOR SELECT * FROM "
1306 " ORDER BY codename DESC;"))
1307 (setq R (pq-exec P "FETCH k_cursor;"))
1308 (while (eq (pq-ntuples R) 1)
1309 (,callout (pq-get-value R 0 0) (pq-get-value R 0 1))
1310 (setq R (pq-exec P "FETCH k_cursor;")))
1311 (pq-exec P "END;")))
1313 (defun callback (arg1 arg2)
1314 (message "arg1 = %s, arg2 = %s" arg1 arg2))
1316 (map-db P "sxemacs_codenames" "WHERE version > '22.1.0'" callback)
1317 @result{} arg1 = 8, arg2 = 22.1.7
1318 @result{} arg1 = 7, arg2 = 22.1.6
1319 @result{} arg1 = 6, arg2 = 22.1.5
1320 @result{} arg1 = 4, arg2 = 22.1.3
1321 @result{} arg1 = 3, arg2 = 22.1.2
1322 @result{} arg1 = 2, arg2 = 22.1.1
1323 @result{} #<PGresult PGRES_COMMAND_OK - COMMIT>