source: branches/4.x/docs/contents/pg/module.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: 16.8 KB
Line 
1Module functions and constants
2==============================
3
4The :mod:`pg` module defines a few functions that allow to connect
5to a database and to define "default variables" that override
6the environment variables used by PostgreSQL.
7
8These "default variables" were designed to allow you to handle general
9connection parameters without heavy code in your programs. You can prompt the
10user for a value, put it in the default variable, and forget it, without
11having to modify your environment. The support for default variables can be
12disabled by setting the ``-DNO_DEF_VAR`` option in the Python setup file.
13Methods relative to this are specified by the tag [DV].
14
15All variables are set to ``None`` at module initialization, specifying that
16standard environment variables should be used.
17
18connect -- Open a PostgreSQL connection
19---------------------------------------
20
21.. function:: pg.connect([dbname], [host], [port], [opt], [tty], [user], [passwd])
22
23    Open a :mod:`pg` connection
24
25    :param dbname: name of connected database (*None* = :data:`defbase`)
26    :type str: str or None
27    :param host: name of the server host (*None* = :data:`defhost`)
28    :type host:  str or None
29    :param port: port used by the database server (-1 = :data:`defport`)
30    :type port: int
31    :param opt: connection options (*None* = :data:`defopt`)
32    :type opt: str or None
33    :param tty: debug terminal (*None* = :data:`deftty`)
34    :type tty: str or None
35    :param user: PostgreSQL user (*None* = :data:`defuser`)
36    :type user: str or None
37    :param passwd: password for user (*None* = :data:`defpasswd`)
38    :type passwd: str or None
39    :returns: If successful, the :class:`pgobject` handling the connection
40    :rtype: :class:`pgobject`
41    :raises TypeError: bad argument type, or too many arguments
42    :raises SyntaxError: duplicate argument definition
43    :raises pg.InternalError: some error occurred during pg connection definition
44    :raises Exception: (all exceptions relative to object allocation)
45
46This function opens a connection to a specified database on a given
47PostgreSQL server. You can use keywords here, as described in the
48Python tutorial. The names of the keywords are the name of the
49parameters given in the syntax line. For a precise description
50of the parameters, please refer to the PostgreSQL user manual.
51
52Example::
53
54    import pg
55
56    con1 = pg.connect('testdb', 'myhost', 5432, None, None, 'bob', None)
57    con2 = pg.connect(dbname='testdb', host='localhost', user='bob')
58
59get/set_defhost -- default server host [DV]
60-------------------------------------------
61
62.. function:: get_defhost(host)
63
64    Get the default host
65
66    :returns: the current default host specification
67    :rtype: str or None
68    :raises TypeError: too many arguments
69
70This method returns the current default host specification,
71or ``None`` if the environment variables should be used.
72Environment variables won't be looked up.
73
74.. function:: set_defhost(host)
75
76    Set the default host
77
78    :param host: the new default host specification
79    :type host: str or None
80    :returns: the previous default host specification
81    :rtype: str or None
82    :raises TypeError: bad argument type, or too many arguments
83
84This methods sets the default host value for new connections.
85If ``None`` is supplied as parameter, environment variables will
86be used in future connections. It returns the previous setting
87for default host.
88
89get/set_defport -- default server port [DV]
90-------------------------------------------
91
92.. function:: get_defport()
93
94    Get the default port
95
96    :returns: the current default port specification
97    :rtype: int
98    :raises TypeError: too many arguments
99
100This method returns the current default port specification,
101or ``None`` if the environment variables should be used.
102Environment variables won't be looked up.
103
104.. function::  set_defport(port)
105
106    Set the default port
107
108    :param port: the new default port
109    :type port: int
110    :returns: previous default port specification
111    :rtype: int or None
112
113This methods sets the default port value for new connections. If -1 is
114supplied as parameter, environment variables will be used in future
115connections. It returns the previous setting for default port.
116
117get/set_defopt --  default connection options [DV]
118--------------------------------------------------
119
120.. function:: get_defopt()
121
122    Get the default connection options
123
124    :returns: the current default options specification
125    :rtype: str or None
126    :raises TypeError: too many arguments
127
128This method returns the current default connection options specification,
129or ``None`` if the environment variables should be used. Environment variables
130won't be looked up.
131
132.. function:: set_defopt(options)
133
134    Set the default connection options
135
136    :param options: the new default connection options
137    :type options: str or None
138    :returns: previous default options specification
139    :rtype: str or None
140    :raises TypeError: bad argument type, or too many arguments
141
142This methods sets the default connection options value for new connections.
143If ``None`` is supplied as parameter, environment variables will be used in
144future connections. It returns the previous setting for default options.
145
146get/set_deftty -- default debug tty [DV]
147----------------------------------------
148
149.. function:: get_deftty()
150
151    Get the default debug terminal
152
153    :returns: the current default debug terminal specification
154    :rtype: str or None
155    :raises TypeError: too many arguments
156
157This method returns the current default debug terminal specification, or
158``None`` if the environment variables should be used. Environment variables
159won't be looked up. Note that this is ignored in newer PostgreSQL versions.
160
161.. function:: set_deftty(terminal)
162
163    Set the default debug terminal
164
165    :param terminal: the new default debug terminal
166    :type terminal: str or None
167    :returns: the previous default debug terminal specification
168    :rtype: str or None
169    :raises TypeError: bad argument type, or too many arguments
170
171This methods sets the default debug terminal value for new connections.
172If ``None`` is supplied as parameter, environment variables will be used
173in future connections. It returns the previous setting for default terminal.
174Note that this is ignored in newer PostgreSQL versions.
175
176get/set_defbase -- default database name [DV]
177---------------------------------------------
178
179.. function:: get_defbase()
180
181    Get the default database name
182
183    :returns: the current default database name specification
184    :rtype: str or None
185    :raises TypeError: too many arguments
186
187This method returns the current default database name specification, or
188``None`` if the environment variables should be used. Environment variables
189won't be looked up.
190
191.. function:: set_defbase(base)
192
193    Set the default database name
194
195    :param base: the new default base name
196    :type base: str or None
197    :returns: the previous default database name specification
198    :rtype: str or None
199    :raises TypeError: bad argument type, or too many arguments
200
201This method sets the default database name value for new connections. If
202``None`` is supplied as parameter, environment variables will be used in
203future connections. It returns the previous setting for default host.
204
205get/set_defuser -- default database user [DV]
206---------------------------------------------
207
208.. function:: get_defuser()
209
210    Get the default database user
211
212    :returns: the current default database user specification
213    :rtype: str or None
214    :raises TypeError: too many arguments
215
216This method returns the current default database user specification, or
217``None`` if the environment variables should be used. Environment variables
218won't be looked up.
219
220.. function:: set_defuser(user)
221
222    Set the default database user
223
224    :param user: the new default database user
225    :type base: str or None
226    :returns: the previous default database user specification
227    :rtype: str or None
228    :raises TypeError: bad argument type, or too many arguments
229
230This method sets the default database user name for new connections. If
231``None`` is supplied as parameter, environment variables will be used in
232future connections. It returns the previous setting for default host.
233
234get/set_defpasswd -- default database password [DV]
235---------------------------------------------------
236
237.. function:: get_defpasswd()
238
239    Get the default database password
240
241    :returns: the current default database password specification
242    :rtype: str or None
243    :raises TypeError: too many arguments
244
245This method returns the current default database password specification, or
246``None`` if the environment variables should be used. Environment variables
247won't be looked up.
248
249.. function:: set_defpasswd(passwd)
250
251    Set the default database password
252
253    :param passwd: the new default database password
254    :type base: str or None
255    :returns: the previous default database password specification
256    :rtype: str or None
257    :raises TypeError: bad argument type, or too many arguments
258
259This method sets the default database password for new connections. If
260``None`` is supplied as parameter, environment variables will be used in
261future connections. It returns the previous setting for default host.
262
263escape_string -- escape a string for use within SQL
264---------------------------------------------------
265
266.. function:: escape_string(string)
267
268    Escape a string for use within SQL
269
270    :param str string: the string that is to be escaped
271    :returns: the escaped string
272    :rtype: str
273    :raises TypeError: bad argument type, or too many arguments
274
275This function escapes a string for use within an SQL command.
276This is useful when inserting data values as literal constants
277in SQL commands. Certain characters (such as quotes and backslashes)
278must be escaped to prevent them from being interpreted specially
279by the SQL parser. :func:`escape_string` performs this operation.
280Note that there is also a :class:`pgobject` method with the same name
281which takes connection properties into account.
282
283.. note::
284
285   It is especially important to do proper escaping when
286   handling strings that were received from an untrustworthy source.
287   Otherwise there is a security risk: you are vulnerable to "SQL injection"
288   attacks wherein unwanted SQL commands are fed to your database.
289
290Example::
291
292    name = raw_input("Name? ")
293    phone = con.query("select phone from employees where name='%s'"
294        % escape_string(name)).getresult()
295
296escape_bytea -- escape binary data for use within SQL
297-----------------------------------------------------
298
299.. function:: escape_bytea(datastring)
300
301    escape binary data for use within SQL as type ``bytea``
302
303    :param str datastring: string containing the binary data that is to be escaped
304    :returns: the escaped string
305    :rtype: str
306    :raises TypeError: bad argument type, or too many arguments
307
308Escapes binary data for use within an SQL command with the type ``bytea``.
309As with :func:`escape_string`, this is only used when inserting data directly
310into an SQL command string.
311Note that there is also a :class:`pgobject` method with the same name
312which takes connection properties into account.
313
314Example::
315
316    picture = open('garfield.gif', 'rb').read()
317    con.query("update pictures set img='%s' where name='Garfield'"
318        % escape_bytea(picture))
319
320unescape_bytea -- unescape data that has been retrieved as text
321---------------------------------------------------------------
322
323.. function:: unescape_bytea(string)
324
325    Unescape ``bytea`` data that has been retrieved as text
326
327    :param str datastring: the ``bytea`` data string that has been retrieved as text
328    :returns: byte string containing the binary data
329    :rtype: str
330    :raises TypeError: bad argument type, or too many arguments
331
332Converts an escaped string representation of binary data into binary
333data -- the reverse of :func:`escape_bytea`. This is needed when retrieving
334``bytea`` data with one of the :meth:`pgqueryobject.getresult`,
335:meth:`pgqueryobject.dictresult` or :meth:`pgqueryobject.namedresult` methods.
336
337Example::
338
339    picture = unescape_bytea(con.query(
340          "select img from pictures where name='Garfield'").getresult[0][0])
341    open('garfield.gif', 'wb').write(picture)
342
343get/set_decimal -- decimal type to be used for numeric values
344-------------------------------------------------------------
345
346.. function:: get_decimal()
347
348    Get the decimal type to be used for numeric values
349
350    :returns: the Python class used for PostgreSQL numeric values
351    :rtype: class
352
353This function returns the Python class that is used by PyGreSQL to hold
354PostgreSQL numeric values. The default class is :class:`decimal.Decimal`
355if available, otherwise the :class:`float` type is used.
356
357.. function:: set_decimal(cls)
358
359    Set a decimal type to be used for numeric values
360
361    :param class cls: the Python class to be used for PostgreSQL numeric values
362
363This function can be used to specify the Python class that shall
364be used by PyGreSQL to hold PostgreSQL numeric values.
365The default class is :class:`decimal.Decimal` if available,
366otherwise the :class:`float` type is used.
367
368get/set_decimal_point -- decimal mark used for monetary values
369--------------------------------------------------------------
370
371.. function:: get_decimal_point()
372
373    Get the decimal mark used for monetary values
374
375    :returns: string with one character representing the decimal mark
376    :rtype: str
377
378This function returns the decimal mark used by PyGreSQL to interpret
379PostgreSQL monetary values when converting them to decimal numbers.
380The default setting is ``'.'`` as a decimal point. This setting is not
381adapted automatically to the locale used by PostGreSQL, but you can
382use ``set_decimal()`` to set a different decimal mark manually. A return
383value of ``None`` means monetary values are not interpreted as decimal
384numbers, but returned as strings including the formatting and currency.
385
386.. versionadded:: 4.1.1
387
388.. function:: set_decimal_point(string)
389
390    Specify which decimal mark is used for interpreting monetary values
391
392    :param str string: string with one character representing the decimal mark
393
394This function can be used to specify the decimal mark used by PyGreSQL
395to interpret PostgreSQL monetary values. The default value is '.' as
396a decimal point. This value is not adapted automatically to the locale
397used by PostGreSQL, so if you are dealing with a database set to a
398locale that uses a ``','`` instead of ``'.'`` as the decimal point,
399then you need to call ``set_decimal(',')`` to have PyGreSQL interpret
400monetary values correctly. If you don't want money values to be converted
401to decimal numbers, then you can call ``set_decimal(None)``, which will
402cause PyGreSQL to return monetary values as strings including their
403formatting and currency.
404
405.. versionadded:: 4.1.1
406
407get/set_bool -- whether boolean values are returned as bool objects
408-------------------------------------------------------------------
409
410.. function:: get_bool()
411
412    Check whether boolean values are returned as bool objects
413
414    :returns: whether or not bool objects will be returned
415    :rtype: bool
416
417This function checks whether PyGreSQL returns PostgreSQL boolean
418values converted to Python bool objects, or as ``'f'`` and ``'t'``
419strings which are the values used internally by PostgreSQL. By default,
420conversion to bool objects is not activated, but you can enable
421this with the ``set_bool()`` method.
422
423.. versionadded:: 4.2
424
425.. function:: set_bool(on)
426
427    Set whether boolean values are returned as bool objects
428
429    :param on: whether or not bool objects shall be returned
430
431This function can be used to specify whether PyGreSQL shall return
432PostgreSQL boolean values converted to Python bool objects, or as
433``'f'`` and ``'t'`` strings which are the values used internally by PostgreSQL.
434By default, conversion to bool objects is not activated, but you can
435enable this by calling ``set_bool(True)``.
436
437.. versionadded:: 4.2
438
439get/set_namedresult -- conversion to named tuples
440-------------------------------------------------
441
442.. function:: get_namedresult()
443
444    Get the function that converts to named tuples
445
446This function returns the function used by PyGreSQL to construct the
447result of the :meth:`pgqueryobject.namedresult` method.
448
449.. function:: set_namedresult(func)
450
451    Set a function that will convert to named tuples
452
453    :param func: the function to be used to convert results to named tuples
454
455You can use this if you want to create different kinds of named tuples
456returned by the :meth:`pgqueryobject.namedresult` method.
457
458
459Module constants
460----------------
461Some constants are defined in the module dictionary.
462They are intended to be used as parameters for methods calls.
463You should refer to the libpq description in the PostgreSQL user manual
464for more information about them. These constants are:
465
466.. data:: version, __version__
467
468    constants that give the current version
469
470.. data:: INV_READ, INV_WRITE
471
472    large objects access modes,
473    used by :meth:`pgobject.locreate` and :meth:`pglarge.open`
474
475.. data:: SEEK_SET, SEEK_CUR, SEEK_END:
476
477    positional flags, used by :meth:`pglarge.seek`
Note: See TracBrowser for help on using the repository browser.