This is pgin.tcl/REFERENCE, programmer's reference to pgin.tcl.
Last updated for pgin.tcl-2.0b1 on 2003-10-30
The project home page is: http://gborg.postgresql.org/project/pgintcl/
-----------------------------------------------------------------------------

For more information on the details of the commands, refer to the libpgtcl
documentation. Pgin.tcl attempts to emulate libpgtcl's command usage and
behavior wherever possible.

(Note: The syntax ?...? refers to optional values, per the Tcl documentation.)


CORE COMMANDS:

     pg_conndefaults
         Returns the connection parameter defaults as a list of elements
         of the following form:
         { OptionName Display-label display-flag display-length default-value }

     pg_connect -conninfo "option=value..."
         Connects to the database. Returns a connection handle conn_handle.
         Commonly used connection option names are:
                 dbname host port user password
         Values need to be in single quotes if they contain spaces.
         Within single quoted values, use \\ for \ and \' for '.

         Note that the older form pg_connect dbname ?-host name ...? is not
         supported. Use the new style instead.
         Parameter values default to environment variables or built-in defaults.

         Host defaults to the environment variable PGHOST, or to "localhost"
         if no PGHOST. (libpgtcl defaults to using a Unix Domain Socket
         in that case, but pgin.tcl cannot support UDS.)

     pg_disconnect $conn_handle
         Disconnect from database. Also destroys any left-over result
         structures associated with this connection.

     pg_select $conn_handle "query" arrayName { proc... }
         Execute a query and iterate proc with arrayName set to each tuple.

     pg_exec $conn_handle "query"
         Execute SQL and return a result_handle (which caller must free).

     pg_execute ?-oid oidName? ?-array arrayName? $conn_handle "query" ?proc?
         Execute SQL and return the number of tuples queried or affected.
         This was added to libpgtcl in PostgreSQL 7.1, and can replace both
         pg_exec and pg_select in many cases.
         If -array is not given on a Select, a variable is created for
         each field in the query result.
         If no proc is supplied, only the first query result row is saved.

     pg_result $result_handle option ?args?
         Get information about a result_handle with these options:
         -status          Returns the result status (see notes)
         -error           Returns the error message if status=PGRES_FATAL_ERROR
         -errorField c    Returns the error message field value (see below)
         -conn            Returns the connection handle for this result
         -oid             Returns the OID of an inserted tuple
         -numTuples       Returns the number of tuples in the result
         -numAttrs        Returns the number of attributes
         -assign A        Assign the query result data to A(tuple,attribName)
         -assignbyidx A s Assign results to an array (see the libpgtcl docs)
         -getTuple N      Return a list of values for tuple N
         -tupleArray N A  Store the Nth tuple in array A as A(attribName)
         -attributes      Return a list of attributes
         -lAttributes     Return a list of attributes as {{name type size}...}
         -lxAttributes    Return a list of extended information about
                          attributes as: {{name type size size_modifier
                             format table_OID table_column}...}
         -cmdTuples       Return number of tuples INSERTed, DELETEd, UPDATEd
         -list            Return result set as a list of values.
         -llist           Return result set as a list of tuple data, each
                          of which is a list of values.
       When finished with a result structure, you must clear it with:
         -clear           Deallocate the result structure
       Notes:
         Result status is one of these string values:
             PGRES_TUPLES_OK PGRES_COMMAND_OK PGRES_FATAL_ERROR
             PGRES_COPY_OUT PGRES_COPY_IN PGRES_EMPTY_QUERY
         -oid returns 0 if the query was not an INSERT.
         -cmdTuples is an extension, expected to be in a future libpgtcl.
             It returns an empty string if the query was not INSERT, UPDATE,
             or DELETE. This is the expected future behavior of libpgtcl.
         -list and -llist are extensions to libpgtcl which were added
             after PostgreSQL-7.2.3 to libpgtcl-1.4.
         -errorField is an extension to access error message subfields. The
             argument following -errorField is a field name or code:
                Field name:        Code:   Notes:
                 SEVERITY           S       ERROR or FATAL for example
                 SQLSTATE           C       5-character SQL State
                 MESSAGE_PRIMARY    M       Main error message
                 MESSAGE_DETAIL     D       Optional detailed message
                 MESSAGE_HINT       H       Optional suggestion
                 STATEMENT_POSITION P       Decimal integer cursor position
                 CONTEXT            W       Call stack-trace
                 SOURCE_FILE        F       PostgreSQL source code filename
                 SOURCE_LINE        L       PostgreSQL source code line number
                 SOURCE_FUNCTION    R       PostgreSQL function name
             If the field name or code is defined, pg_result returns
             the value of that field (if defined), else an empty string.
             Note: pg_result -error returns the SEVERITY followed by the
             MESSAGE_PRIMARY as a single string.
         -lxAttributes is an extension. It returns the same information
             as -lAttributes plus additional information provided by the
             PostgreSQL server about the result attributes.

     pg_listen $conn_handle "name" ?proc?
         Listen for notifications and call procedure proc, or unlisten.

     pg_escape_string $str
         Returns the string str properly escaped for including in SQL
         strings. That is, returns str with single quotes and backslashes
         doubled up.
         Note: This command was added to libpgtcl in CVS after 1.4b release.

