source: branches/4.x/docs/contents/pg/module.rst @ 775

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

Backport some minor doc fixes to the 4.x branch

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