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

Last change on this file since 900 was 900, checked in by cito, 3 years ago

Allow query_formatted() to be used without parameters

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