-----------------------------------------------------------------------------
EXTENSIONS:

pgin.tcl has some extended commands and variables.
NOTE: These commands are subject to change, and those changes may break
code which uses these commands. These commands do not exist in libpgtcl. If
equivalent but different commands are added to libpgtcl, it is likely that
pgin.tcl will be changed to match.

     pg_configure $conn_handle option ?value?
         Query or set an interface option. The $conn_handle names
         the database connection, and the option applies to that
         connection except as noted below.
         If the value is supplied, sets the option to that value, and
         returns the previous value. If the value is not supplied,
         returns the current value.

         The following options are available:

               nulls       A string to use for NULL database values.
                           Default value is "", an empty string.

               notice      A command to use when a notice message
                           arrives. See NOTICES below.
                           Default is a procedure which just prints
                           the message to stderr. Empty string means
                           do nothing when a notice is received.

               debug       Debug print flag. Default is 0 for off.
                           This applies to all connections (conn_handle
                           is ignored when setting).

     pg_endcopy $result_handle
         This must be called after SQL COPY FROM or COPY TO completes.
         See COPY FROM/TO below.

     pg_copy_read $result_handle
         Read the next line (record) for SQL COPY TO STDOUT.
         Returns the line read, or an empty string when COPY is done.
         The returned line does not end in a newline, so you can just
         split it on tab to get the column values.
         With PostgreSQL-7.4 support, you must use this routine for
         COPY TO STDOUT; reading from the socket no longer works.

     pg_copy_write $result_handle $line
         Write one line (record) $line for SQL COPY FROM STDIN.
         The passed argument must not end in a newline.
         With PostgreSQL-7.4 support, you must use this routine for
         COPY FROM STDIN; writing to the socket no longer works.

     $pgtcl::version
         This variable has the pgin.tcl version number. The existence of
         this variable can also be used to determine if pgin.tcl has been
         loaded.

     pg_callfn $db "fname" result "arginfo" arg...
     pg_callfn_int $db "fname" "arginfo" arg...
         These two calls allow access to the PostgreSQL back-end
         "fast-path" function call interface. This is not intended
         for routine use. See the INTERNALS document for more information.

     pg_parameter_status $db ?param?
         Fetch the value of a parameter supplied by a PostgreSQL-7.4 or
         higher backend. If param is not given, return all parameters
         as a list of "parameter-name parameter-value" pairs (suitable
         for "array set"). If param is given, return the value of that
         parameter (or an empty string if no such parameter has been
         sent by the backend). The following parameters are commonly
         sent by the backend:
           client_encoding DateStyle is_superuser server_encoding
           server_version session_authorization

     pg_exec_prepared $db statement_name res_formats arg_formats arg...
         Executes a pre-prepared SQL statement named $statement_name
         with parameters arg... formatted per arg_formats, expecting
         query results formatted per res_formats, and returns a result
         handle.
         This allows binding arguments to SQL statement parameters without
         quoting problems, and sending and receiving raw binary data.

         The statement must be prepared with the SQL command
              PREPARE statement_name (args) AS ...

         res_formats is a list describing the query result columns, and
         arg_formats is a list describing the query parameter formats, as
         follows. An empty list means all parameters or result columns are
         text (or, that there are no parameters/result columns). A single
         word "TEXT" (or "T"), or "BINARY" (or "B"), indicate the format
         of all parameters or of all result columns. Finally, a list of
         those words indicates the format of each individual parameter
         or result column.

     pg_transaction_status $db
         Returns the current in-transaction status. This will return one
         of the following strings:
            IDLE        (Connection is idle, not in a transaction)
            INTRANS     (Connection is idle, in a valid transaction block)
            INERROR     (Connection is in a failed transaction block)
            UNKNOWN     (Connection is bad or in an unknown state)

-----------------------------------------------------------------------------
LARGE OBJECTS:

pgin.tcl implements the Large Object commands of libpgtcl.

