1Connection -- The connection object
2===================================
3
4.. currentmodule:: pg
5
6.. class:: Connection
7
8This object handles a connection to a PostgreSQL database. It embeds and
9hides all the parameters that define this connection, thus just leaving really
10significant parameters in function calls.
11
12.. note::
13
14    Some methods give direct access to the connection socket.
15    *Do not use them unless you really know what you are doing.*
16    If you prefer disabling them,
17    do not set the ``direct_access`` option in the Python setup file.
18    These methods are specified by the tag [DA].
19
20.. note::
21
22    Some other methods give access to large objects
23    (refer to PostgreSQL user manual for more information about these).
24    If you want to forbid access to these from the module,
25    set the ``large_objects`` option in the Python setup file.
26    These methods are specified by the tag [LO].
27
28query -- execute a SQL command string
29-------------------------------------
30
31.. method:: Connection.query(command, [args])
32
33    Execute a SQL command string
34
35    :param str command: SQL command
36    :param args: optional parameter values
37    :returns: result values
38    :rtype: :class:`Query`, None
39    :raises TypeError: bad argument type, or too many arguments
40    :raises TypeError: invalid connection
41    :raises ValueError: empty SQL query or lost connection
42    :raises pg.ProgrammingError: error in query
43    :raises pg.InternalError: error during query processing
44
45This method simply sends a SQL query to the database. If the query is an
46insert statement that inserted exactly one row into a table that has OIDs,
47the return value is the OID of the newly inserted row as an integer.
48If the query is an update or delete statement, or an insert statement that
49did not insert exactly one row, or on a table without OIDs, then the number
50of rows affected is returned as a string. If it is a statement that returns
51rows as a result (usually a select statement, but maybe also an
52``"insert/update ... returning"`` statement), this method returns
53a :class:`Query`. Otherwise, it returns ``None``.
54
55You can use the :class:`Query` object as an iterator that yields all results
56as tuples, or call :meth:`Query.getresult` to get the result as a list
57of tuples. Alternatively, you can call :meth:`Query.dictresult` or
58:meth:`Query.dictiter` if you want to get the rows as dictionaries,
59or :meth:`Query.namedresult` or :meth:`Query.namediter` if you want to
60get the rows as named tuples. You can also simply print the :class:`Query`
61object to show the query results on the console.
62
63The SQL command may optionally contain positional parameters of the form
64``$1``, ``$2``, etc instead of literal data, in which case the values
65must be supplied separately as a tuple.  The values are substituted by
66the database in such a way that they don't need to be escaped, making this
67an effective way to pass arbitrary or unknown data without worrying about
68SQL injection or syntax errors.
69
70If you don't pass any parameters, the command string can also include
71multiple SQL commands (separated by semicolons). You will only get the
72return value for the last command in this case.
73
74When the database could not process the query, a :exc:`pg.ProgrammingError` or
75a :exc:`pg.InternalError` is raised. You can check the ``SQLSTATE`` error code
76of this error by reading its :attr:`sqlstate` attribute.
77
78Example::
79
80    name = input("Name? ")
81    phone = con.query("select phone from employees where name=$1",
82        (name,)).getresult()
83
84
85send_query - executes a SQL command string asynchronously
86---------------------------------------------------------
87
88.. method:: Connection.send_query(command, [args])
89
90    Submits a command to the server without waiting for the result(s).
91
92    :param str command: SQL command
93    :param args: optional parameter values
94    :returns: a query object, as described below
95    :rtype: :class:`Query`
96    :raises TypeError: bad argument type, or too many arguments
97    :raises TypeError: invalid connection
98    :raises ValueError: empty SQL query or lost connection
99    :raises pg.ProgrammingError: error in query
100
101This method is much the same as :meth:`Connection.query`, except that it
102returns without waiting for the query to complete. The database connection
103cannot be used for other operations until the query completes, but the
104application can do other things, including executing queries using other
105database connections. The application can call ``select()`` using the
106``fileno```  obtained by the connection#s :meth:`Connection.fileno` method
107to determine when the query has results to return.
108
109This method always returns a :class:`Query` object. This object differs
110from the :class:`Query` object returned by :meth:`Connection.query` in a
111few way. Most importantly, when :meth:`Connection.send_query` is used, the
112application must call one of the result-returning methods such as
113:meth:`Query.getresult` or :meth:`Query.dictresult` until it either raises
114an exception or returns ``None``.
115
116Otherwise, the database connection will be left in an unusable state.
117
118In cases when :meth:`Connection.query` would return something other than
119a :class:`Query` object, that result will be returned by calling one of
120the result-returning methods on the :class:`Query` object returned by
121:meth:`Connection.send_query`. There's one important difference in these
122result codes: if :meth:`Connection.query` returns `None`, the result-returning
123methods will return an empty string (`''`). It's still necessary to call a
124result-returning method until it returns `None`.
125
126:meth:`Query.listfields`, :meth:`Query.fieldname`, :meth:`Query.fieldnum`,
127and :meth:`Query.ntuples` only work after a call to a result-returning method
128with a non-`None` return value. :meth:`Query.ntuples` returns only the number
129of rows returned by the previous result-returning method.
130
131If multiple semi-colon-delimited statements are passed to
132:meth:`Connection.query`, only the results of the last statement are returned
133in the :class:`Query` object. With :meth:`Connection.send_query`, all results
134are returned. Each result set will be returned by a separate call to
135:meth:`Query.getresult()` or other result-returning methods.
136
137.. versionadded:: 5.2
138
139Examples::
140
141    name = input("Name? ")
142    query = con.send_query("select phone from employees where name=$1",
143                          (name,))
144    phone = query.getresult()
145    query.getresult()  # to close the query
146
147    # Run two queries in one round trip:
148    # (Note that you cannot use a union here
149    # when the result sets have different row types.)
150    query = con.send_query("select a,b,c from x where d=e;
151                          "select e,f from y where g")
152    result_x = query.dictresult()
153    result_y = query.dictresult()
154    query.dictresult()  # to close the query
155
156    # Using select() to wait for the query to be ready:
157    query = con.send_query("select pg_sleep(20)")
158    r, w, e = select([con.fileno(), other, sockets], [], [])
159    if con.fileno() in r:
160        results = query.getresult()
161        query.getresult()  # to close the query
162
163    # Concurrent queries on separate connections:
164    con1 = connect()
165    con2 = connect()
166    s = con1.query("begin; set transaction isolation level repeatable read;"
167                   "select pg_export_snapshot();").getresult()[0][0]
168    con2.query("begin; set transaction isolation level repeatable read;"
169               "set transaction snapshot '%s'" % (s,))
170    q1 = con1.send_query("select a,b,c from x where d=e")
171    q2 = con2.send_query("select e,f from y where g")
172    r1 = q1.getresult()
173    q1.getresult()
174    r2 = q2.getresult()
175    q2.getresult()
176    con1.query("commit")
177    con2.query("commit")
178
179
180query_prepared -- execute a prepared statement
181----------------------------------------------
182
183.. method:: Connection.query_prepared(name, [args])
184
185    Execute a prepared statement
186
187    :param str name: name of the prepared statement
188    :param args: optional parameter values
189    :returns: result values
190    :rtype: :class:`Query`, None
191    :raises TypeError: bad argument type, or too many arguments
192    :raises TypeError: invalid connection
193    :raises ValueError: empty SQL query or lost connection
194    :raises pg.ProgrammingError: error in query
195    :raises pg.InternalError: error during query processing
196    :raises pg.OperationalError: prepared statement does not exist
197
198This method works exactly like :meth:`Connection.query` except that instead
199of passing the command itself, you pass the name of a prepared statement.
200An empty name corresponds to the unnamed statement.  You must have previously
201created the corresponding named or unnamed statement with
202:meth:`Connection.prepare`, or an :exc:`pg.OperationalError` will be raised.
203
204.. versionadded:: 5.1
205
206prepare -- create a prepared statement
207--------------------------------------
208
209.. method:: Connection.prepare(name, command)
210
211    Create a prepared statement
212
213    :param str name: name of the prepared statement
214    :param str command: SQL command
215    :rtype: None
216    :raises TypeError: bad argument types, or wrong number of arguments
217    :raises TypeError: invalid connection
218    :raises pg.ProgrammingError: error in query or duplicate query
219
220This method creates a prepared statement with the specified name for the
221given command for later execution with the :meth:`Connection.query_prepared`
222method. The name can be empty to create an unnamed statement, in which case
223any pre-existing unnamed statement is automatically replaced; otherwise a
224:exc:`pg.ProgrammingError` is raised if the statement name is already defined
225in the current database session.
226
227The SQL command may optionally contain positional parameters of the form
228``$1``, ``$2``, etc instead of literal data.  The corresponding values
229must then later be passed to the :meth:`Connection.query_prepared` method
230separately as a tuple.
231
232.. versionadded:: 5.1
233
234describe_prepared -- describe a prepared statement
235--------------------------------------------------
236
237.. method:: Connection.describe_prepared(name)
238
239    Describe a prepared statement
240
241    :param str name: name of the prepared statement
242    :rtype: :class:`Query`
243    :raises TypeError: bad argument type, or too many arguments
244    :raises TypeError: invalid connection
245    :raises pg.OperationalError: prepared statement does not exist
246
247This method returns a :class:`Query` object describing the prepared
248statement with the given name.  You can also pass an empty name in order
249to describe the unnamed statement.  Information on the fields of the
250corresponding query can be obtained through the :meth:`Query.listfields`,
251:meth:`Query.fieldname` and :meth:`Query.fieldnum` methods.
252
253.. versionadded:: 5.1
254
255reset -- reset the connection
256-----------------------------
257
258.. method:: Connection.reset()
259
260    Reset the :mod:`pg` connection
261
262    :rtype: None
263    :raises TypeError: too many (any) arguments
264    :raises TypeError: invalid connection
265
266This method resets the current database connection.
267
268poll - completes an asynchronous connection
269-------------------------------------------
270
271.. method:: Connection.poll()
272
273    Complete an asynchronous :mod:`pg` connection and get its state
274
275    :returns: state of the connection
276    :rtype: int
277    :raises TypeError: too many (any) arguments
278    :raises TypeError: invalid connection
279    :raises pg.InternalError: some error occurred during pg connection
280
281The database connection can be performed without any blocking calls.
282This allows the application mainline to perform other operations or perhaps
283connect to multiple databases concurrently. Once the connection is established,
284it's no different from a connection made using blocking calls.
285
286The required steps are to pass the parameter ``nowait=True`` to  the
287:meth:`pg.connect` call, then call :meth:`Connection.poll` until it either
288returns :const':`POLLING_OK` or raises an exception. To avoid blocking
289in :meth:`Connection.poll`, use `select()` or `poll()` to wait for the
290connection to be readable or writable, depending on the return code of the
291previous call to :meth:`Connection.poll`. The initial state of the connection
292is :const:`POLLING_WRITING`. The possible states are defined as constants in
293the :mod:`pg` module (:const:`POLLING_OK`, :const:`POLLING_FAILED`,
294:const:`POLLING_READING` and :const:`POLLING_WRITING`).
295
296.. versionadded:: 5.2
297
298Example::
299
300    con = pg.connect('testdb', nowait=True)
301    fileno = con.fileno()
302    rd = []
303    wt = [fileno]
304    rc = pg.POLLING_WRITING
305    while rc not in (pg.POLLING_OK, pg.POLLING_FAILED):
306        ra, wa, xa = select(rd, wt, [], timeout)
307        if not ra and not wa:
308            timedout()
309        rc = con.poll()
310        if rc == pg.POLLING_READING:
311            rd = [fileno]
312            wt = []
313        else:
314            rd = []
315            wt = [fileno]
316
317
318cancel -- abandon processing of current SQL command
319---------------------------------------------------
320
321.. method:: Connection.cancel()
322
323    :rtype: None
324    :raises TypeError: too many (any) arguments
325    :raises TypeError: invalid connection
326
327This method requests that the server abandon processing
328of the current SQL command.
329
330close -- close the database connection
331--------------------------------------
332
333.. method:: Connection.close()
334
335    Close the :mod:`pg` connection
336
337    :rtype: None
338    :raises TypeError: too many (any) arguments
339
340This method closes the database connection. The connection will
341be closed in any case when the connection is deleted but this
342allows you to explicitly close it. It is mainly here to allow
343the DB-SIG API wrapper to implement a close function.
344
345transaction -- get the current transaction state
346------------------------------------------------
347
348.. method:: Connection.transaction()
349
350    Get the current in-transaction status of the server
351
352    :returns: the current in-transaction status
353    :rtype: int
354    :raises TypeError: too many (any) arguments
355    :raises TypeError: invalid connection
356
357The status returned by this method can be :const:`TRANS_IDLE` (currently idle),
358:const:`TRANS_ACTIVE` (a command is in progress), :const:`TRANS_INTRANS` (idle,
359in a valid transaction block), or :const:`TRANS_INERROR` (idle, in a failed
360transaction block).  :const:`TRANS_UNKNOWN` is reported if the connection is
361bad.  The status :const:`TRANS_ACTIVE` is reported only when a query has been
362sent to the server and not yet completed.
363
364parameter -- get a current server parameter setting
365---------------------------------------------------
366
367.. method:: Connection.parameter(name)
368
369    Look up a current parameter setting of the server
370
371    :param str name: the name of the parameter to look up
372    :returns: the current setting of the specified parameter
373    :rtype: str or None
374    :raises TypeError: too many (any) arguments
375    :raises TypeError: invalid connection
376
377Certain parameter values are reported by the server automatically at
378connection startup or whenever their values change.  This method can be used
379to interrogate these settings.  It returns the current value of a parameter
380if known, or *None* if the parameter is not known.
381
382You can use this method to check the settings of important parameters such as
383`server_version`, `server_encoding`, `client_encoding`, `application_name`,
384`is_superuser`, `session_authorization`, `DateStyle`, `IntervalStyle`,
385`TimeZone`, `integer_datetimes`, and `standard_conforming_strings`.
386
387Values that are not reported by this method can be requested using
388:meth:`DB.get_parameter`.
389
390.. versionadded:: 4.0
391
392date_format -- get the currently used date format
393-------------------------------------------------
394
395.. method:: Connection.date_format()
396
397    Look up the date format currently being used by the database
398
399    :returns: the current date format
400    :rtype: str
401    :raises TypeError: too many (any) arguments
402    :raises TypeError: invalid connection
403
404This method returns the current date format used by the server.  Note that
405it is cheap to call this method, since there is no database query involved
406and the setting is also cached internally.  You will need the date format
407when you want to manually typecast dates and timestamps coming from the
408database instead of using the built-in typecast functions.  The date format
409returned by this method can be directly used with date formatting functions
410such as :meth:`datetime.strptime`.  It is derived from the current setting
411of the database parameter ``DateStyle``.
412
413.. versionadded:: 5.0
414
415fileno -- get the socket used to connect to the database
416--------------------------------------------------------
417
418.. method:: Connection.fileno()
419
420    Get the socket used to connect to the database
421
422    :returns: the socket id of the database connection
423    :rtype: int
424    :raises TypeError: too many (any) arguments
425    :raises TypeError: invalid connection
426
427This method returns the underlying socket id used to connect
428to the database. This is useful for use in select calls, etc.
429
430set_non_blocking - set the non-blocking status of the connection
431----------------------------------------------------------------
432
433.. method:: set_non_blocking(nb)
434
435    Set the non-blocking mode of the connection
436
437    :param bool nb: True to put the connection into non-blocking mode.
438                    False to put it into blocking mode.
439    :raises TypeError: too many parameters
440    :raises TypeError: invalid connection
441
442Puts the socket connection into non-blocking mode or into blocking mode.
443This affects copy commands and large object operations, but not queries.
444
445.. versionadded:: 5.2
446
447is_non_blocking - report the blocking status of the connection
448--------------------------------------------------------------
449
450.. method:: is_non_blocking()
451
452    get the non-blocking mode of the connection
453
454    :returns: True if the connection is in non-blocking mode.
455              False if it is in blocking mode.
456    :rtype: bool
457    :raises TypeError: too many parameters
458    :raises TypeError: invalid connection
459
460Returns True if the connection is in non-blocking mode, False otherwise.
461
462.. versionadded:: 5.2
463
464getnotify -- get the last notify from the server
465------------------------------------------------
466
467.. method:: Connection.getnotify()
468
469    Get the last notify from the server
470
471    :returns: last notify from server
472    :rtype: tuple, None
473    :raises TypeError: too many parameters
474    :raises TypeError: invalid connection
475
476This method tries to get a notify from the server (from the SQL statement
477NOTIFY). If the server returns no notify, the methods returns None.
478Otherwise, it returns a tuple (triplet) *(relname, pid, extra)*, where
479*relname* is the name of the notify, *pid* is the process id of the
480connection that triggered the notify, and *extra* is a payload string
481that has been sent with the notification. Remember to do a listen query
482first, otherwise :meth:`Connection.getnotify` will always return ``None``.
483
484.. versionchanged:: 4.1
485    Support for payload strings was added in version 4.1.
486
487inserttable -- insert a list into a table
488-----------------------------------------
489
490.. method:: Connection.inserttable(table, values, [columns])
491
492    Insert a Python list into a database table
493
494    :param str table: the table name
495    :param list values: list of rows values
496    :param list columns: list of column names
497    :rtype: None
498    :raises TypeError: invalid connection, bad argument type, or too many arguments
499    :raises MemoryError: insert buffer could not be allocated
500    :raises ValueError: unsupported values
501
502This method allows to *quickly* insert large blocks of data in a table:
503It inserts the whole values list into the given table. Internally, it
504uses the COPY command of the PostgreSQL database. The list is a list
505of tuples/lists that define the values for each inserted row. The rows
506values may contain string, integer, long or double (real) values.
507``columns`` is an optional sequence of column names to be passed on
508to the COPY command.
509
510.. warning::
511
512    This method doesn't type check the fields according to the table definition;
513    it just looks whether or not it knows how to handle such types.
514
515get/set_cast_hook -- fallback typecast function
516-----------------------------------------------
517
518.. method:: Connection.get_cast_hook()
519
520    Get the function that handles all external typecasting
521
522    :returns: the current external typecast function
523    :rtype: callable, None
524    :raises TypeError: too many (any) arguments
525
526This returns the callback function used by PyGreSQL to provide plug-in
527Python typecast functions for the connection.
528
529.. versionadded:: 5.0
530
531.. method:: Connection.set_cast_hook(func)
532
533    Set a function that will handle all external typecasting
534
535    :param func: the function to be used as a callback
536    :rtype: None
537    :raises TypeError: the specified notice receiver is not callable
538
539This methods allows setting a custom fallback function for providing
540Python typecast functions for the connection to supplement the C
541extension module.  If you set this function to *None*, then only the typecast
542functions implemented in the C extension module are enabled.  You normally
543would not want to change this.  Instead, you can use :func:`get_typecast` and
544:func:`set_typecast` to add or change the plug-in Python typecast functions.
545
546.. versionadded:: 5.0
547
548get/set_notice_receiver -- custom notice receiver
549-------------------------------------------------
550
551.. method:: Connection.get_notice_receiver()
552
553    Get the current notice receiver
554
555    :returns: the current notice receiver callable
556    :rtype: callable, None
557    :raises TypeError: too many (any) arguments
558
559This method gets the custom notice receiver callback function that has
560been set with :meth:`Connection.set_notice_receiver`, or ``None`` if no
561custom notice receiver has ever been set on the connection.
562
563.. versionadded:: 4.1
564
565.. method:: Connection.set_notice_receiver(func)
566
567    Set a custom notice receiver
568
569    :param func: the custom notice receiver callback function
570    :rtype: None
571    :raises TypeError: the specified notice receiver is not callable
572
573This method allows setting a custom notice receiver callback function.
574When a notice or warning message is received from the server,
575or generated internally by libpq, and the message level is below
576the one set with ``client_min_messages``, the specified notice receiver
577function will be called. This function must take one parameter,
578the :class:`Notice` object, which provides the following read-only
579attributes:
580
581    .. attribute:: Notice.pgcnx
582
583        the connection
584
585    .. attribute:: Notice.message
586
587        the full message with a trailing newline
588
589    .. attribute:: Notice.severity
590
591        the level of the message, e.g. 'NOTICE' or 'WARNING'
592
593    .. attribute:: Notice.primary
594
595        the primary human-readable error message
596
597    .. attribute:: Notice.detail
598
599        an optional secondary error message
600
601    .. attribute:: Notice.hint
602
603        an optional suggestion what to do about the problem
604
605.. versionadded:: 4.1
606
607putline -- write a line to the server socket [DA]
608-------------------------------------------------
609
610.. method:: Connection.putline(line)
611
612    Write a line to the server socket
613
614    :param str line: line to be written
615    :rtype: None
616    :raises TypeError: invalid connection, bad parameter type, or too many parameters
617
618This method allows to directly write a string to the server socket.
619
620getline -- get a line from server socket [DA]
621---------------------------------------------
622
623.. method:: Connection.getline()
624
625    Get a line from server socket
626
627    :returns:  the line read
628    :rtype: str
629    :raises TypeError: invalid connection
630    :raises TypeError: too many parameters
631    :raises MemoryError: buffer overflow
632
633This method allows to directly read a string from the server socket.
634
635endcopy -- synchronize client and server [DA]
636---------------------------------------------
637
638.. method:: Connection.endcopy()
639
640    Synchronize client and server
641
642    :rtype: None
643    :raises TypeError: invalid connection
644    :raises TypeError: too many parameters
645
646The use of direct access methods may desynchronize client and server.
647This method ensure that client and server will be synchronized.
648
649locreate -- create a large object in the database [LO]
650------------------------------------------------------
651
652.. method:: Connection.locreate(mode)
653
654    Create a large object in the database
655
656    :param int mode: large object create mode
657    :returns: object handling the PostgreSQL large object
658    :rtype: :class:`LargeObject`
659    :raises TypeError: invalid connection, bad parameter type, or too many parameters
660    :raises pg.OperationalError: creation error
661
662This method creates a large object in the database. The mode can be defined
663by OR-ing the constants defined in the :mod:`pg` module (:const:`INV_READ`,
664and :const:`INV_WRITE`). Please refer to PostgreSQL user manual for a
665description of the mode values.
666
667getlo -- build a large object from given oid [LO]
668-------------------------------------------------
669
670.. method:: Connection.getlo(oid)
671
672    Create a large object in the database
673
674    :param int oid: OID of the existing large object
675    :returns: object handling the PostgreSQL large object
676    :rtype: :class:`LargeObject`
677    :raises TypeError:  invalid connection, bad parameter type, or too many parameters
678    :raises ValueError: bad OID value (0 is invalid_oid)
679
680This method allows reusing a previously created large object through the
681:class:`LargeObject` interface, provided the user has its OID.
682
683loimport -- import a file to a large object [LO]
684------------------------------------------------
685
686.. method:: Connection.loimport(name)
687
688    Import a file to a large object
689
690    :param str name: the name of the file to be imported
691    :returns: object handling the PostgreSQL large object
692    :rtype: :class:`LargeObject`
693    :raises TypeError: invalid connection, bad argument type, or too many arguments
694    :raises pg.OperationalError: error during file import
695
696This methods allows to create large objects in a very simple way. You just
697give the name of a file containing the data to be used.
698
699Object attributes
700-----------------
701Every :class:`Connection` defines a set of read-only attributes that describe
702the connection and its status. These attributes are:
703
704.. attribute:: Connection.host
705
706    the host name of the server (str)
707
708.. attribute:: Connection.port
709
710    the port of the server (int)
711
712.. attribute:: Connection.db
713
714    the selected database (str)
715
716.. attribute:: Connection.options
717
718    the connection options (str)
719
720.. attribute:: Connection.user
721
722    user name on the database system (str)
723
724.. attribute:: Connection.protocol_version
725
726    the frontend/backend protocol being used (int)
727
728.. versionadded:: 4.0
729
730.. attribute:: Connection.server_version
731
732    the backend version (int, e.g. 90305 for 9.3.5)
733
734.. versionadded:: 4.0
735
736.. attribute:: Connection.status
737
738    the status of the connection (int: 1 = OK, 0 = bad)
739
740.. attribute:: Connection.error
741
742    the last warning/error message from the server (str)
743
744.. attribute:: Connection.socket
745
746    the file descriptor number of the connection socket to the server (int)
747
748.. versionadded:: 5.1
749
750.. attribute:: Connection.backend_pid
751
752     the PID of the backend process handling this connection (int)
753
754.. versionadded:: 5.1
755
756.. attribute:: Connection.ssl_in_use
757
758     this is True if the connection uses SSL, False if not
759
760.. versionadded:: 5.1 (needs PostgreSQL >= 9.5)
761
762.. attribute:: Connection.ssl_attributes
763
764     SSL-related information about the connection (dict)
765
766.. versionadded:: 5.1 (needs PostgreSQL >= 9.5)
767