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

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

Add version information for new/changed features to docs

File size: 11.9 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
146.. versionchanged:: 4.1
147    Support for payload strings was added in version 4.1.
148
149inserttable -- insert a list into a table
150-----------------------------------------
151
152.. method:: pgobject.inserttable(table, values)
153
154    Insert a Python list into a database table
155
156    :param str table: the table name
157    :param list values: list of rows values
158    :rtype: None
159    :raises TypeError: invalid connection, bad argument type, or too many arguments
160    :raises MemoryError: insert buffer could not be allocated
161    :raises ValueError: unsupported values
162
163This method allows to *quickly* insert large blocks of data in a table:
164It inserts the whole values list into the given table. Internally, it
165uses the COPY command of the PostgreSQL database. The list is a list
166of tuples/lists that define the values for each inserted row. The rows
167values may contain string, integer, long or double (real) values.
168
169.. note::
170
171   **Be very careful**:
172   This method doesn't type check the fields according to the table definition;
173   it just look whether or not it knows how to handle such types.
174
175get/set_notice_receiver -- custom notice receiver
176-------------------------------------------------
177
178.. method:: pgobject.get_notice_receiver()
179
180    Get the current notice receiver
181
182    :returns: the current notice receiver callable
183    :rtype: callable, None
184    :raises TypeError: too many (any) arguments
185
186This method gets the custom notice receiver callback function that has
187been set with :meth:`pgobject.set_notice_receiver`, or ``None`` if no
188custom notice receiver has ever been set on the connection.
189
190.. versionadded:: 4.1
191
192.. method:: pgobject.set_notice_receiver(proc)
193
194    Set a custom notice receiver
195
196    :param proc: the custom notice receiver callback function
197    :rtype: None
198    :raises TypeError: the specified notice receiver is not callable
199
200This method allows setting a custom notice receiver callback function.
201When a notice or warning message is received from the server,
202or generated internally by libpq, and the message level is below
203the one set with ``client_min_messages``, the specified notice receiver
204function will be called. This function must take one parameter,
205the :class:`pgnotice` object, which provides the following read-only
206attributes:
207
208    .. attribute:: pgnotice.pgcnx
209
210        the connection
211
212    .. attribute:: pgnotice.message
213
214        the full message with a trailing newline
215
216    .. attribute:: pgnotice.severity
217
218        the level of the message, e.g. 'NOTICE' or 'WARNING'
219
220    .. attribute:: pgnotice.primary
221
222        the primary human-readable error message
223
224    .. attribute:: pgnotice.detail
225
226        an optional secondary error message
227
228    .. attribute:: pgnotice.hint
229
230        an optional suggestion what to do about the problem
231
232.. versionadded:: 4.1
233
234putline -- write a line to the server socket [DA]
235-------------------------------------------------
236
237.. method:: pgobject.putline(line)
238
239    Write a line to the server socket
240
241    :param str line: line to be written
242    :rtype: None
243    :raises TypeError: invalid connection, bad parameter type, or too many parameters
244
245This method allows to directly write a string to the server socket.
246
247getline -- get a line from server socket [DA]
248---------------------------------------------
249
250.. method:: pgobject.getline()
251
252    Get a line from server socket
253
254    :returns:  the line read
255    :rtype: str
256    :raises TypeError: invalid connection
257    :raises TypeError: too many parameters
258    :raises MemoryError: buffer overflow
259
260This method allows to directly read a string from the server socket.
261
262endcopy -- synchronize client and server [DA]
263---------------------------------------------
264
265.. method:: pgobject.endcopy()
266
267    Synchronize client and server
268
269    :rtype: None
270    :raises TypeError: invalid connection
271    :raises TypeError: too many parameters
272
273The use of direct access methods may desynchronize client and server.
274This method ensure that client and server will be synchronized.
275
276locreate -- create a large object in the database [LO]
277------------------------------------------------------
278
279.. method:: pgobject.locreate(mode)
280
281    Create a large object in the database
282
283    :param int mode: large object create mode
284    :returns: object handling the PostGreSQL large object
285    :rtype: :class:`pglarge`
286    :raises TypeError: invalid connection, bad parameter type, or too many parameters
287    :raises pg.OperationalError: creation error
288
289This method creates a large object in the database. The mode can be defined
290by OR-ing the constants defined in the :mod:`pg` module (:const:`INV_READ`,
291:const:`INV_WRITE` and :const:`INV_ARCHIVE`). Please refer to PostgreSQL
292user manual for a description of the mode values.
293
294getlo -- build a large object from given oid [LO]
295-------------------------------------------------
296
297.. method:: pgobject.getlo(oid)
298
299    Create a large object in the database
300
301    :param int oid: OID of the existing large object
302    :returns: object handling the PostGreSQL large object
303    :rtype: :class:`pglarge`
304    :raises TypeError:  invalid connection, bad parameter type, or too many parameters
305    :raises ValueError: bad OID value (0 is invalid_oid)
306
307This method allows to reuse a formerly created large object through the
308:class:`pglarge` interface, providing the user have its OID.
309
310loimport -- import a file to a large object [LO]
311------------------------------------------------
312
313.. method:: pgobject.loimport(name)
314
315    Import a file to a large object
316
317    :param str name: the name of the file to be imported
318    :returns: object handling the PostGreSQL large object
319    :rtype: :class:`pglarge`
320    :raises TypeError: invalid connection, bad argument type, or too many arguments
321    :raises pg.OperationalError: error during file import
322
323This methods allows to create large objects in a very simple way. You just
324give the name of a file containing the data to be used.
325
326Object attributes
327-----------------
328Every :class:`pgobject` defines a set of read-only attributes that describe
329the connection and its status. These attributes are:
330
331.. attribute:: pgobject.host
332
333   the host name of the server (str)
334
335.. attribute:: pgobject.port
336
337   the port of the server (int)
338
339.. attribute:: pgobject.db
340
341   the selected database (str)
342
343.. attribute:: pgobject.options
344
345   the connection options (str)
346
347.. attribute:: pgobject.tty
348
349   the connection debug terminal (str)
350
351.. attribute:: pgobject.user
352
353    user name on the database system (str)
354
355.. attribute:: pgobject.protocol_version
356
357   the frontend/backend protocol being used (int)
358
359.. versionadded:: 4.0
360
361.. attribute:: pgobject.server_version
362
363   the backend version (int, e.g. 80305 for 8.3.5)
364
365.. versionadded:: 4.0
366
367.. attribute:: pgobject.status
368
369   the status of the connection (int: 1 = OK, 0 = bad)
370
371.. attribute:: pgobject.error
372
373   the last warning/error message from the server (str)
Note: See TracBrowser for help on using the repository browser.