Remember that these routines must be used inside transactions. Also note
that these routines do not deal with your own database tables, and in
general PostgreSQL does not attempt to synchronize actual large object
storage with their OID fields in your tables. So for example you will
generally have to pair a database INSERT with a pg_lo_creat, and a database
DELETE with a pg_lo_unlink.

     pg_lo_creat $conn_handle "mode"
         Create a large object. Mode should be one of the strings INV_READ,
         INV_WRITE, or INV_READ|INV_WRITE, although to be honest I do not
         know what the difference is. As an extension, to be compatible with
         pg_lo_open, this command also accepts mode of "r", "w", or "rw".
         Returns a large object OID, which you should promptly insert into
         a table.

     pg_lo_open $conn_handle $loid "mode"
         Open the large object with id $loid in mode "mode". Mode can be "r",
         "w", or "rw" specifying read and/or write. As an extension, to be
         compatible with pg_lo_creat and libPQ, this command also accepts mode
         of INV_READ, INV_WRITE, or "INV_READ|INV_WRITE".
         The $loid usually comes from the return value of pg_lo_creat directly
         or indirectly as an oid-type field in a table.
         Returns a large object file descriptor (a lofd) for use with the
         commands below.

     pg_lo_close $conn_handle $lofd
         Close a large object opened with pg_lo_open.

     pg_lo_unlink $conn_handle $loid
         Delete the large object identified by ID $loid.

     pg_lo_read $conn_handle $lofd buf_name $maxlen
         Read up to $maxlen bytes from the large object $lofd into the
         buffer variable named by buf_name. Returns the number of bytes
         actually read. Returns 0 at the end of the large object.

     pg_lo_write $conn_handle $lofd $buf $len
         Write at most $len bytes from $buf to the open large object $lofd.
         (If $buf has fewer than $len bytes, just write all of $buf.)

     pg_lo_lseek $conn_handle $lofd $offset "whence"
         Reposition the (virtual) file position pointer in the open large
         object identified by $lofd to the position $offset modified by
         "whence", which is one of SEEK_SET, SEEK_CUR, or SEEK_END specifying
         positions relative to start of file, current position, or end of file.

     pg_lo_tell $conn_handle $lofd
         Return the integer (virtual) file offset of the current file position
         pointer in the open large object identified by $lofd.

     pg_lo_import $conn_handle "filename"
         Create a new large object, import the contents of the specified
         file into it, and return the Large Object ID. You should probably
         insert the returned loid into a table promptly.

     pg_lo_export $conn_handle $loid "filename"
         Export the large object identified by ID $loid into the named file.

-----------------------------------------------------------------------------
NOTICES:

If the backend sends a notice or warning message, the notice handler will
be called with the text of the notice as the final parameter. The default
procedure just prints the message to stderr (like libPQ does). You may
replace this by defining your own procedure and calling
      pg_configure $conn_handle notice "notice_command ..."
The actual message will be appended as an additional argument to your
command.  (libpgtcl does not provide this capability.)

If you want to suppress notice and warning messages completely, you can set
the notice handler to an empty string. For example, if you need to
temporarily suppress notices and warnings, use something like this:
    set save_handler [pg_configure $conn_handle notice {}]
    ... commands with no notice or warning messages reported ...
    pg_configure $conn_handle $save_handler
But note that a better way to ignore NOTICE messages is to increase the
message threshold with: SET CLIENT_MIN_MESSAGES TO WARNING

Don't confuse Notices with Notification.  Notice and warning messages are
generated by the server in response to a command from the client, but do
not imply failure of the command so they don't affect the result status.
An example of a notice is index creation as a result of a primary key. An
example of a warning is a rollback issued outside a transaction.  By
contrast, notifications are messages sent on behalf of another database
client.

-----------------------------------------------------------------------------
NOTIFICATIONS:

Support for backend notifications differs from libpgtcl. With libpgtcl, the
notification will be received as soon as Tcl enters the idle loop, e.g. if
you use "update". libpgtcl does not need to be reading from the backend to
get a notification. With pgin.tcl, the notification from the backend will
only be seen while something is being read from the backend; that is,
during pg_exec, pg_select, or pg_execute processing. After a notification
is read, it will be delivered the next time Tcl enters the idle loop.

-----------------------------------------------------------------------------
COPY FROM/TO:

Front-end copy is a bulk import or export operation where multiple rows
are sent between the PostgreSQL back-end and client front-end with minimal
formatting. This is implemented in PostgreSQL with the following SQL:
         COPY tablename TO STDOUT;   -- Export table
         COPY tablename FROM STDIN;  -- Import table
Each row is transmitted as one line, with columns separated by a delimiter
which defaults to tab, backslash (\) escaping of control characters, and
\N used for NULL.

(Note: You never have to use COPY FROM/TO. You can always use the standard
SQL SELECT and INSERT instead. COPY FROM/TO is said to be more efficient
for large amounts of data.)

The COPY protocol changed with PostgreSQL-7.4, and it is no longer possible
to directly read and write to the connection handle as with previous
versions of pgin.tcl. You must use the routines below to read and write
records during COPY. This is currently incompatible with libpgtcl.

To copy out a table, first issue "COPY tablename TO STDOUT" using pg_exec.
The result status will change to PGRES_COPY_OUT. Then use pg_copy_read to
read each record. Returned records will not end in a newline. Repeat
pg_copy_read until it returns an empty string, then call pg_endcopy.
For example:

        while {[set line [pg_copy_read $result_handle]] != ""} {
           ... Process record in $line ...
        }
        pg_endcopy $result_handle

After pg_endcopy returns, the result status should be PGRES_COMMAND_OK if
the copy was successful.

To copy in a table, first issue "COPY tablename FROM STDIN" using pg_exec.
The result status will change to PGRES_COPY_IN. Then use pg_copy_write to
write each record. Do not append a newline to the record. Repeat
pg_copy_write until you are done, then call pg_endcopy. For example:
        while {... more data to send ...} {
          pg_copy_write $result_handle $tab_separated_data_line
        }
        pg_endcopy $result_handle

After pg_endcopy returns, the result status should be PGRES_COMMAND_OK if
the copy was successful.

Do not write or expect to read the old COPY delimiter "\.".

-----------------------------------------------------------------------------
