source: trunk/docs/contents/pg/db_wrapper.rst @ 801

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

Add documentation and tests for two older methods

transaction() was there since 3.6 and parameter() since 4.0,
but they have never been documented or tested

File size: 32.2 KB
Line 
1The DB wrapper class
2====================
3
4.. py:currentmodule:: pg
5
6.. class:: DB
7
8The :class:`Connection` methods are wrapped in the class :class:`DB`
9which also adds convenient higher level methods for working with the
10database.  It also serves as a context manager for the connection.
11The preferred way to use this module is as follows::
12
13    import pg
14
15    with pg.DB(...) as db:  # for parameters, see below
16        for r in db.query(  # just for example
17                "SELECT foo, bar FROM foo_bar_table WHERE foo !~ bar"
18                ).dictresult():
19            print('%(foo)s %(bar)s' % r)
20
21This class can be subclassed as in this example::
22
23    import pg
24
25    class DB_ride(pg.DB):
26        """Ride database wrapper
27
28        This class encapsulates the database functions and the specific
29        methods for the ride database."""
30
31    def __init__(self):
32        """Open a database connection to the rides database"""
33        pg.DB.__init__(self, dbname='ride')
34        self.query("SET DATESTYLE TO 'ISO'")
35
36    [Add or override methods here]
37
38The following describes the methods and variables of this class.
39
40Initialization
41--------------
42The :class:`DB` class is initialized with the same arguments as the
43:func:`connect` function described above. It also initializes a few
44internal variables. The statement ``db = DB()`` will open the local
45database with the name of the user just like ``connect()`` does.
46
47You can also initialize the DB class with an existing :mod:`pg` or :mod:`pgdb`
48connection. Pass this connection as a single unnamed parameter, or as a
49single parameter named ``db``. This allows you to use all of the methods
50of the DB class with a DB-API 2 compliant connection. Note that the
51:meth:`Connection.close` and :meth:`Connection.reopen` methods are inoperative
52in this case.
53
54pkey -- return the primary key of a table
55-----------------------------------------
56
57.. method:: DB.pkey(table)
58
59    Return the primary key of a table
60
61    :param str table: name of table
62    :returns: Name of the field which is the primary key of the table
63    :rtype: str
64    :raises KeyError: the table does not have a primary key
65
66This method returns the primary key of a table.  Single primary keys are
67returned as strings unless you set the composite flag.  Composite primary
68keys are always represented as tuples.  Note that this raises a KeyError
69if the table does not have a primary key.
70
71get_databases -- get list of databases in the system
72----------------------------------------------------
73
74.. method:: DB.get_databases()
75
76    Get the list of databases in the system
77
78    :returns: all databases in the system
79    :rtype: list
80
81Although you can do this with a simple select, it is added here for
82convenience.
83
84get_relations -- get list of relations in connected database
85------------------------------------------------------------
86
87.. method:: DB.get_relations(kinds)
88
89    Get the list of relations in connected database
90
91    :param str kinds: a string or sequence of type letters
92    :returns: all relations of the given kinds in the database
93    :rtype: list
94
95The type letters are ``r`` = ordinary table, ``i`` = index, ``S`` = sequence,
96``v`` = view, ``c`` = composite type, ``s`` = special, ``t`` = TOAST table.
97If `kinds` is None or an empty string, all relations are returned (this is
98also the default). Although you can do this with a simple select, it is
99added here for convenience.
100
101get_tables -- get list of tables in connected database
102------------------------------------------------------
103
104.. method:: DB.get_tables()
105
106    Get the list of tables in connected database
107
108    :returns: all tables in connected database
109    :rtype: list
110
111This is a shortcut for ``get_relations('r')`` that has been added for
112convenience.
113
114get_attnames -- get the attribute names of a table
115--------------------------------------------------
116
117.. method:: DB.get_attnames(table)
118
119    Get the attribute names of a table
120
121    :param str table: name of table
122    :returns: an ordered dictionary mapping attribute names to type names
123
124Given the name of a table, digs out the set of attribute names.
125
126Returns a read-only dictionary of attribute names (the names are the keys,
127the values are the names of the attributes' types) with the column names
128in the proper order if you iterate over it.
129
130By default, only a limited number of simple types will be returned.
131You can get the regular types after enabling this by calling the
132:meth:`DB.use_regtypes` method.
133
134has_table_privilege -- check table privilege
135--------------------------------------------
136
137.. method:: DB.has_table_privilege(table, privilege)
138
139    Check whether current user has specified table privilege
140
141    :param str table: the name of the table
142    :param str privilege: privilege to be checked -- default is 'select'
143    :returns: whether current user has specified table privilege
144    :rtype: bool
145
146Returns True if the current user has the specified privilege for the table.
147
148.. versionadded:: 4.0
149
150get/set_parameter -- get or set  run-time parameters
151----------------------------------------------------
152
153.. method:: DB.get_parameter(parameter)
154
155    Get the value of run-time parameters
156
157    :param parameter: the run-time parameter(s) to get
158    :type param: str, tuple, list or dict
159    :returns: the current value(s) of the run-time parameter(s)
160    :rtype: str, list or dict
161    :raises TypeError: Invalid parameter type(s)
162    :raises pg.ProgrammingError: Invalid parameter name(s)
163
164If the parameter is a string, the return value will also be a string
165that is the current setting of the run-time parameter with that name.
166
167You can get several parameters at once by passing a list, set or dict.
168When passing a list of parameter names, the return value will be a
169corresponding list of parameter settings.  When passing a set of
170parameter names, a new dict will be returned, mapping these parameter
171names to their settings.  Finally, if you pass a dict as parameter,
172its values will be set to the current parameter settings corresponding
173to its keys.
174
175By passing the special name ``'all'`` as the parameter, you can get a dict
176of all existing configuration parameters.
177
178Note that you can request most of the important parameters also using
179:meth:`Connection.parameter()` which does not involve a database query
180like it is the case for :meth:`DB.get_parameter` and :meth:`DB.set_parameter`.
181
182.. versionadded:: 4.2
183
184.. method:: DB.set_parameter(parameter, [value], [local])
185
186    Set the value of run-time parameters
187
188    :param parameter: the run-time parameter(s) to set
189    :type param: string, tuple, list or dict
190    :param value: the value to set
191    :type param: str or None
192    :raises TypeError: Invalid parameter type(s)
193    :raises ValueError: Invalid value argument(s)
194    :raises pg.ProgrammingError: Invalid parameter name(s) or values
195
196If the parameter and the value are strings, the run-time parameter
197will be set to that value.  If no value or *None* is passed as a value,
198then the run-time parameter will be restored to its default value.
199
200You can set several parameters at once by passing a list of parameter
201names, together with a single value that all parameters should be
202set to or with a corresponding list of values.  You can also pass
203the parameters as a set if you only provide a single value.
204Finally, you can pass a dict with parameter names as keys.  In this
205case, you should not pass a value, since the values for the parameters
206will be taken from the dict.
207
208By passing the special name ``'all'`` as the parameter, you can reset
209all existing settable run-time parameters to their default values.
210
211If you set *local* to `True`, then the command takes effect for only the
212current transaction.  After :meth:`DB.commit` or :meth:`DB.rollback`,
213the session-level setting takes effect again.  Setting *local* to `True`
214will appear to have no effect if it is executed outside a transaction,
215since the transaction will end immediately.
216
217.. versionadded:: 4.2
218
219begin/commit/rollback/savepoint/release -- transaction handling
220---------------------------------------------------------------
221
222.. method:: DB.begin([mode])
223
224    Begin a transaction
225
226    :param str mode: an optional transaction mode such as 'READ ONLY'
227
228    This initiates a transaction block, that is, all following queries
229    will be executed in a single transaction until :meth:`DB.commit`
230    or :meth:`DB.rollback` is called.
231
232.. versionadded:: 4.1
233
234.. method:: DB.start()
235
236    This is the same as the :meth:`DB.begin` method.
237
238.. method:: DB.commit()
239
240    Commit a transaction
241
242    This commits the current transaction. All changes made by the
243    transaction become visible to others and are guaranteed to be
244    durable if a crash occurs.
245
246.. method:: DB.end()
247
248    This is the same as the :meth:`DB.commit` method.
249
250.. versionadded:: 4.1
251
252.. method:: DB.rollback([name])
253
254    Roll back a transaction
255
256    :param str name: optionally, roll back to the specified savepoint
257
258    This rolls back the current transaction and causes all the updates
259    made by the transaction to be discarded.
260
261.. method:: DB.abort()
262
263    This is the same as the :meth:`DB.rollback` method.
264
265.. versionadded:: 4.2
266
267.. method:: DB.savepoint(name)
268
269    Define a new savepoint
270
271    :param str name: the name to give to the new savepoint
272
273    This establishes a new savepoint within the current transaction.
274
275.. versionadded:: 4.1
276
277.. method:: DB.release(name)
278
279    Destroy a savepoint
280
281    :param str name: the name of the savepoint to destroy
282
283    This destroys a savepoint previously defined in the current transaction.
284
285.. versionadded:: 4.1
286
287get -- get a row from a database table or view
288----------------------------------------------
289
290.. method:: DB.get(table, row, [keyname])
291
292    Get a row from a database table or view
293
294    :param str table: name of table or view
295    :param row: either a dictionary or the value to be looked up
296    :param str keyname: name of field to use as key (optional)
297    :returns: A dictionary - the keys are the attribute names,
298      the values are the row values.
299    :raises pg.ProgrammingError: table has no primary key or missing privilege
300    :raises KeyError: missing key value for the row
301
302This method is the basic mechanism to get a single row.  It assumes
303that the *keyname* specifies a unique row.  It must be the name of a
304single column or a tuple of column names.  If *keyname* is not specified,
305then the primary key for the table is used.
306
307If *row* is a dictionary, then the value for the key is taken from it.
308Otherwise, the row must be a single value or a tuple of values
309corresponding to the passed *keyname* or primary key.  The fetched row
310from the table will be returned as a new dictionary or used to replace
311the existing values when row was passed as aa dictionary.
312
313The OID is also put into the dictionary if the table has one, but
314in order to allow the caller to work with multiple tables, it is
315munged as ``oid(table)`` using the actual name of the table.
316
317Note that since PyGreSQL 5.0 this will return the value of an array
318type column as a Python list.
319
320insert -- insert a row into a database table
321--------------------------------------------
322
323.. method:: DB.insert(table, [row], [col=val, ...])
324
325    Insert a row into a database table
326
327    :param str table: name of table
328    :param dict row: optional dictionary of values
329    :param col: optional keyword arguments for updating the dictionary
330    :returns: the inserted values in the database
331    :rtype: dict
332    :raises pg.ProgrammingError: missing privilege or conflict
333
334This method inserts a row into a table.  If the optional dictionary is
335not supplied then the required values must be included as keyword/value
336pairs.  If a dictionary is supplied then any keywords provided will be
337added to or replace the entry in the dictionary.
338
339The dictionary is then reloaded with the values actually inserted in order
340to pick up values modified by rules, triggers, etc.
341
342Note that since PyGreSQL 5.0 it is possible to insert a value for an
343array type column by passing it as Python list.
344
345update -- update a row in a database table
346------------------------------------------
347
348.. method:: DB.update(table, [row], [col=val, ...])
349
350    Update a row in a database table
351
352    :param str table: name of table
353    :param dict row: optional dictionary of values
354    :param col: optional keyword arguments for updating the dictionary
355    :returns: the new row in the database
356    :rtype: dict
357    :raises pg.ProgrammingError: table has no primary key or missing privilege
358    :raises KeyError: missing key value for the row
359
360Similar to insert but updates an existing row.  The update is based on
361the primary key of the table or the OID value as munged by :meth:`DB.get`
362or passed as keyword.
363
364The dictionary is then modified to reflect any changes caused by the
365update due to triggers, rules, default values, etc.
366
367Like insert, the dictionary is optional and updates will be performed
368on the fields in the keywords.  There must be an OID or primary key
369either in the dictionary where the OID must be munged, or in the keywords
370where it can be simply the string ``'oid'``.
371
372upsert -- insert a row with conflict resolution
373-----------------------------------------------
374
375.. method:: DB.upsert(table, [row], [col=val, ...])
376
377    Insert a row into a database table with conflict resolution
378
379    :param str table: name of table
380    :param dict row: optional dictionary of values
381    :param col: optional keyword arguments for specifying the update
382    :returns: the new row in the database
383    :rtype: dict
384    :raises pg.ProgrammingError: table has no primary key or missing privilege
385
386This method inserts a row into a table, but instead of raising a
387ProgrammingError exception in case a row with the same primary key already
388exists, an update will be executed instead.  This will be performed as a
389single atomic operation on the database, so race conditions can be avoided.
390
391Like the insert method, the first parameter is the name of the table and the
392second parameter can be used to pass the values to be inserted as a dictionary.
393
394Unlike the insert und update statement, keyword parameters are not used to
395modify the dictionary, but to specify which columns shall be updated in case
396of a conflict, and in which way:
397
398A value of `False` or `None` means the column shall not be updated,
399a value of `True` means the column shall be updated with the value that
400has been proposed for insertion, i.e. has been passed as value in the
401dictionary.  Columns that are not specified by keywords but appear as keys
402in the dictionary are also updated like in the case keywords had been passed
403with the value `True`.
404
405So if in the case of a conflict you want to update every column that has been
406passed in the dictionary `d` , you would call ``upsert(table, d)``.  If you
407don't want to do anything in case of a conflict, i.e. leave the existing row
408as it is, call ``upsert(table, d, **dict.fromkeys(d))``.
409
410If you need more fine-grained control of what gets updated, you can also pass
411strings in the keyword parameters.  These strings will be used as SQL
412expressions for the update columns.  In these expressions you can refer
413to the value that already exists in the table by writing the table prefix
414``included.`` before the column name, and you can refer to the value that
415has been proposed for insertion by writing ``excluded.`` as table prefix.
416
417The dictionary is modified in any case to reflect the values in the database
418after the operation has completed.
419
420.. note::
421
422    The method uses the PostgreSQL "upsert" feature which is only available
423    since PostgreSQL 9.5. With older PostgreSQL versions, you will get a
424    ProgrammingError if you use this method.
425
426.. versionadded:: 5.0
427
428query -- execute a SQL command string
429-------------------------------------
430
431.. method:: DB.query(command, [arg1, [arg2, ...]])
432
433    Execute a SQL command string
434
435    :param str command: SQL command
436    :param arg*: optional positional arguments
437    :returns: result values
438    :rtype: :class:`Query`, None
439    :raises TypeError: bad argument type, or too many arguments
440    :raises TypeError: invalid connection
441    :raises ValueError: empty SQL query or lost connection
442    :raises pg.ProgrammingError: error in query
443    :raises pg.InternalError: error during query processing
444
445Similar to the :class:`Connection` function with the same name, except that
446positional arguments can be passed either as a single list or tuple, or as
447individual positional arguments.
448
449Example::
450
451    name = input("Name? ")
452    phone = input("Phone? ")
453    rows = db.query("update employees set phone=$2 where name=$1",
454        (name, phone)).getresult()[0][0]
455    # or
456    rows = db.query("update employees set phone=$2 where name=$1",
457         name, phone).getresult()[0][0]
458
459query_formatted -- execute a formatted SQL command string
460---------------------------------------------------------
461
462.. method:: DB.query_formatted(command, parameters, [types], [inline])
463
464    Execute a formatted SQL command string
465
466    :param str command: SQL command
467    :param parameters: the values of the parameters for the SQL command
468    :type parameters: tuple, list or dict
469    :param types: optionally, the types of the parameters
470    :type types: tuple, list or dict
471    :param bool inline: whether the parameters should be passed in the SQL
472    :rtype: :class:`Query`, None
473    :raises TypeError: bad argument type, or too many arguments
474    :raises TypeError: invalid connection
475    :raises ValueError: empty SQL query or lost connection
476    :raises pg.ProgrammingError: error in query
477    :raises pg.InternalError: error during query processing
478
479Similar to :meth:`DB.query`, but using Python format placeholders of the form
480``%s`` or ``%(names)s`` instead of PostgreSQL placeholders of the form ``$1``.
481The parameters must be passed as a tuple, list or dict.  You can also pass a
482corresponding tuple, list or dict of database types in order to format the
483parameters properly in case there is ambiguity.
484
485If you set *inline* to True, the parameters will be sent to the database
486embedded in the SQL command, otherwise they will be sent separately.
487
488Example::
489
490    name = input("Name? ")
491    phone = input("Phone? ")
492    rows = db.query_formatted(
493        "update employees set phone=%s where name=%s",
494        (phone, name)).getresult()[0][0]
495    # or
496    rows = db.query_formatted(
497        "update employees set phone=%(phone)s where name=%(name)s",
498        dict(name=name, phone=phone)).getresult()[0][0]
499
500clear -- clear row values in memory
501-----------------------------------
502
503.. method:: DB.clear(table, [row])
504
505    Clear row values in memory
506
507    :param str table: name of table
508    :param dict row: optional dictionary of values
509    :returns: an empty row
510    :rtype: dict
511
512This method clears all the attributes to values determined by the types.
513Numeric types are set to 0, Booleans are set to ``'f'``, and everything
514else is set to the empty string.  If the row argument is present, it is
515used as the row dictionary and any entries matching attribute names are
516cleared with everything else left unchanged.
517
518If the dictionary is not supplied a new one is created.
519
520delete -- delete a row from a database table
521--------------------------------------------
522
523.. method:: DB.delete(table, [row], [col=val, ...])
524
525    Delete a row from a database table
526
527    :param str table: name of table
528    :param dict d: optional dictionary of values
529    :param col: optional keyword arguments for updating the dictionary
530    :rtype: None
531    :raises pg.ProgrammingError: table has no primary key,
532        row is still referenced or missing privilege
533    :raises KeyError: missing key value for the row
534
535This method deletes the row from a table.  It deletes based on the
536primary key of the table or the OID value as munged by :meth:`DB.get`
537or passed as keyword.
538
539The return value is the number of deleted rows (i.e. 0 if the row did not
540exist and 1 if the row was deleted).
541
542Note that if the row cannot be deleted because e.g. it is still referenced
543by another table, this method will raise a ProgrammingError.
544
545truncate -- quickly empty database tables
546-----------------------------------------
547
548.. method:: DB.truncate(table, [restart], [cascade], [only])
549
550    Empty a table or set of tables
551
552    :param table: the name of the table(s)
553    :type table: str, list or set
554    :param bool restart: whether table sequences should be restarted
555    :param bool cascade: whether referenced tables should also be truncated
556    :param only: whether only parent tables should be truncated
557    :type only: bool or list
558
559This method quickly removes all rows from the given table or set
560of tables.  It has the same effect as an unqualified DELETE on each
561table, but since it does not actually scan the tables it is faster.
562Furthermore, it reclaims disk space immediately, rather than requiring
563a subsequent VACUUM operation. This is most useful on large tables.
564
565If *restart* is set to `True`, sequences owned by columns of the truncated
566table(s) are automatically restarted.  If *cascade* is set to `True`, it
567also truncates all tables that have foreign-key references to any of
568the named tables.  If the parameter *only* is not set to `True`, all the
569descendant tables (if any) will also be truncated. Optionally, a ``*``
570can be specified after the table name to explicitly indicate that
571descendant tables are included.  If the parameter *table* is a list,
572the parameter *only* can also be a list of corresponding boolean values.
573
574.. versionadded:: 4.2
575
576get_as_list/dict -- read a table as a list or dictionary
577--------------------------------------------------------
578
579.. method:: DB.get_as_list(table, [what], [where], [order], [limit], [offset], [scalar])
580
581    Get a table as a list
582
583    :param str table: the name of the table (the FROM clause)
584    :param what: column(s) to be returned (the SELECT clause)
585    :type what: str, list, tuple or None
586    :param where: conditions(s) to be fulfilled (the WHERE clause)
587    :type where: str, list, tuple or None
588    :param order: column(s) to sort by (the ORDER BY clause)
589    :type order: str, list, tuple, False or None
590    :param int limit: maximum number of rows returned (the LIMIT clause)
591    :param int offset: number of rows to be skipped (the OFFSET clause)
592    :param bool scalar: whether only the first column shall be returned
593    :returns: the content of the table as a list
594    :rtype: list
595    :raises TypeError: the table name has not been specified
596
597This gets a convenient representation of the table as a list of named tuples
598in Python.  You only need to pass the name of the table (or any other SQL
599expression returning rows).  Note that by default this will return the full
600content of the table which can be huge and overflow your memory.  However, you
601can control the amount of data returned using the other optional parameters.
602
603The parameter *what* can restrict the query to only return a subset of the
604table columns.  The parameter *where* can restrict the query to only return a
605subset of the table rows.  The specified SQL expressions all need to be
606fulfilled for a row to get into the result.  The parameter *order* specifies
607the ordering of the rows.  If no ordering is specified, the result will be
608ordered by the primary key(s) or all columns if no primary key exists.
609You can set *order* to *False* if you don't care about the ordering.
610The parameters *limit* and *offset* specify the maximum number of rows
611returned and a number of rows skipped over.
612
613If you set the *scalar* option to *True*, then instead of the named tuples
614you will get the first items of these tuples.  This is useful if the result
615has only one column anyway.
616
617.. method:: DB.get_as_dict(table, [keyname], [what], [where], [order], [limit], [offset], [scalar])
618
619    Get a table as a dictionary
620
621    :param str table: the name of the table (the FROM clause)
622    :param keyname: column(s) to be used as key(s) of the dictionary
623    :type keyname: str, list, tuple or None
624    :param what: column(s) to be returned (the SELECT clause)
625    :type what: str, list, tuple or None
626    :param where: conditions(s) to be fulfilled (the WHERE clause)
627    :type where: str, list, tuple or None
628    :param order: column(s) to sort by (the ORDER BY clause)
629    :type order: str, list, tuple, False or None
630    :param int limit: maximum number of rows returned (the LIMIT clause)
631    :param int offset: number of rows to be skipped (the OFFSET clause)
632    :param bool scalar: whether only the first column shall be returned
633    :returns: the content of the table as a list
634    :rtype: dict or OrderedDict
635    :raises TypeError: the table name has not been specified
636    :raises KeyError: keyname(s) are invalid or not part of the result
637    :raises pg.ProgrammingError: no keyname(s) and table has no primary key
638
639This method is similar to :meth:`DB.get_as_list`, but returns the table as
640a Python dict instead of a Python list, which can be even more convenient.
641The primary key column(s) of the table will be used as the keys of the
642dictionary, while the other column(s) will be the corresponding values.
643The keys will be named tuples if the table has a composite primary key.
644The rows will be also named tuples unless the *scalar* option has been set
645to *True*.  With the optional parameter *keyname* you can specify a different
646set of columns to be used as the keys of the dictionary.
647
648If the Python version supports it, the dictionary will be an *OrderedDict*
649using the order specified with the *order* parameter or the key column(s)
650if not specified.  You can set *order* to *False* if you don't care about the
651ordering.  In this case the returned dictionary will be an ordinary one.
652
653escape_literal/identifier/string/bytea -- escape for SQL
654--------------------------------------------------------
655
656The following methods escape text or binary strings so that they can be
657inserted directly into an SQL command.  Except for :meth:`DB.escape_byte`,
658you don't need to call these methods for the strings passed as parameters
659to :meth:`DB.query`.  You also don't need to call any of these methods
660when storing data using :meth:`DB.insert` and similar.
661
662.. method:: DB.escape_literal(string)
663
664    Escape a string for use within SQL as a literal constant
665
666    :param str string: the string that is to be escaped
667    :returns: the escaped string
668    :rtype: str
669
670This method escapes a string for use within an SQL command. This is useful
671when inserting data values as literal constants in SQL commands. Certain
672characters (such as quotes and backslashes) must be escaped to prevent them
673from being interpreted specially by the SQL parser.
674
675.. versionadded:: 4.1
676
677.. method:: DB.escape_identifier(string)
678
679    Escape a string for use within SQL as an identifier
680
681    :param str string: the string that is to be escaped
682    :returns: the escaped string
683    :rtype: str
684
685This method escapes a string for use as an SQL identifier, such as a table,
686column, or function name. This is useful when a user-supplied identifier
687might contain special characters that would otherwise not be interpreted
688as part of the identifier by the SQL parser, or when the identifier might
689contain upper case characters whose case should be preserved.
690
691.. versionadded:: 4.1
692
693.. method:: DB.escape_string(string)
694
695    Escape a string for use within SQL
696
697    :param str string: the string that is to be escaped
698    :returns: the escaped string
699    :rtype: str
700
701Similar to the module function :func:`pg.escape_string` with the same name,
702but the behavior of this method is adjusted depending on the connection
703properties (such as character encoding).
704
705.. method:: DB.escape_bytea(datastring)
706
707    Escape binary data for use within SQL as type ``bytea``
708
709    :param str datastring: string containing the binary data that is to be escaped
710    :returns: the escaped string
711    :rtype: str
712
713Similar to the module function :func:`pg.escape_bytea` with the same name,
714but the behavior of this method is adjusted depending on the connection
715properties (in particular, whether standard-conforming strings are enabled).
716
717unescape_bytea -- unescape data retrieved from the database
718-----------------------------------------------------------
719
720.. method:: DB.unescape_bytea(string)
721
722    Unescape ``bytea`` data that has been retrieved as text
723
724    :param datastring: the ``bytea`` data string that has been retrieved as text
725    :returns: byte string containing the binary data
726    :rtype: bytes
727
728Converts an escaped string representation of binary data stored as ``bytea``
729into the raw byte string representing the binary data  -- this is the reverse
730of :meth:`DB.escape_bytea`.  Since the :class:`Query` results will already
731return unescaped byte strings, you normally don't have to use this method.
732
733encode/decode_json -- encode and decode JSON data
734-------------------------------------------------
735
736The following methods can be used to encode end decode data in
737`JSON <http://www.json.org/>`_ format.
738
739.. method:: DB.encode_json(obj)
740
741    Encode a Python object for use within SQL as type ``json`` or ``jsonb``
742
743    :param obj: Python object that shall be encoded to JSON format
744    :type obj: dict, list or None
745    :returns: string representation of the Python object in JSON format
746    :rtype: str
747
748This method serializes a Python object into a JSON formatted string that can
749be used within SQL.  You don't need to use this method on the data stored
750with :meth:`DB.insert` and similar, only if you store the data directly as
751part of an SQL command or parameter with :meth:`DB.query`.  This is the same
752as the :func:`json.dumps` function from the standard library.
753
754.. versionadded:: 5.0
755
756.. method:: DB.decode_json(string)
757
758    Decode ``json`` or ``jsonb`` data that has been retrieved as text
759
760    :param string: JSON formatted string shall be decoded into a Python object
761    :type string: str
762    :returns: Python object representing the JSON formatted string
763    :rtype: dict, list or None
764
765This method deserializes a JSON formatted string retrieved as text from the
766database to a Python object.  You normally don't need to use this method as
767JSON data is automatically decoded by PyGreSQL.  If you don't want the data
768to be decoded, then you can cast ``json`` or ``jsonb`` columns to ``text``
769in PostgreSQL or you can set the decoding function to *None* or a different
770function using :func:`pg.set_jsondecode`.  By default this is the same as
771the :func:`json.dumps` function from the standard library.
772
773.. versionadded:: 5.0
774
775use_regtypes -- determine use of regular type names
776---------------------------------------------------
777
778.. method:: DB.use_regtypes([regtypes])
779
780    Determine whether regular type names shall be used
781
782    :param bool regtypes: if passed, set whether regular type names shall be used
783    :returns: whether regular type names are used
784
785The :meth:`DB.get_attnames` method can return either simplified "classic"
786type names (the default) or more specific "regular" type names. Which kind
787of type names is used can be changed by calling :meth:`DB.get_regtypes`.
788If you pass a boolean, it sets whether regular type names shall be used.
789The method can also be used to check through its return value whether
790currently regular type names are used.
791
792.. versionadded:: 4.1
793
794notification_handler -- create a notification handler
795-----------------------------------------------------
796
797.. class:: DB.notification_handler(event, callback, [arg_dict], [timeout], [stop_event])
798
799    Create a notification handler instance
800
801    :param str event: the name of an event to listen for
802    :param callback: a callback function
803    :param dict arg_dict: an optional dictionary for passing arguments
804    :param timeout: the time-out when waiting for notifications
805    :type timeout: int, float or None
806    :param str stop_event: an optional different name to be used as stop event
807
808This method creates a :class:`pg.NotificationHandler` object using the
809:class:`DB` connection as explained under :doc:`notification`.
810
811.. versionadded:: 4.1.1
812
813Attributes of the DB wrapper class
814----------------------------------
815
816.. attribute:: DB.db
817
818    The wrapped :class:`Connection` object
819
820You normally don't need this, since all of the members can be accessed
821from the :class:`DB` wrapper class as well.
822
823.. attribute:: DB.dbname
824
825    The name of the database that the connection is using
826
827.. attribute:: DB.dbtypes
828
829    A dictionary with the various type names for the PostgreSQL types
830
831This can be used for getting more information on the PostgreSQL database
832types or changing the typecast functions used for the connection.  See the
833description of the :class:`DbTypes` class for details.
834
835.. versionadded:: 5.0
836
837.. attribute:: DB.adapter
838
839    A class with some helper functions for adapting parameters
840
841This can be used for building queries with parameters.  You normally will
842not need this, as you can use the :class:`DB.query_formatted` method.
843
844.. versionadded:: 5.0
Note: See TracBrowser for help on using the repository browser.