2 @c This is part of the XEmacs Lisp Reference Manual.
3 @c Copyright (C) 2000 Electrotechnical Laboratory, JAPAN
4 @c Licensed to the Free Software Foundation
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
9 @node PostgreSQL Support, Internationalization, LDAP Support, top
10 @chapter PostgreSQL Support
13 XEmacs can be linked with PostgreSQL libpq run-time support to provide
14 relational database access from Emacs Lisp code.
17 * Building XEmacs with PostgreSQL support::
18 * XEmacs PostgreSQL libpq API::
19 * XEmacs PostgreSQL libpq Examples::
22 @node Building XEmacs with PostgreSQL support, XEmacs PostgreSQL libpq API, ,PostgreSQL Support
23 @comment node-name, next, previous, up
24 @section Building XEmacs with PostgreSQL support
26 XEmacs PostgreSQL support requires linking to the PostgreSQL libpq
27 library. Describing how to build and install PostgreSQL is beyond the
28 scope of this document. See the PostgreSQL manual for details.
30 If you have installed XEmacs from one of the binary kits on
31 (@url{ftp://ftp.xemacs.org/}), or are using an XEmacs binary from a CD
32 ROM, you may have XEmacs PostgreSQL support by default. @code{M-x
33 describe-installation} will tell you if you do.
35 If you are building XEmacs from source, you need to install PostgreSQL
36 first. On some systems, PostgreSQL will come pre-installed in /usr. In
37 this case, it should be autodetected when you run configure. If
38 PostgreSQL is installed into its default location,
39 @file{/usr/local/pgsql}, you must specify
40 @code{--site-prefixes=/usr/local/pgsql} when you run configure. If
41 PostgreSQL is installed into another location, use that instead of
42 @file{/usr/local/pgsql} when specifying @code{--site-prefixes}.
44 As of XEmacs 21.2, PostgreSQL versions 6.5.3 and 7.0 are supported.
45 XEmacs Lisp support for V7.0 is somewhat more extensive than support for
46 V6.5. In particular, asynchronous queries are supported.
48 @node XEmacs PostgreSQL libpq API, XEmacs PostgreSQL libpq Examples, Building XEmacs with PostgreSQL support, PostgreSQL Support
49 @comment node-name, next, previous, up
50 @section XEmacs PostgreSQL libpq API
52 The XEmacs PostgreSQL API is intended to be a policy-free, low-level
53 binding to libpq. The intent is to provide all the basic functionality
54 and then let high level Lisp code decide its own policies.
56 This documentation assumes that the reader has knowledge of SQL, but
57 requires no prior knowledge of libpq.
59 There are many examples in this manual and some setup will be required.
60 In order to run most of the following examples, the following code needs
61 to be executed. In addition to the data is in this table, nearly all of
62 the examples will assume that the free variable @code{P} refers to this
63 database connection. The examples in the original edition of this
64 manual were run against Postgres 7.0beta1.
68 (setq P (pq-connectdb ""))
69 ;; id is the primary key, shikona is a Japanese word that
70 ;; means `the professional name of a Sumo wrestler', and
71 ;; rank is the Sumo rank name.
72 (pq-exec P (concat "CREATE TABLE xemacs_test"
73 " (id int, shikona text, rank text);"))
74 (pq-exec P "COPY xemacs_test FROM stdin;")
75 (pq-put-line P "1\tMusashimaru\tYokuzuna\n")
76 (pq-put-line P "2\tDejima\tOozeki\n")
77 (pq-put-line P "3\tMusoyama\tSekiwake\n")
78 (pq-put-line P "4\tMiyabiyama\tSekiwake\n")
79 (pq-put-line P "5\tWakanoyama\tMaegashira\n")
80 (pq-put-line P "\\.\n")
86 * libpq Lisp Variables::
87 * libpq Lisp Symbols and DataTypes::
88 * Synchronous Interface Functions::
89 * Asynchronous Interface Functions::
90 * Large Object Support::
91 * Other libpq Functions::
92 * Unimplemented libpq Functions::
95 @node libpq Lisp Variables, libpq Lisp Symbols and DataTypes, XEmacs PostgreSQL libpq API, XEmacs PostgreSQL libpq API
96 @comment node-name, next, previous, up
97 @subsection libpq Lisp Variables
99 Various Unix environment variables are used by libpq to provide defaults
100 to the many different parameters. In the XEmacs Lisp API, these
101 environment variables are bound to Lisp variables to provide more
102 convenient access to Lisp Code. These variables are passed to the
103 backend database server during the establishment of a database
104 connection and when the @code{pq-setenv} call is made.
107 Initialized from the @var{PGHOST} environment variable. The default
112 Initialized from the @var{PGUSER} environment variable. The default
117 Initialized from the @var{PGOPTIONS} environment variable. Default
118 additional server options.
122 Initialized from the @var{PGPORT} environment variable. The default TCP
127 Initialized from the @var{PGTTY} environment variable. The default
130 Compatibility note: Debugging TTYs are turned off in the XEmacs Lisp
135 Initialized from the @var{PGDATABASE} environment variable. The default
136 database to connect to.
140 Initialized from the @var{PGREALM} environment variable. The default
144 @defvar pg:client-encoding
145 Initialized from the @var{PGCLIENTENCODING} environment variable. The
146 default client encoding.
148 Compatibility note: This variable is not present in non-Mule XEmacsen.
149 This variable is not present in versions of libpq prior to 7.0.
150 In the current implementation, client encoding is equivalent to the
151 @code{file-name-coding-system} format.
156 Initialized from the @var{PGAUTHTYPE} environment variable. The default
157 authentication scheme used.
159 Compatibility note: This variable is unused in versions of libpq after
160 6.5. It is not implemented at all in the XEmacs Lisp binding.
164 Initialized from the @var{PGGEQO} environment variable. Genetic
168 @defvar pg:cost-index
169 Initialized from the @var{PGCOSTINDEX} environment variable. Cost index
174 Initialized from the @var{PGCOSTHEAP} environment variable. Cost heap
179 Initialized from the @var{PGTZ} environment variable. Default
183 @defvar pg:date-style
184 Initialized from the @var{PGDATESTYLE} environment variable. Default
185 date style in returned date objects.
188 @defvar pg-coding-system
189 This is a variable controlling which coding system is used to encode
190 non-ASCII strings sent to the database.
192 Compatibility Note: This variable is not present in InfoDock.
195 @node libpq Lisp Symbols and DataTypes, Synchronous Interface Functions, libpq Lisp Variables, XEmacs PostgreSQL libpq API
196 @comment node-name, next, previous, up
197 @subsection libpq Lisp Symbols and Datatypes
199 The following set of symbols are used to represent the intermediate
200 states involved in the asynchronous interface.
202 @defvr {Symbol} pgres::polling-failed
203 Undocumented. A fatal error has occurred during processing of an
204 asynchronous operation.
207 @defvr {Symbol} pgres::polling-reading
208 An intermediate status return during an asynchronous operation. It
209 indicates that one may use @code{select} before polling again.
212 @defvr {Symbol} pgres::polling-writing
213 An intermediate status return during an asynchronous operation. It
214 indicates that one may use @code{select} before polling again.
217 @defvr {Symbol} pgres::polling-ok
218 An asynchronous operation has successfully completed.
221 @defvr {Symbol} pgres::polling-active
222 An intermediate status return during an asynchronous operation. One can
223 call the poll function again immediately.
226 @defun pq-pgconn conn field
227 @var{conn} A database connection object.
228 @var{field} A symbol indicating which field of PGconn to fetch. Possible
229 values are shown in the following table.
236 Database user's password
238 Hostname database server is running on
240 TCP port number used in the connection
244 Compatibility note: Debugging TTYs are not used in the XEmacs Lisp API.
246 Additional server options
248 Connection status. Possible return values are shown in the following
251 @item pg::connection-ok
252 The normal, connected status.
253 @item pg::connection-bad
254 The connection is not open and the PGconn object needs to be deleted by
256 @item pg::connection-started
257 An asynchronous connection has been started, but is not yet complete.
258 @item pg::connection-made
259 An asynchronous connect has been made, and there is data waiting to be sent.
260 @item pg::connection-awaiting-response
261 Awaiting data from the backend during an asynchronous connection.
262 @item pg::connection-auth-ok
263 Received authentication, waiting for the backend to start up.
264 @item pg::connection-setenv
265 Negotiating environment during an asynchronous connection.
267 @item pq::error-message
268 The last error message that was delivered to this connection.
269 @item pq::backend-pid
270 The process ID of the backend database server.
274 The @code{PGresult} object is used by libpq to encapsulate the results
275 of queries. The printed representation takes on four forms. When the
276 PGresult object contains tuples from an SQL @code{SELECT} it will look
280 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
281 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
284 The number in brackets indicates how many rows of data are available.
285 When the PGresult object is the result of a command query that doesn't
286 return anything, it will look like:
289 (pq-exec P "CREATE TABLE a_new_table (i int);")
290 @result{} #<PGresult PGRES_COMMAND_OK - CREATE>
293 When either the query is a command-type query that can affect a number
294 of different rows, but doesn't return any of them it will look like:
298 (pq-exec P "INSERT INTO a_new_table VALUES (1);")
299 (pq-exec P "INSERT INTO a_new_table VALUES (2);")
300 (pq-exec P "INSERT INTO a_new_table VALUES (3);")
301 (setq R (pq-exec P "DELETE FROM a_new_table;")))
302 @result{} #<PGresult PGRES_COMMAND_OK[3] - DELETE 3>
305 Lastly, when the underlying PGresult object has been deallocated
306 directly by @code{pq-clear} the printed representation will look like:
310 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
313 @result{} #<PGresult DEAD>
316 The following set of functions are accessors to various data in the PGresult
319 @defun pq-result-status result
320 Return status of a query result.
321 @var{result} is a PGresult object. The return value is one of the
322 symbols in the following table.
324 @item pgres::empty-query
325 A query contained no text. This is usually the result of a recoverable
326 error, or a minor programming error.
327 @item pgres::command-ok
328 A query command that doesn't return anything was executed properly by
330 @item pgres::tuples-ok
331 A query command that returns tuples was executed properly by the
333 @item pgres::copy-out
334 Copy Out data transfer is in progress.
336 Copy In data transfer is in progress.
337 @item pgres::bad-response
338 An unexpected response was received from the backend.
339 @item pgres::nonfatal-error
340 Undocumented. This value is returned when the libpq function
341 @code{PQresultStatus} is called with a @var{NULL} pointer.
342 @item pgres::fatal-error
343 Undocumented. An error has occurred in processing the query and the
344 operation was not completed.
348 @defun pq-res-status result
349 Return the query result status as a string, not a symbol.
350 @var{result} is a PGresult object.
353 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
354 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
356 @result{} "PGRES_TUPLES_OK"
360 @defun pq-result-error-message result
361 Return an error message generated by the query, if any.
362 @var{result} is a PGresult object.
365 (setq R (pq-exec P "SELECT * FROM xemacs-test;"))
366 @result{} <A fatal error is signaled in the echo area>
367 (pq-result-error-message R)
368 @result{} "ERROR: parser: parse error at or near \"-\"
373 @defun pq-ntuples result
374 Return the number of tuples in the query result.
375 @var{result} is a PGresult object.
378 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
379 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
385 @defun pq-nfields result
386 Return the number of fields in each tuple of the query result.
387 @var{result} is a PGresult object.
390 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
391 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
397 @defun pq-binary-tuples result
398 Returns t if binary tuples are present in the results, nil otherwise.
399 @var{result} is a PGresult object.
402 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
403 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
409 @defun pq-fname result field-index
410 Returns the name of a specific field.
411 @var{result} is a PGresult object.
412 @var{field-index} is the number of the column to select from. The first
413 column is number zero.
417 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
418 (setq i (pq-nfields R))
419 (while (>= (decf i) 0)
420 (push (pq-fname R i) l))
422 @result{} ("id" "shikona" "rank")
426 @defun pq-fnumber result field-name
427 Return the field number corresponding to the given field name.
428 -1 is returned on a bad field name.
429 @var{result} is a PGresult object.
430 @var{field-name} is a string representing the field name to find.
432 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
433 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
436 (pq-fnumber R "Not a field")
441 @defun pq-ftype result field-num
442 Return an integer code representing the data type of the specified column.
443 @var{result} is a PGresult object.
444 @var{field-num} is the field number.
446 The return value of this function is the Object ID (Oid) in the database
447 of the type. Further queries need to be made to various system tables
448 in order to convert this value into something useful.
451 @defun pq-fmod result field-num
452 Return the type modifier code associated with a field. Field numbers
454 @var{result} is a PGresult object.
455 @var{field-index} selects which field to use.
458 @defun pq-fsize result field-index
459 Return size of the given field.
460 @var{result} is a PGresult object.
461 @var{field-index} selects which field to use.
465 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
466 (setq i (pq-nfields R))
467 (while (>= (decf i) 0)
468 (push (list (pq-ftype R i) (pq-fsize R i)) l))
470 @result{} ((23 23) (25 25) (25 25))
474 @defun pq-get-value result tup-num field-num
475 Retrieve a return value.
476 @var{result} is a PGresult object.
477 @var{tup-num} selects which tuple to fetch from.
478 @var{field-num} selects which field to fetch from.
480 Both tuples and fields are numbered from zero.
483 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
484 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
486 @result{} "Musashimaru"
494 @defun pq-get-length result tup-num field-num
495 Return the length of a specific value.
496 @var{result} is a PGresult object.
497 @var{tup-num} selects which tuple to fetch from.
498 @var{field-num} selects which field to fetch from.
501 (setq R (pq-exec P "SELECT * FROM xemacs_test;"))
502 @result{} #<PGresult PGRES_TUPLES_OK[5] - SELECT>
503 (pq-get-length R 0 1)
505 (pq-get-length R 1 1)
507 (pq-get-length R 2 1)
512 @defun pq-get-is-null result tup-num field-num
513 Return t if the specific value is the SQL @var{NULL}.
514 @var{result} is a PGresult object.
515 @var{tup-num} selects which tuple to fetch from.
516 @var{field-num} selects which field to fetch from.
519 @defun pq-cmd-status result
520 Return a summary string from the query.
521 @var{result} is a PGresult object.
523 @comment This example was written on day 3 of the 2000 Haru Basho.
524 (setq R (pq-exec P "INSERT INTO xemacs_test
525 VALUES (6, 'Wakanohana', 'Yokozuna');"))
526 @result{} #<PGresult PGRES_COMMAND_OK[1] - INSERT 542086 1>
528 @result{} "INSERT 542086 1"
529 (setq R (pq-exec P "UPDATE xemacs_test SET rank='retired'
530 WHERE shikona='Wakanohana';"))
531 @result{} #<PGresult PGRES_COMMAND_OK[1] - UPDATE 1>
536 Note that the first number returned from an insertion, like in the
537 example, is an object ID number and will almost certainly vary from
538 system to system since object ID numbers in Postgres must be unique
539 across all databases.
542 @defun pq-cmd-tuples result
543 Return the number of tuples if the last command was an INSERT/UPDATE/DELETE.
544 If the last command was something else, the empty string is returned.
545 @var{result} is a PGresult object.
548 (setq R (pq-exec P "INSERT INTO xemacs_test VALUES
549 (7, 'Takanohana', 'Yokuzuna');"))
550 @result{} #<PGresult PGRES_COMMAND_OK[1] - INSERT 38688 1>
553 (setq R (pq-exec P "SELECT * from xemacs_test;"))
554 @result{} #<PGresult PGRES_TUPLES_OK[7] - SELECT>
557 (setq R (pq-exec P "DELETE FROM xemacs_test
558 WHERE shikona LIKE '%hana';"))
559 @result{} #<PGresult PGRES_COMMAND_OK[2] - DELETE 2>
565 @defun pq-oid-value result
566 Return the object id of the insertion if the last command was an INSERT.
567 0 is returned if the last command was not an insertion.
568 @var{result} is a PGresult object.
570 In the first example, the numbers you will see on your local system will
571 almost certainly be different, however the second number from the right
572 in the unprintable PGresult object and the number returned by
573 @code{pq-oid-value} should match.
575 (setq R (pq-exec P "INSERT INTO xemacs_test VALUES
576 (8, 'Terao', 'Maegashira');"))
577 @result{} #<PGresult PGRES_COMMAND_OK[1] - INSERT 542089 1>
580 (setq R (pq-exec P "SELECT shikona FROM xemacs_test
581 WHERE rank='Maegashira';"))
582 @result{} #<PGresult PGRES_TUPLES_OK[2] - SELECT>
588 @defun pq-make-empty-pgresult conn status
589 Create an empty pgresult with the given status.
590 @var{conn} a database connection object
591 @var{status} a value that can be returned by @code{pq-result-status}.
593 The caller is responsible for making sure the return value gets properly
597 @node Synchronous Interface Functions, Asynchronous Interface Functions, libpq Lisp Symbols and DataTypes, XEmacs PostgreSQL libpq API
598 @comment node-name, next, previous, up
599 @subsection Synchronous Interface Functions
601 @defun pq-connectdb conninfo
602 Establish a (synchronous) database connection.
603 @var{conninfo} A string of blank separated options. Options are of the
604 form ``@var{option} = @var{value}''. If @var{value} contains blanks, it
605 must be single quoted. Blanks around the equal sign are optional.
606 Multiple option assignments are blank separated.
608 (pq-connectdb "dbname=japanese port = 25432")
609 @result{} #<PGconn localhost:25432 steve/japanese>
611 The printed representation of a database connection object has four
612 fields. The first field is the hostname where the database server is
613 running (in this case localhost), the second field is the port number,
614 the third field is the database user name, and the fourth field is the
615 name of the database.
617 Database connection objects which have been disconnected and will
618 generate an immediate error if they are used look like:
622 Bad connections can be reestablished with @code{pq-reset}, or deleted
623 entirely with @code{pq-finish}.
625 A database connection object that has been deleted looks like:
627 (let ((P1 (pq-connectdb "")))
630 @result{} #<PGconn DEAD>
633 Note that database connection objects are the most heavy weight objects
634 in XEmacs Lisp at this writing, usually representing as much as several
635 megabytes of virtual memory on the machine the database server is
636 running on. It is wisest to explicitly delete them when you are
637 finished with them, rather than letting garbage collection do it. An
641 (let ((P (pq-connectiondb "")))
644 (...)) ; access database here
648 The following options are available in the options string:
651 Authentication type. Same as @var{PGAUTHTYPE}. This is no longer used.
653 Database user name. Same as @var{PGUSER}.
657 Database name. Same as @var{PGDATABASE}
659 Symbolic hostname. Same as @var{PGHOST}.
661 Host address as four octets (eg. like 192.168.1.1).
663 TCP port to connect to. Same as @var{PGPORT}.
665 Debugging TTY. Same as @var{PGTTY}. This value is suppressed in the
668 Extra backend database options. Same as @var{PGOPTIONS}.
670 A database connection object is returned regardless of whether a
671 connection was established or not.
675 Reestablish database connection.
676 @var{conn} A database connection object.
678 This function reestablishes a database connection using the original
679 connection parameters. This is useful if something has happened to the
680 TCP link and it has become broken.
683 @defun pq-exec conn query
684 Make a synchronous database query.
685 @var{conn} A database connection object.
686 @var{query} A string containing an SQL query.
687 A PGresult object is returned, which in turn may be queried by its many
688 accessor functions to retrieve state out of it. If the query string
689 contains multiple SQL commands, only results from the final command are
693 (setq R (pq-exec P "SELECT * FROM xemacs_test;
694 DELETE FROM xemacs_test WHERE id=8;"))
695 @result{} #<PGresult PGRES_COMMAND_OK[1] - DELETE 1>
699 @defun pq-notifies conn
700 Return the latest async notification that has not yet been handled.
701 @var{conn} A database connection object.
702 If there has been a notification, then a list of two elements will be returned.
703 The first element contains the relation name being notified, the second
704 element contains the backend process ID number. nil is returned if there
705 aren't any notifications to process.
709 Synchronous transfer of environment variables to a backend
710 @var{conn} A database connection object.
712 Environment variable transfer is done as a normal part of database
715 Compatibility note: This function was present but not documented in versions
716 of libpq prior to 7.0.
719 @node Asynchronous Interface Functions, Large Object Support, Synchronous Interface Functions, XEmacs PostgreSQL libpq API
720 @comment node-name, next, previous, up
721 @subsection Asynchronous Interface Functions
723 Making command by command examples is too complex with the asynchronous
724 interface functions. See the examples section for complete calling
727 @defun pq-connect-start conninfo
728 Begin establishing an asynchronous database connection.
729 @var{conninfo} A string containing the connection options. See the
730 documentation of @code{pq-connectdb} for a listing of all the available
734 @defun pq-connect-poll conn
735 An intermediate function to be called during an asynchronous database
737 @var{conn} A database connection object.
738 The result codes are documented in a previous section.
741 @defun pq-is-busy conn
742 Returns t if @code{pq-get-result} would block waiting for input.
743 @var{conn} A database connection object.
746 @defun pq-consume-input conn
747 Consume any available input from the backend.
748 @var{conn} A database connection object.
750 Nil is returned if anything bad happens.
753 @defun pq-reset-start conn
754 Reset connection to the backend asynchronously.
755 @var{conn} A database connection object.
758 @defun pq-reset-poll conn
759 Poll an asynchronous reset for completion
760 @var{conn} A database connection object.
763 @defun pq-reset-cancel conn
764 Attempt to request cancellation of the current operation.
765 @var{conn} A database connection object.
767 The return value is t if the cancel request was successfully
768 dispatched, nil if not (in which case conn->errorMessage is set).
769 Note: successful dispatch is no guarantee that there will be any effect at
770 the backend. The application must read the operation result as usual.
773 @defun pq-send-query conn query
774 Submit a query to Postgres and don't wait for the result.
775 @var{conn} A database connection object.
776 Returns: t if successfully submitted
777 nil if error (conn->errorMessage is set)
780 @defun pq-get-result conn
781 Retrieve an asynchronous result from a query.
782 @var{conn} A database connection object.
784 @code{nil} is returned when no more query work remains.
787 @defun pq-set-nonblocking conn arg
788 Sets the PGconn's database connection non-blocking if the arg is TRUE
789 or makes it non-blocking if the arg is FALSE, this will not protect
790 you from PQexec(), you'll only be safe when using the non-blocking API.
791 @var{conn} A database connection object.
794 @defun pq-is-nonblocking conn
795 Return the blocking status of the database connection
796 @var{conn} A database connection object.
800 Force the write buffer to be written (or at least try)
801 @var{conn} A database connection object.
804 @defun PQsetenvStart conn
805 Start asynchronously passing environment variables to a backend.
806 @var{conn} A database connection object.
808 Compatibility note: this function is only available with libpq-7.0.
811 @defun PQsetenvPoll conn
812 Check an asynchronous environment variables transfer for completion.
813 @var{conn} A database connection object.
815 Compatibility note: this function is only available with libpq-7.0.
818 @defun PQsetenvAbort conn
819 Attempt to terminate an asynchronous environment variables transfer.
820 @var{conn} A database connection object.
822 Compatibility note: this function is only available with libpq-7.0.
825 @node Large Object Support, Other libpq Functions, Asynchronous Interface Functions, XEmacs PostgreSQL libpq API
826 @comment node-name, next, previous, up
827 @subsection Large Object Support
829 @defun pq-lo-import conn filename
830 Import a file as a large object into the database.
831 @var{conn} a database connection object
832 @var{filename} filename to import
834 On success, the object id is returned.
837 @defun pq-lo-export conn oid filename
838 Copy a large object in the database into a file.
839 @var{conn} a database connection object.
840 @var{oid} object id number of a large object.
841 @var{filename} filename to export to.
844 @node Other libpq Functions, Unimplemented libpq Functions, Large Object Support, XEmacs PostgreSQL libpq API
845 @comment node-name, next, previous, up
846 @subsection Other libpq Functions
848 @defun pq-finish conn
849 Destroy a database connection object by calling free on it.
850 @var{conn} a database connection object
852 It is possible to not call this routine because the usual XEmacs garbage
853 collection mechanism will call the underlying libpq routine whenever it
854 is releasing stale @code{PGconn} objects. However, this routine is
855 useful in @code{unwind-protect} clauses to make connections go away
856 quickly when unrecoverable errors have occurred.
858 After calling this routine, the printed representation of the XEmacs
859 wrapper object will contain the string ``DEAD''.
862 @defun pq-client-encoding conn
863 Return the client encoding as an integer code.
864 @var{conn} a database connection object
867 (pq-client-encoding P)
871 Compatibility note: This function did not exist prior to libpq-7.0 and
872 does not exist in a non-Mule XEmacs.
875 @defun pq-set-client-encoding conn encoding
876 Set client coding system.
877 @var{conn} a database connection object
878 @var{encoding} a string representing the desired coding system
881 (pq-set-client-encoding P "EUC_JP")
885 The current idiom for ensuring proper coding system conversion is the
886 following (illustrated for EUC Japanese encoding):
888 (setq P (pq-connectdb "..."))
889 (let ((file-name-coding-system 'euc-jp)
890 (pg-coding-system 'euc-jp))
891 (pq-set-client-encoding "EUC_JP")
895 Compatibility note: This function did not exist prior to libpq-7.0 and
896 does not exist in a non-Mule XEmacs.
899 @defun pq-env-2-encoding
900 Return the integer code representing the coding system in @var{PGCLIENTENCODING}.
906 Compatibility note: This function did not exist prior to libpq-7.0 and
907 does not exist in a non-Mule XEmacs.
911 Destroy a query result object by calling free() on it.
912 @var{res} a query result object
914 Note: The memory allocation systems of libpq and XEmacs are different.
915 The XEmacs representation of a query result object will have both the
916 XEmacs version and the libpq version freed at the next garbage collection
917 when the object is no longer being referenced. Calling this function does
918 not release the XEmacs object, it is still subject to the usual rules for
919 Lisp objects. The printed representation of the XEmacs object will contain
920 the string ``DEAD'' after this routine is called indicating that it is no
921 longer useful for anything.
924 @defun pq-conn-defaults
925 Return a data structure that represents the connection defaults.
926 The data is returned as a list of lists, where each sublist contains
927 info regarding a single option.
930 @node Unimplemented libpq Functions, , Other libpq Functions, XEmacs PostgreSQL libpq API
931 @comment node-name, next, previous, up
932 @subsection Unimplemented libpq Functions
934 @deftypefn {Unimplemented Function} PGconn *PQsetdbLogin (char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName, char *login, char *pwd)
935 Synchronous database connection.
936 @var{pghost} is the hostname of the PostgreSQL backend to connect to.
937 @var{pgport} is the TCP port number to use.
938 @var{pgoptions} specifies other backend options.
939 @var{pgtty} specifies the debugging tty to use.
940 @var{dbName} specifies the database name to use.
941 @var{login} specifies the database user name.
942 @var{pwd} specifies the database user's password.
944 This routine is deprecated as of libpq-7.0, and its functionality can be
945 replaced by external Lisp code if needed.
948 @deftypefn {Unimplemented Function} PGconn *PQsetdb (char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName)
949 Synchronous database connection.
950 @var{pghost} is the hostname of the PostgreSQL backend to connect to.
951 @var{pgport} is the TCP port number to use.
952 @var{pgoptions} specifies other backend options.
953 @var{pgtty} specifies the debugging tty to use.
954 @var{dbName} specifies the database name to use.
956 This routine was deprecated in libpq-6.5.
959 @deftypefn {Unimplemented Function} int PQsocket (PGconn *conn)
960 Return socket file descriptor to a backend database process.
961 @var{conn} database connection object.
964 @deftypefn {Unimplemented Function} void PQprint (FILE *fout, PGresult *res, PGprintOpt *ps)
965 Print out the results of a query to a designated C stream.
966 @var{fout} C stream to print to
967 @var{res} the query result object to print
968 @var{ps} the print options structure.
970 This routine is deprecated as of libpq-7.0 and cannot be sensibly exported
974 @deftypefn {Unimplemented Function} void PQdisplayTuples (PGresult *res, FILE *fp, int fillAlign, char *fieldSep, int printHeader, int quiet)
975 @var{res} query result object to print
976 @var{fp} C stream to print to
977 @var{fillAlign} pad the fields with spaces
978 @var{fieldSep} field separator
979 @var{printHeader} display headers?
982 This routine was deprecated in libpq-6.5.
985 @deftypefn {Unimplemented Function} void PQprintTuples (PGresult *res, FILE *fout, int printAttName, int terseOutput, int width)
986 @var{res} query result object to print
987 @var{fout} C stream to print to
988 @var{printAttName} print attribute names
989 @var{terseOutput} delimiter bars
990 @var{width} width of column, if 0, use variable width
992 This routine was deprecated in libpq-6.5.
995 @deftypefn {Unimplemented Function} int PQmblen (char *s, int encoding)
996 Determine length of a multibyte encoded char at @code{*s}.
997 @var{s} encoded string
998 @var{encoding} type of encoding
1000 Compatibility note: This function was introduced in libpq-7.0.
1003 @deftypefn {Unimplemented Function} void PQtrace (PGconn *conn, FILE *debug_port)
1004 Enable tracing on @code{debug_port}.
1005 @var{conn} database connection object.
1006 @var{debug_port} C output stream to use.
1009 @deftypefn {Unimplemented Function} void PQuntrace (PGconn *conn)
1011 @var{conn} database connection object.
1014 @deftypefn {Unimplemented Function} char *PQoidStatus (PGconn *conn)
1015 Return the object id as a string of the last tuple inserted.
1016 @var{conn} database connection object.
1018 Compatibility note: This function is deprecated in libpq-7.0, however it
1019 is used internally by the XEmacs binding code when linked against versions
1023 @deftypefn {Unimplemented Function} PGresult *PQfn (PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, PQArgBlock *args, int nargs)
1024 ``Fast path'' interface --- not really recommended for application use
1025 @var{conn} A database connection object.
1034 The following set of very low level large object functions aren't
1035 appropriate to be exported to Lisp.
1037 @deftypefn {Unimplemented Function} int pq-lo-open (PGconn *conn, int lobjid, int mode)
1038 @var{conn} a database connection object.
1039 @var{lobjid} a large object ID.
1040 @var{mode} opening modes.
1043 @deftypefn {Unimplemented Function} int pq-lo-close (PGconn *conn, int fd)
1044 @var{conn} a database connection object.
1045 @var{fd} a large object file descriptor
1048 @deftypefn {Unimplemented Function} int pq-lo-read (PGconn *conn, int fd, char *buf, int len)
1049 @var{conn} a database connection object.
1050 @var{fd} a large object file descriptor.
1051 @var{buf} buffer to read into.
1052 @var{len} size of buffer.
1055 @deftypefn {Unimplemented Function} int pq-lo-write (PGconn *conn, int fd, char *buf, size_t len)
1056 @var{conn} a database connection object.
1057 @var{fd} a large object file descriptor.
1058 @var{buf} buffer to write from.
1059 @var{len} size of buffer.
1062 @deftypefn {Unimplemented Function} int pq-lo-lseek (PGconn *conn, int fd, int offset, int whence)
1063 @var{conn} a database connection object.
1064 @var{fd} a large object file descriptor.
1069 @deftypefn {Unimplemented Function} int pq-lo-creat (PGconn *conn, int mode)
1070 @var{conn} a database connection object.
1071 @var{mode} opening modes.
1074 @deftypefn {Unimplemented Function} int pq-lo-tell (PGconn *conn, int fd)
1075 @var{conn} a database connection object.
1076 @var{fd} a large object file descriptor.
1079 @deftypefn {Unimplemented Function} int pq-lo-unlink (PGconn *conn, int lobjid)
1080 @var{conn} a database connection object.
1081 @var{lbojid} a large object ID.
1084 @node XEmacs PostgreSQL libpq Examples, , XEmacs PostgreSQL libpq API, PostgreSQL Support
1085 @comment node-name, next, previous, up
1086 @section XEmacs PostgreSQL libpq Examples
1088 This is an example of one method of establishing an asynchronous
1092 (defun database-poller (P)
1093 (message "%S before poll" (pq-pgconn P 'pq::status))
1095 (message "%S after poll" (pq-pgconn P 'pq::status))
1096 (if (eq (pq-pgconn P 'pq::status) 'pg::connection-ok)
1098 (add-timeout .1 'database-poller P)))
1099 @result{} database-poller
1101 (setq P (pq-connect-start ""))
1102 (add-timeout .1 'database-poller P))
1103 @result{} pg::connection-started before poll
1104 @result{} pg::connection-made after poll
1105 @result{} pg::connection-made before poll
1106 @result{} pg::connection-awaiting-response after poll
1107 @result{} pg::connection-awaiting-response before poll
1108 @result{} pg::connection-auth-ok after poll
1109 @result{} pg::connection-auth-ok before poll
1110 @result{} pg::connection-setenv after poll
1111 @result{} pg::connection-setenv before poll
1112 @result{} pg::connection-ok after poll
1115 @result{} #<PGconn localhost:25432 steve/steve>
1118 Here is an example of one method of doing an asynchronous reset.
1121 (defun database-poller (P)
1123 (message "%S before poll" (pq-pgconn P 'pq::status))
1124 (setq PS (pq-reset-poll P))
1125 (message "%S after poll [%S]" (pq-pgconn P 'pq::status) PS)
1126 (if (eq (pq-pgconn P 'pq::status) 'pg::connection-ok)
1128 (add-timeout .1 'database-poller P))))
1129 @result{} database-poller
1132 (add-timeout .1 'database-poller P))
1133 @result{} pg::connection-started before poll
1134 @result{} pg::connection-made after poll [pgres::polling-writing]
1135 @result{} pg::connection-made before poll
1136 @result{} pg::connection-awaiting-response after poll [pgres::polling-reading]
1137 @result{} pg::connection-awaiting-response before poll
1138 @result{} pg::connection-setenv after poll [pgres::polling-reading]
1139 @result{} pg::connection-setenv before poll
1140 @result{} pg::connection-ok after poll [pgres::polling-ok]
1143 @result{} #<PGconn localhost:25432 steve/steve>
1146 And finally, an asynchronous query.
1149 (defun database-poller (P)
1151 (pq-consume-input P)
1153 (add-timeout .1 'database-poller P)
1154 (setq R (pq-get-result P))
1157 (push R result-list)
1158 (add-timeout .1 'database-poller P))))))
1159 @result{} database-poller
1160 (when (pq-send-query P "SELECT * FROM xemacs_test;")
1161 (setq result-list nil)
1162 (add-timeout .1 'database-poller P))
1166 @result{} (#<PGresult PGRES_TUPLES_OK - SELECT>)
1169 Here is an example showing how multiple SQL statements in a single query
1170 can have all their results collected.
1172 ;; Using the same @code{database-poller} function from the previous example
1173 (when (pq-send-query P "SELECT * FROM xemacs_test;
1174 SELECT * FROM pg_database;
1175 SELECT * FROM pg_user;")
1176 (setq result-list nil)
1177 (add-timeout .1 'database-poller P))
1181 @result{} (#<PGresult PGRES_TUPLES_OK - SELECT> #<PGresult PGRES_TUPLES_OK - SELECT> #<PGresult PGRES_TUPLES_OK - SELECT>)
1184 Here is an example which illustrates collecting all data from a query,
1185 including the field names.
1188 (defun pg-util-query-results (results)
1189 "Retrieve results of last SQL query into a list structure."
1190 (let ((i (1- (pq-ntuples R)))
1193 (setq j (1- (pq-nfields R)))
1196 (push (pq-get-value R i j) l2)
1200 (setq j (1- (pq-nfields R)))
1203 (push (pq-fname R j) l2)
1207 @result{} pg-util-query-results
1208 (setq R (pq-exec P "SELECT * FROM xemacs_test ORDER BY field2 DESC;"))
1209 @result{} #<PGresult PGRES_TUPLES_OK - SELECT>
1210 (pg-util-query-results R)
1211 @result{} (("f1" "field2") ("a" "97") ("b" "97") ("stuff" "42") ("a string" "12") ("foo" "10") ("string" "2") ("text" "1"))
1214 Here is an example of a query that uses a database cursor.
1218 (setq R (pq-exec P "BEGIN;"))
1219 (setq R (pq-exec P "DECLARE k_cursor CURSOR FOR SELECT * FROM xemacs_test ORDER BY f1 DESC;"))
1221 (setq R (pq-exec P "FETCH k_cursor;"))
1222 (while (eq (pq-ntuples R) 1)
1223 (push (list (pq-get-value R 0 0) (pq-get-value R 0 1)) data)
1224 (setq R (pq-exec P "FETCH k_cursor;")))
1225 (setq R (pq-exec P "END;"))
1227 @result{} (("a" "97") ("a string" "12") ("b" "97") ("foo" "10") ("string" "2") ("stuff" "42") ("text" "1"))
1230 Here's another example of cursors, this time with a Lisp macro to
1231 implement a mapping function over a table.
1234 (defmacro map-db (P table condition callout)
1236 (pq-exec ,P "BEGIN;")
1237 (pq-exec ,P (concat "DECLARE k_cursor CURSOR FOR SELECT * FROM "
1241 " ORDER BY f1 DESC;"))
1242 (setq R (pq-exec P "FETCH k_cursor;"))
1243 (while (eq (pq-ntuples R) 1)
1244 (,callout (pq-get-value R 0 0) (pq-get-value R 0 1))
1245 (setq R (pq-exec P "FETCH k_cursor;")))
1246 (pq-exec P "END;")))
1248 (defun callback (arg1 arg2)
1249 (message "arg1 = %s, arg2 = %s" arg1 arg2))
1251 (map-db P "xemacs_test" "WHERE field2 > 10" callback)
1252 @result{} arg1 = stuff, arg2 = 42
1253 @result{} arg1 = b, arg2 = 97
1254 @result{} arg1 = a string, arg2 = 12
1255 @result{} arg1 = a, arg2 = 97
1256 @result{} #<PGresult PGRES_COMMAND_OK - COMMIT>