source: branches/4.x/docs/contents/pg/connection.rst @ 695

Last change on this file since 695 was 695, checked in by cito, 4 years ago

Reorganize and improve the Sphinx docs

The Sphinx HTML docs can now also serve as home page for the project.
They can be built with the mkdocs script and can then be found in the
docs/_build/html directory (this needs sphinx and the cloud_sptheme).

The "actual" core docs can be found in docs/contents. The layout has
been modified to only show these pages with the typical documentation
relbars; the other pages of the homepage use a simpler layout. The
pg and pgdb documentation has been cut in chunks and can now be found
in docs/contents/pg and docs/contents/pgdb.

File size: 11.7 KB
Line 
1pgobject -- The connection object
2=================================
3
4.. class:: pgobject
5
6This object handles a connection to a PostgreSQL database. It embeds and
7hides all the parameters that define this connection, thus just leaving really
8significant parameters in function calls.
9
10.. note::
11
12    Some methods give direct access to the connection socket.
13    *Do not use them unless you really know what you are doing.*
14    If you prefer disabling them,
15    set the ``-DNO_DIRECT`` option in the Python setup file.
16    These methods are specified by the tag [DA].
17
18.. note::
19
20    Some other methods give access to large objects
21    (refer to PostgreSQL user manual for more information about these).
22    If you want to forbid access to these from the module,
23    set the ``-DNO_LARGE`` option in the Python setup file.
24    These methods are specified by the tag [LO].
25
26query -- execute a SQL command string
27-------------------------------------
28
29.. method:: pgobject.query(command, [args])
30
31    Execute a SQL command string
32
33    :param str command: SQL command
34    :param args: optional positional arguments
35    :returns: result values
36    :rtype: :class:`pgqueryobject`, None
37    :raises TypeError: bad argument type, or too many arguments
38    :raises TypeError: invalid connection
39    :raises ValueError: empty SQL query or lost connection
40    :raises pg.ProgrammingError: error in query
41    :raises pg.InternalError: error during query processing
42
43This method simply sends a SQL query to the database. If the query is an
44insert statement that inserted exactly one row into a table that has OIDs, the
45return value is the OID of the newly inserted row. If the query is an update
46or delete statement, or an insert statement that did not insert exactly one
47row in a table with OIDs, then the number of rows affected is returned as a
48string. If it is a statement that returns rows as a result (usually a select
49statement, but maybe also an ``"insert/update ... returning"`` statement),
50this method returns a :class:`pgqueryobject` that can be accessed via the
51:meth:`pgqueryobject.getresult`, :meth:`pgqueryobject.dictresult` or
52:meth:`pgqueryobject.namedresult` methods or simply printed.
53Otherwise, it returns ``None``.
54
55The query may optionally contain positional parameters of the form ``$1``,
56``$2``, etc instead of literal data, and the values supplied as a tuple.
57The values are substituted by the database in such a way that they don't
58need to be escaped, making this an effective way to pass arbitrary or
59unknown data without worrying about SQL injection or syntax errors.
60
61When the database could not process the query, a :exc:`pg.ProgrammingError` or
62a :exc:`pg.InternalError` is raised. You can check the ``SQLSTATE`` code of
63this error by reading its :attr:`sqlstate` attribute.
64
65Example::
66
67    name = raw_input("Name? ")
68    phone = con.query("select phone from employees where name=$1",
69        (name,)).getresult()
70
71reset -- reset the connection
72-----------------------------
73
74.. method:: pgobject.reset()
75
76    Reset the :mod:`pg` connection
77
78    :rtype: None
79    :raises TypeError: too many (any) arguments
80    :raises TypeError: invalid connection
81
82This method resets the current database connection.
83
84cancel -- abandon processing of current SQL command
85---------------------------------------------------
86
87.. method:: pgobject.cancel()
88
89    :rtype: None
90    :raises TypeError: too many (any) arguments
91    :raises TypeError: invalid connection
92
93This method requests that the server abandon processing
94of the current SQL command.
95
96close -- close the database connection
97--------------------------------------
98
99.. method:: pgobject.close()
100
101    Close the :mod:`pg` connection
102
103    :rtype: None
104    :raises TypeError: too many (any) arguments
105
106This method closes the database connection. The connection will
107be closed in any case when the connection is deleted but this
108allows you to explicitly close it. It is mainly here to allow
109the DB-SIG API wrapper to implement a close function.
110
111fileno -- returns the socket used to connect to the database
112------------------------------------------------------------
113
114.. method:: pgobject.fileno()
115
116    Return the socket used to connect to the database
117
118    :returns: the socket id of the database connection
119    :rtype: int
120    :raises TypeError: too many (any) arguments
121    :raises TypeError: invalid connection
122
123This method returns the underlying socket id used to connect
124to the database. This is useful for use in select calls, etc.
125
126getnotify -- get the last notify from the server
127------------------------------------------------
128
129.. method:: pgobject.getnotify()
130
131    Get the last notify from the server
132
133    :returns: last notify from server
134    :rtype: tuple, None
135    :raises TypeError: too many parameters
136    :raises TypeError: invalid connection
137
138This method tries to get a notify from the server (from the SQL statement
139NOTIFY). If the server returns no notify, the methods returns None.
140Otherwise, it returns a tuple (triplet) *(relname, pid, extra)*, where
141*relname* is the name of the notify, *pid* is the process id of the
142connection that triggered the notify, and *extra* is a payload string
143that has been sent with the notification. Remember to do a listen query
144first, otherwise :meth:`pgobject.getnotify` will always return ``None``.
145
146inserttable -- insert a list into a table
147-----------------------------------------
148
149.. method:: pgobject.inserttable(table, values)
150
151    Insert a Python list into a database table
152
153    :param str table: the table name
154    :param list values: list of rows values
155    :rtype: None
156    :raises TypeError: invalid connection, bad argument type, or too many arguments
157    :raises MemoryError: insert buffer could not be allocated
158    :raises ValueError: unsupported values
159
160This method allows to *quickly* insert large blocks of data in a table:
161It inserts the whole values list into the given table. Internally, it
162uses the COPY command of the PostgreSQL database. The list is a list
163of tuples/lists that define the values for each inserted row. The rows
164values may contain string, integer, long or double (real) values.
165
166.. note::
167
168   **Be very careful**:
169   This method doesn't type check the fields according to the table definition;
170   it just look whether or not it knows how to handle such types.
171
172get/set_notice_receiver -- custom notice receiver
173-------------------------------------------------
174
175.. method:: pgobject.get_notice_receiver()
176
177    Get the current notice receiver
178
179    :returns: the current notice receiver callable
180    :rtype: callable, None
181    :raises TypeError: too many (any) arguments
182
183This method gets the custom notice receiver callback function that has
184been set with :meth:`pgobject.set_notice_receiver`, or ``None`` if no
185custom notice receiver has ever been set on the connection.
186
187.. method:: pgobject.set_notice_receiver(proc)
188
189    Set a custom notice receiver
190
191    :param proc: the custom notice receiver callback function
192    :rtype: None
193    :raises TypeError: the specified notice receiver is not callable
194
195This method allows setting a custom notice receiver callback function.
196When a notice or warning message is received from the server,
197or generated internally by libpq, and the message level is below
198the one set with ``client_min_messages``, the specified notice receiver
199function will be called. This function must take one parameter,
200the :class:`pgnotice` object, which provides the following read-only
201attributes:
202
203    .. attribute:: pgnotice.pgcnx
204
205        the connection
206
207    .. attribute:: pgnotice.message
208
209        the full message with a trailing newline
210
211    .. attribute:: pgnotice.severity
212
213        the level of the message, e.g. 'NOTICE' or 'WARNING'
214
215    .. attribute:: pgnotice.primary
216
217        the primary human-readable error message
218
219    .. attribute:: pgnotice.detail
220
221        an optional secondary error message
222
223    .. attribute:: pgnotice.hint
224
225        an optional suggestion what to do about the problem
226
227putline -- write a line to the server socket [DA]
228-------------------------------------------------
229
230.. method:: pgobject.putline(line)
231
232    Write a line to the server socket
233
234    :param str line: line to be written
235    :rtype: None
236    :raises TypeError: invalid connection, bad parameter type, or too many parameters
237
238This method allows to directly write a string to the server socket.
239
240getline -- get a line from server socket [DA]
241---------------------------------------------
242
243.. method:: pgobject.getline()
244
245    Get a line from server socket
246
247    :returns:  the line read
248    :rtype: str
249    :raises TypeError: invalid connection
250    :raises TypeError: too many parameters
251    :raises MemoryError: buffer overflow
252
253This method allows to directly read a string from the server socket.
254
255endcopy -- synchronize client and server [DA]
256---------------------------------------------
257
258.. method:: pgobject.endcopy()
259
260    Synchronize client and server
261
262    :rtype: None
263    :raises TypeError: invalid connection
264    :raises TypeError: too many parameters
265
266The use of direct access methods may desynchronize client and server.
267This method ensure that client and server will be synchronized.
268
269locreate -- create a large object in the database [LO]
270------------------------------------------------------
271
272.. method:: pgobject.locreate(mode)
273
274    Create a large object in the database
275
276    :param int mode: large object create mode
277    :returns: object handling the PostGreSQL large object
278    :rtype: :class:`pglarge`
279    :raises TypeError: invalid connection, bad parameter type, or too many parameters
280    :raises pg.OperationalError: creation error
281
282This method creates a large object in the database. The mode can be defined
283by OR-ing the constants defined in the :mod:`pg` module (:const:`INV_READ`,
284:const:`INV_WRITE` and :const:`INV_ARCHIVE`). Please refer to PostgreSQL
285user manual for a description of the mode values.
286
287getlo -- build a large object from given oid [LO]
288-------------------------------------------------
289
290.. method:: pgobject.getlo(oid)
291
292    Create a large object in the database
293
294    :param int oid: OID of the existing large object
295    :returns: object handling the PostGreSQL large object
296    :rtype: :class:`pglarge`
297    :raises TypeError:  invalid connection, bad parameter type, or too many parameters
298    :raises ValueError: bad OID value (0 is invalid_oid)
299
300This method allows to reuse a formerly created large object through the
301:class:`pglarge` interface, providing the user have its OID.
302
303loimport -- import a file to a large object [LO]
304------------------------------------------------
305
306.. method:: pgobject.loimport(name)
307
308    Import a file to a large object
309
310    :param str name: the name of the file to be imported
311    :returns: object handling the PostGreSQL large object
312    :rtype: :class:`pglarge`
313    :raises TypeError: invalid connection, bad argument type, or too many arguments
314    :raises pg.OperationalError: error during file import
315
316This methods allows to create large objects in a very simple way. You just
317give the name of a file containing the data to be used.
318
319Object attributes
320-----------------
321Every :class:`pgobject` defines a set of read-only attributes that describe
322the connection and its status. These attributes are:
323
324.. attribute:: pgobject.host
325
326   the host name of the server (str)
327
328.. attribute:: pgobject.port
329
330   the port of the server (int)
331
332.. attribute:: pgobject.db
333
334   the selected database (str)
335
336.. attribute:: pgobject.options
337
338   the connection options (str)
339
340.. attribute:: pgobject.tty
341
342   the connection debug terminal (str)
343
344.. attribute:: pgobject.user
345
346    user name on the database system (str)
347
348.. attribute:: pgobject.protocol_version
349
350   the frontend/backend protocol being used (int)
351
352.. attribute:: pgobject.server_version
353
354   the backend version (int, e.g. 80305 for 8.3.5)
355
356.. attribute:: pgobject.status
357
358   the status of the connection (int: 1 = OK, 0 = bad)
359
360.. attribute:: pgobject.error
361
362   the last warning/error message from the server (str)
Note: See TracBrowser for help on using the repository browser.