source: trunk/docs/pg.txt @ 371

Last change on this file since 371 was 371, checked in by cito, 11 years ago

Updated docs. "insert/update ... returning" is already supported and only needed documentation.

File size: 36.4 KB
Line 
1================================
2PyGreSQL Programming Information
3================================
4
5------------------------------------------
6The classic PyGreSQL interface (pg module)
7------------------------------------------
8
9.. meta::
10   :description: The classic PyGreSQL interface (pg module)
11   :keywords: PyGreSQL, pg, PostGreSQL, Python
12
13.. sectnum::
14.. contents:: Contents
15
16
17Introduction
18============
19You may either choose to use the
20`"classic" PyGreSQL interface <pg.html>`_
21provided by the `pg` module or else the
22`DB-API 2.0 compliant interface <pgdb.html>`_
23provided by the `pgdb` module.
24
25The following documentation covers only the older `pg` API.
26
27The `pg` module handles three types of objects,
28
29- the `pgobject`, which handles the connection
30  and all the requests to the database,
31- the `pglarge` object, which handles
32  all the accesses to PostgreSQL large objects,
33- the `pgqueryobject` that handles query results
34
35and it provides a convenient wrapper class `DB` for the `pgobject`.
36
37If you want to see a simple example of the use of some of these functions,
38see http://ontario.bikerides.ca where you can find a link at the bottom to the
39actual Python code for the page.
40
41
42Module functions and constants
43==============================
44The `pg` module defines a few functions that allow to connect
45to a database and to define "default variables" that override
46the environment variables used by PostgreSQL.
47
48These "default variables" were designed to allow you to handle general
49connection parameters without heavy code in your programs. You can prompt the
50user for a value, put it in the default variable, and forget it, without
51having to modify your environment. The support for default variables can be
52disabled by setting the -DNO_DEF_VAR option in the Python setup file. Methods
53relative to this are specified by the tag [DV].
54
55All variables are set to `None` at module initialization, specifying that
56standard environment variables should be used.
57
58connect - opens a pg connection
59-------------------------------
60Syntax::
61
62  connect([dbname], [host], [port], [opt], [tty], [user], [passwd])
63
64Parameters:
65  :dbname: name of connected database (string/None)
66  :host:   name of the server host (string/None)
67  :port:   port used by the database server (integer/-1)
68  :opt:    connection options (string/None)
69  :tty:    debug terminal (string/None)
70  :user:   PostgreSQL user (string/None)
71  :passwd: password for user (string/None)
72
73Return type:
74  :pgobject: If successful, the `pgobject` handling the connection
75
76Exceptions raised:
77  :TypeError: bad argument type, or too many arguments
78  :SyntaxError: duplicate argument definition
79  :pg.InternalError: some error occurred during pg connection definition
80
81  (plus all exceptions relative to object allocation)
82
83Description:
84  This function opens a connection to a specified database on a given
85  PostgreSQL server. You can use keywords here, as described in the
86  Python tutorial. The names of the keywords are the name of the
87  parameters given in the syntax line. For a precise description
88  of the parameters, please refer to the PostgreSQL user manual.
89
90Examples::
91
92  import pg
93
94  con1 = pg.connect('testdb', 'myhost', 5432, None, None, 'bob', None)
95  con2 = pg.connect(dbname='testdb', host='localhost', user='bob')
96
97get_defhost, set_defhost - default server host [DV]
98---------------------------------------------------
99Syntax::
100
101  get_defhost()
102
103Parameters:
104  None
105
106Return type:
107  :string, None: default host specification
108
109Exceptions raised:
110  :TypeError: too many arguments
111
112Description:
113  This method returns the current default host specification,
114  or `None` if the environment variables should be used.
115  Environment variables won't be looked up.
116
117Syntax::
118
119  set_defhost(host)
120
121Parameters:
122  :host: new default host (string/None)
123
124Return type:
125  :string, None: previous default host specification
126
127Exceptions raised:
128  :TypeError: bad argument type, or too many arguments
129
130Description:
131  This methods sets the default host value for new connections.
132  If `None` is supplied as parameter, environment variables will
133  be used in future connections. It returns the previous setting
134  for default host.
135
136get_defport, set_defport - default server port [DV]
137---------------------------------------------------
138Syntax::
139
140  get_defport()
141
142Parameters:
143  None
144
145Return type:
146  :integer, None: default port specification
147
148Exceptions raised:
149  :TypeError: too many arguments
150
151Description:
152  This method returns the current default port specification,
153  or `None` if the environment variables should be used.
154  Environment variables won't be looked up.
155
156Syntax::
157
158  set_defport(port)
159
160Parameters:
161  :port: new default port (integer/-1)
162
163Return type:
164  :integer, None: previous default port specification
165
166Description:
167  This methods sets the default port value for new connections. If -1 is
168  supplied as parameter, environment variables will be used in future
169  connections. It returns the previous setting for default port.
170
171get_defopt, set_defopt - default connection options [DV]
172--------------------------------------------------------
173Syntax::
174
175  get_defopt()
176
177Parameters:
178  None
179
180Return type:
181  :string, None: default options specification
182
183Exceptions raised:
184  :TypeError: too many arguments
185
186Description:
187  This method returns the current default connection options  specification,
188  or `None` if the environment variables should be used. Environment variables
189  won't be looked up.
190
191Syntax::
192
193  set_defopt(options)
194
195Parameters:
196  :options: new default connection options (string/None)
197
198Return type:
199  :string, None: previous default options specification
200
201Exceptions raised:
202  :TypeError: bad argument type, or too many arguments
203
204Description:
205  This methods sets the default connection options value for new connections.
206  If `None` is supplied as parameter, environment variables will be used in
207  future connections. It returns the previous setting for default options.
208
209get_deftty, set_deftty - default debug tty [DV]
210-----------------------------------------------
211Syntax::
212
213  get_deftty()
214
215Parameters:
216  None
217
218Return type:
219  :string, None: default debug terminal specification
220
221Exceptions raised:
222  :TypeError: too many arguments
223
224Description:
225  This method returns the current default debug terminal specification, or
226  `None` if the environment variables should be used. Environment variables
227  won't be looked up.
228
229Syntax::
230
231  set_deftty(terminal)
232
233Parameters:
234  :terminal: new default debug terminal (string/None)
235
236Return type:
237  :string, None: previous default debug terminal specification
238
239Exceptions raised:
240  :TypeError: bad argument type, or too many arguments
241
242Description:
243  This methods sets the default debug terminal value for new connections. If
244  `None` is supplied as parameter, environment variables will be used in future
245  connections. It returns the previous setting for default terminal.
246
247get_defbase, set_defbase - default database name [DV]
248-----------------------------------------------------
249Syntax::
250
251  get_defbase()
252
253Parameters:
254  None
255
256Return type:
257  :string, None: default database name specification
258
259Exceptions raised:
260  :TypeError: too many arguments
261
262Description:
263  This method returns the current default database name specification, or
264  `None` if the environment variables should be used. Environment variables
265  won't be looked up.
266
267Syntax::
268
269  set_defbase(base)
270
271Parameters:
272  :base: new default base name (string/None)
273
274Return type:
275  :string, None: previous default database name specification
276
277Exceptions raised:
278  :TypeError: bad argument type, or too many arguments
279
280Description:
281  This method sets the default database name value for new connections. If
282  `None` is supplied as parameter, environment variables will be used in
283  future connections. It returns the previous setting for default host.
284
285escape_string - escape a string for use within SQL
286--------------------------------------------------
287Syntax::
288
289  escape_string(string)
290
291Parameters:
292  :string: the string that is to be escaped
293
294Return type:
295  :str: the escaped string
296
297Exceptions raised:
298  :TypeError: bad argument type, or too many arguments
299
300Description:
301  This function escapes a string for use within an SQL command.
302  This is useful when inserting data values as literal constants
303  in SQL commands. Certain characters (such as quotes and backslashes)
304  must be escaped to prevent them from being interpreted specially
305  by the SQL parser. `escape_string` performs this operation.
306  Note that there is also a `pgobject` method with the same name
307  which takes connection properties into account.
308
309.. caution:: It is especially important to do proper escaping when
310  handling strings that were received from an untrustworthy source.
311  Otherwise there is a security risk: you are vulnerable to "SQL injection"
312  attacks wherein unwanted SQL commands are fed to your database.
313
314Example::
315
316  name = raw_input("Name? ")
317  phone = con.query("select phone from employees"
318    " where name='%s'" % escape_string(name)).getresult()
319
320escape_bytea - escape binary data for use within SQL as type `bytea`
321--------------------------------------------------------------------
322Syntax::
323
324  escape_bytea(datastring)
325
326Parameters:
327  :datastring: string containing the binary data that is to be escaped
328
329Return type:
330  :str: the escaped string
331
332Exceptions raised:
333  :TypeError: bad argument type, or too many arguments
334
335Description:
336  Escapes binary data for use within an SQL command with the type `bytea`.
337  As with `escape_string`, this is only used when inserting data directly
338  into an SQL command string.
339  Note that there is also a `pgobject` method with the same name
340  which takes connection properties into account.
341
342Example::
343
344  picture = file('garfield.gif', 'rb').read()
345  con.query("update pictures set img='%s' where name='Garfield'"
346    % escape_bytea(picture))
347
348unescape_bytea -- unescape `bytea` data that has been retrieved as text
349-----------------------------------------------------------------------
350Syntax::
351
352  unescape_bytea(string)
353
354Parameters:
355  :datastring: the `bytea` data string that has been retrieved as text
356
357Return type:
358  :str: string containing the binary data
359
360Exceptions raised:
361  :TypeError: bad argument type, or too many arguments
362
363Description:
364  Converts an escaped string representation of binary data into binary
365  data - the reverse of `escape_bytea`. This is needed when retrieving
366  `bytea` data with the `getresult()` or `dictresult()` method.
367
368Example::
369
370  picture = unescape_bytea(con.query(
371    "select img from pictures where name='Garfield'").getresult[0][0])
372  file('garfield.gif', 'wb').write(picture)
373
374set_decimal -- set a decimal type to be used for numeric values
375---------------------------------------------------------------
376Syntax::
377
378  set_decimal(cls)
379
380Parameters:
381  :cls: the Python class to be used for PostgreSQL numeric values
382
383Description:
384  This function can be used to specify the Python class that shall be
385  used by PyGreSQL to hold PostgreSQL numeric values. The default class
386  is decimal.Decimal if available, otherwise the float type is used.
387
388Module constants
389----------------
390Some constants are defined in the module dictionary.
391They are intended to be used as parameters for methods calls.
392You should refer to the libpq description in the PostgreSQL user manual
393for more information about them. These constants are:
394
395:version, __version__: constants that give the current version.
396:INV_READ, INV_WRITE: large objects access modes,
397  used by `(pgobject.)locreate` and `(pglarge.)open`
398:SEEK_SET, SEEK_CUR, SEEK_END: positional flags,
399  used by `(pglarge.)seek`
400
401
402Connection objects: pgobject
403============================
404This object handles a connection to a PostgreSQL database. It embeds and
405hides all the parameters that define this connection, thus just leaving really
406significant parameters in function calls.
407
408.. caution:: Some methods give direct access to the connection socket.
409  *Do not use them unless you really know what you are doing.*
410  If you prefer disabling them,
411  set the -DNO_DIRECT option in the Python setup file.
412
413  **These methods are specified by the tag [DA].**
414
415.. note:: Some other methods give access to large objects
416  (refer to PostgreSQL user manual for more information about these).
417  If you want to forbid access to these from the module,
418  set the -DNO_LARGE option in the Python setup file.
419
420  **These methods are specified by the tag [LO].**
421
422query - executes a SQL command string
423-------------------------------------
424Syntax::
425
426  query(command)
427
428Parameters:
429  :command: SQL command (string)
430
431Return type:
432  :pgqueryobject, None: result values
433
434Exceptions raised:
435  :TypeError: bad argument type, or too many arguments
436  :ValueError: empty SQL query or lost connection
437  :pg.ProgrammingError: error in query
438  :pg.InternalError': error during query processing
439
440Description:
441  This method simply sends a SQL query to the database. If the query is an
442  insert statement that inserted exactly one row into a table that has OIDs, the
443  return value is the OID of the newly inserted row. If the query is an update
444  or delete statement, or an insert statement that did not insert exactly one
445  row in a table with OIDs, then the numer of rows affected is returned as a
446  string. If it is a statement that returns rows as a result (usually a select
447  statement, but maybe also an "insert/update ... returning" statement), this
448  method returns a `pgqueryobject` that can be accessed via the `getresult()`
449  or `dictresult()` method or simply printed. Otherwise, it returns `None`.
450
451
452reset - resets the connection
453-----------------------------
454Syntax::
455
456  reset()
457
458Parameters:
459  None
460
461Return type:
462  None
463
464Exceptions raised:
465  :TypeError: too many (any) arguments
466
467Description:
468  This method resets the current database connection.
469
470cancel - abandon processing of current SQL command
471--------------------------------------------------
472Syntax::
473
474  cancel()
475
476Parameters:
477  None
478
479Return type:
480  None
481
482Exceptions raised:
483  :TypeError: too many (any) arguments
484
485Description:
486  This method requests that the server abandon processing
487  of the current SQL command.
488
489close - close the database connection
490-------------------------------------
491Syntax::
492
493  close()
494
495Parameters:
496  None
497
498Return type:
499  None
500
501Exceptions raised:
502  :TypeError: too many (any) arguments
503
504Description:
505  This method closes the database connection. The connection will
506  be closed in any case when the connection is deleted but this
507  allows you to explicitly close it. It is mainly here to allow
508  the DB-SIG API wrapper to implement a close function.
509
510fileno - returns the socket used to connect to the database
511-----------------------------------------------------------
512Syntax::
513
514  fileno()
515
516Parameters:
517  None
518
519Exceptions raised:
520  :TypeError: too many (any) arguments
521
522Description:
523  This method returns the underlying socket id used to connect
524  to the database. This is useful for use in select calls, etc.
525
526getnotify - gets the last notify from the server
527------------------------------------------------
528Syntax::
529
530  getnotify()
531
532Parameters:
533  None
534
535Return type:
536  :tuple, None: last notify from server
537
538Exceptions raised:
539  :TypeError: too many parameters
540  :TypeError: invalid connection
541
542Description:
543  This methods try to get a notify from the server (from the SQL statement
544  NOTIFY). If the server returns no notify, the methods returns None.
545  Otherwise, it returns a tuple (couple) `(relname, pid)`, where `relname`
546  is the name of the notify and `pid` the process id of the connection that
547  triggered the notify. Remember to do a listen query first otherwise
548  getnotify() will always return `None`.
549
550inserttable - insert a list into a table
551----------------------------------------
552Syntax::
553
554  inserttable(table, values)
555
556Parameters:
557  :table: the table name (string)
558  :values: list of rows values (list)
559
560Return type:
561  None
562
563Exceptions raised:
564  :TypeError: invalid connection, bad argument type, or too many arguments
565  :MemoryError: insert buffer could not be allocated
566  :ValueError: unsupported values
567
568Description:
569  This method allow to *quickly* insert large blocks of data in a table:
570  It inserts the whole values list into the given table. Internally, it
571  uses the COPY command of the PostgreSQL database. The list is a list
572  of tuples/lists that define the values for each inserted row. The rows
573  values may contain string, integer, long or double (real) values.
574
575.. caution:: *Be very careful*:
576  This method doesn't typecheck the fields according to the table definition;
577  it just look whether or not it knows how to handle such types.
578
579putline - writes a line to the server socket [DA]
580-------------------------------------------------
581Syntax::
582
583  putline(line)
584
585Parameters:
586  :line: line to be written (string)
587
588Return type:
589  None
590
591Exceptions raised:
592  :TypeError: invalid connection, bad parameter type, or too many parameters
593
594Description:
595  This method allows to directly write a string to the server socket.
596
597getline - gets a line from server socket [DA]
598---------------------------------------------
599Syntax::
600
601  getline()
602
603Parameters:
604  None
605
606Return type:
607  :string: the line read
608
609Exceptions raised:
610  :TypeError: invalid connection
611  :TypeError: too many parameters
612  :MemoryError: buffer overflow
613
614Description:
615  This method allows to directly read a string from the server socket.
616
617endcopy - synchronizes client and server [DA]
618---------------------------------------------
619Syntax::
620
621  endcopy()
622
623Parameters:
624  None
625
626Return type:
627  None
628
629Exceptions raised:
630  :TypeError: invalid connection
631  :TypeError: too many parameters
632
633Description:
634  The use of direct access methods may desynchonize client and server.
635  This method ensure that client and server will be synchronized.
636
637locreate - create a large object in the database [LO]
638-----------------------------------------------------
639Syntax::
640
641  locreate(mode)
642
643Parameters:
644  :mode: large object create mode
645
646Return type:
647  :pglarge: object handling the PostGreSQL large object
648
649Exceptions raised:
650
651  :TypeError: invalid connection, bad parameter type, or too many parameters
652  :pg.OperationalError: creation error
653
654Description:
655  This method creates a large object in the database. The mode can be defined
656  by OR-ing the constants defined in the pg module (INV_READ, INV_WRITE and
657  INV_ARCHIVE). Please refer to PostgreSQL user manual for a description of
658  the mode values.
659
660getlo - build a large object from given oid [LO]
661------------------------------------------------
662Syntax::
663
664  getlo(oid)
665
666Parameters:
667  :oid: OID of the existing large object (integer)
668
669Return type:
670  :pglarge: object handling the PostGreSQL large object
671
672Exceptions raised:
673  :TypeError:  invalid connection, bad parameter type, or too many parameters
674  :ValueError: bad OID value (0 is invalid_oid)
675
676Description:
677  This method allows to reuse a formerly created large object through the
678  `pglarge` interface, providing the user have its OID.
679
680loimport - import a file to a large object [LO]
681-----------------------------------------------
682Syntax::
683
684  loimport(name)
685
686Parameters:
687  :name: the name of the file to be imported (string)
688
689Return type:
690  :pglarge: object handling the PostGreSQL large object
691
692Exceptions raised:
693  :TypeError: invalid connection, bad argument type, or too many arguments
694  :pg.OperationalError: error during file import
695
696Description:
697  This methods allows to create large objects in a very simple way. You just
698  give the name of a file containing the data to be use.
699
700Object attributes
701-----------------
702Every `pgobject` defines a set of read-only attributes that describe the
703connection and its status. These attributes are:
704
705  :host:    the host name of the server (string)
706  :port:    the port of the server (integer)
707  :db:      the selected database (string)
708  :options: the connection options (string)
709  :tty:     the connection debug terminal (string)
710  :user:    user name on the database system (string)
711  :status:  the status of the connection (integer: 1 - OK, 0 - bad)
712  :error:   the last warning/error message from the server (string)
713
714
715The DB wrapper class
716====================
717The `pgobject` methods are wrapped in the class `DB`.
718The preferred way to use this module is as follows::
719
720  import pg
721
722  db = pg.DB(...) # see below
723
724  for r in db.query( # just for example
725      """SELECT foo,bar
726         FROM foo_bar_table
727         WHERE foo !~ bar"""
728      ).dictresult():
729
730      print '%(foo)s %(bar)s' % r
731
732This class can be subclassed as in this example::
733
734  import pg
735
736  class DB_ride(pg.DB):
737    """This class encapsulates the database functions and the specific
738       methods for the ride database."""
739
740    def __init__(self):
741        """Opens a database connection to the rides database"""
742
743        pg.DB.__init__(self, dbname = 'ride')
744        self.query("""SET DATESTYLE TO 'ISO'""")
745
746    [Add or override methods here]
747
748The following describes the methods and variables of this class.
749
750Initialization
751--------------
752The DB class is initialized with the same arguments as the connect
753function described in section 2. It also initializes a few
754internal variables. The statement `db = DB()` will open the
755local database with the name of the user just like connect() does.
756
757You can also initialize the DB class with an existing `_pg` or `pgdb`
758connection. Pass this connection as a single unnamed parameter, or as a
759single parameter named `db`. This allows you to use all of the methods
760of the DB class with a DB-API 2 compliant connection. Note that the
761`close()` and `reopen()` methods are inoperative in this case.
762
763
764
765pkey - return the primary key of a table
766----------------------------------------
767Syntax::
768
769  pkey(table)
770
771Parameters:
772  :table: name of table
773
774Return type:
775  :string: Name of the field which is the primary key of the table
776
777Description:
778  This method returns the primary key of a table. Note that this raises
779  an exception if the table does not have a primary key.
780
781get_databases - get list of databases in the system
782---------------------------------------------------
783Syntax::
784
785  get_databases()
786
787Parameters:
788  None
789
790Return type:
791  :list: all databases in the system
792
793Description:
794  Although you can do this with a simple select, it is added here for
795  convenience.
796
797get_relations - get list of relations in connected database
798-----------------------------------------------------------
799Syntax::
800
801  get_relations(kinds)
802
803Parameters:
804  :kinds: a string or sequence of type letters
805
806Description:
807  The type letters are `r` = ordinary table, `i` = index, `S` = sequence,
808  `v` = view, `c` = composite type, `s` = special, `t` = TOAST table.
809  If `kinds` is None or an empty string, all relations are returned (this is
810  also the default). Although you can do this with a simple select, it is
811  added here for convenience.
812
813get_tables - get list of tables in connected database
814-----------------------------------------------------
815Syntax::
816
817  get_tables()
818
819Parameters:
820  None
821
822Returns:
823  :list: all tables in connected database
824
825Description:
826  Although you can do this with a simple select, it is added here for
827  convenience.
828
829get_attnames - get the attribute names of a table
830-------------------------------------------------
831Syntax::
832
833  get_attnames(table)
834
835Parameters:
836  :table: name of table
837
838Returns:
839  :dictionary:  The keys are the attribute names,
840    the values are the type names of the attributes.
841
842Description:
843  Given the name of a table, digs out the set of attribute names.
844
845get - get a row from a database table or view
846---------------------------------------------
847Syntax::
848
849 get(table, arg, [keyname])
850
851Parameters:
852  :table:   name of table or view
853  :arg:     either a dictionary or the value to be looked up
854  :keyname: name of field to use as key (optional)
855
856Return type:
857  :dictionary: The keys are the attribute names,
858    the values are the row values.
859
860Description:
861  This method is the basic mechanism to get a single row. It assumes
862  that the key specifies a unique row. If keyname is not specified
863  then the primary key for the table is used. If `arg` is a dictionary
864  then the value for the key is taken from it and it is modified to
865  include the new values, replacing existing values where necessary.
866  The OID is also put into the dictionary, but in order to allow the
867  caller to work with multiple tables, it is munged as `oid(schema.table)`.
868
869insert - insert a row into a database table
870-------------------------------------------
871Syntax::
872
873  insert(table, [d,] [key = val, ...])
874
875Parameters:
876  :table: name of table
877  :d:     optional dictionary of values
878
879Return type:
880  :integer: the OID of the newly inserted row
881
882Description:
883  This method inserts values into the table specified filling in the
884  values from the dictionary. It then reloads the dictionary with the
885  values from the database. This causes the dictionary to be updated
886  with values that are modified by rules, triggers, etc.
887
888  If the optional dictionary is not supplied then the required values
889  must be included as keyword/value pairs.  If a dictionary is supplied
890  then any keywords provided will be added to or replace the entry in
891  the dictionary.
892
893  Due to the way that this function works you will find inserts taking
894  longer and longer as your table gets bigger. To overcome this problem
895  simply add an index onto the OID of any table that you think may get
896  large over time. You may also consider using the inserttable() method
897  described in section 3.
898
899update - update a row in a database table
900-----------------------------------------
901Syntax::
902
903  update(table, [d,] [key = val, ...])
904
905Parameters:
906  :table: name of table
907  :d:     optional dictionary of values
908
909Return type:
910  :dictionary: the new row
911
912Description:
913  Similar to insert but updates an existing row. The update is based
914  on the OID value as munged by get. The array returned is the
915  one sent modified to reflect any changes caused by the update due
916  to triggers, rules, defaults, etc.
917
918  Like insert, the dictionary is optional and updates will be performed
919  on the fields in the keywords.  There must be an OID or primary key
920  either in the dictionary where the OID must be munged, or in the keywords
921  where it can be simply the string "oid".
922
923clear - clears row values in memory
924-----------------------------------
925Syntax::
926
927 clear(table, [a])
928
929Parameters:
930  :table: name of table
931  :a:     optional dictionary of values
932
933Return type:
934  :dictionary: an empty row
935
936Description:
937  This method clears all the attributes to values determined by the types.
938  Numeric types are set to 0, Booleans are set to 'f', dates are set
939  to 'now()' and everything else is set to the empty string.
940  If the array argument is present, it is used as the array and any entries
941  matching attribute names are cleared with everything else left unchanged.
942
943  If the dictionary is not supplied a new one is created.
944
945delete - delete a row from a database table
946-------------------------------------------
947Syntax::
948
949  delete(table, [d,] [key = val, ...])
950
951Parameters:
952  :table: name of table
953  :d:     optional dictionary of values
954
955Returns:
956  None
957
958Description:
959  This method deletes the row from a table. It deletes based on the OID
960  as munged as described above.  Alternatively, the keyword "oid" can
961  be used to specify the OID.
962
963escape_string - escape a string for use within SQL
964--------------------------------------------------
965Syntax::
966
967  escape_string(string)
968
969Parameters:
970  :string: the string that is to be escaped
971
972Return type:
973  :str: the escaped string
974
975Description:
976  Similar to the module function with the same name, but the
977  behavior of this method is adjusted depending on the connection properties
978  (such as character encoding).
979
980escape_bytea - escape binary data for use within SQL as type `bytea`
981--------------------------------------------------------------------
982Syntax::
983
984  escape_bytea(datastring)
985
986Parameters:
987  :datastring: string containing the binary data that is to be escaped
988
989Return type:
990  :str: the escaped string
991
992Description:
993  Similar to the module function with the same name, but the
994  behavior of this method is adjusted depending on the connection properties
995  (in particular, whether standard-conforming strings are enabled).
996
997unescape_bytea -- unescape `bytea` data that has been retrieved as text
998-----------------------------------------------------------------------
999Syntax::
1000
1001  unescape_bytea(string)
1002
1003Parameters:
1004  :datastring: the `bytea` data string that has been retrieved as text
1005
1006Return type:
1007  :str: string containing the binary data
1008
1009Description:
1010  See the module function with the same name.
1011
1012
1013pgqueryobject methods
1014=====================
1015
1016getresult - get query values as list of tuples
1017-----------------------------------------------
1018Syntax::
1019
1020  getresult()
1021
1022Parameters:
1023  None
1024
1025Return type:
1026  :list: result values as a list of tuples
1027
1028Exceptions raised:
1029  :TypeError: too many parameters
1030  :pg.InternalError: invalid previous result
1031
1032Description:
1033  This method returns the list of the values returned by the query.
1034  More information about this result may be accessed using listfields(),
1035  fieldname() and fieldnum() methods.
1036
1037dictresult - get query values as list of dictionaries
1038-----------------------------------------------------
1039Syntax::
1040
1041  dictresult()
1042
1043Parameters:
1044  None
1045
1046Return type:
1047  :list: result values as a list of dictionaries
1048
1049Exceptions raised:
1050  :TypeError: too many parameters
1051  :pg.InternalError: invalid previous result
1052
1053Description:
1054  This method returns the list of the values returned by the query
1055  with each tuple returned as a dictionary with the field names
1056  used as the dictionary index.
1057
1058
1059listfields - lists fields names of previous query result
1060--------------------------------------------------------
1061Syntax::
1062
1063  listfields()
1064
1065Parameters:
1066  None
1067
1068Return type:
1069  :list: field names
1070
1071Exceptions raised:
1072  :TypeError: too many parameters
1073  :pg.InternalError: invalid previous result, or lost connection
1074
1075Description:
1076  This method returns the list of names of the fields defined for the
1077  query result. The fields are in the same order as the result values.
1078
1079fieldname, fieldnum - field name/number conversion
1080--------------------------------------------------
1081Syntax::
1082
1083  fieldname(i)
1084
1085Parameters:
1086  :i: field number (integer)
1087
1088Return type:
1089  :string: field name
1090
1091Exceptions raised:
1092  :TypeError: invalid connection, bad parameter type, or too many parameters
1093  :ValueError: invalid field number
1094  :pg.InternalError: invalid previous result, or lost connection
1095
1096Description:
1097  This method allows to find a field name from its rank number. It can be
1098  useful for displaying a result. The fields are in the same order as the
1099  result values.
1100
1101Syntax::
1102
1103  fieldnum(name)
1104
1105Parameters:
1106  :name: field name (string)
1107
1108Return type:
1109  :integer: field number
1110
1111Exceptions raised:
1112  :TypeError: invalid connection, bad parameter type, or too many parameters
1113  :ValueError: unknown field name
1114  :pg.InternalError: invalid previous result, or lost connection
1115
1116Description:
1117  This method returns a field number from its name. It can be used to
1118  build a function that converts result list strings to their correct
1119  type, using a hardcoded table definition. The number returned is the
1120  field rank in the result values list.
1121
1122ntuples - return number of tuples in query object
1123-------------------------------------------------
1124Syntax::
1125
1126  ntuples()
1127
1128Parameters:
1129  None
1130
1131Return type:
1132  :integer: number of tuples in `pgqueryobject`
1133
1134Exceptions raised:
1135  :TypeError: Too many arguments.
1136
1137Description:
1138  This method returns the number of tuples found in a query.
1139
1140
1141Large objects: pglarge
1142======================
1143This object handles all the request concerning a PostgreSQL large object. It
1144embeds and hides all the "recurrent" variables (object OID and connection),
1145exactly in the same way `pgobjects` do, thus only keeping significant
1146parameters in function calls. It keeps a reference to the `pgobject` used for
1147its creation, sending requests though with its parameters. Any modification but
1148dereferencing the `pgobject` will thus affect the `pglarge` object.
1149Dereferencing the initial `pgobject` is not a problem since Python won't
1150deallocate it before the `pglarge` object dereference it.
1151All functions return a generic error message on call error, whatever the
1152exact error was. The `error` attribute of the object allow to get the exact
1153error message.
1154
1155See also the PostgreSQL programmer's guide for more information about the
1156large object interface.
1157
1158open - opens a large object
1159---------------------------
1160Syntax::
1161
1162  open(mode)
1163
1164Parameters:
1165  :mode: open mode definition (integer)
1166
1167Return type:
1168  None
1169
1170Exceptions raised:
1171  :TypeError: invalid connection, bad parameter type, or too many parameters
1172  :IOError: already opened object, or open error
1173
1174Description:
1175  This method opens a large object for reading/writing, in the same way than
1176  the Unix open() function. The mode value can be obtained by OR-ing the
1177  constants defined in the pgmodule (INV_READ, INV_WRITE).
1178
1179close - closes a large object
1180-----------------------------
1181Syntax::
1182
1183  close()
1184
1185Parameters:
1186  None
1187
1188Return type:
1189  None
1190
1191Exceptions raised:
1192  :TypeError: invalid connection
1193  :TypeError: too many parameters
1194  :IOError: object is not opened, or close error
1195
1196Description:
1197  This method closes a previously opened large object, in the same way than
1198  the Unix close() function.
1199
1200read, write, tell, seek, unlink - file like large object handling
1201-----------------------------------------------------------------
1202Syntax::
1203
1204  read(size)
1205
1206Parameters:
1207  :size: maximal size of the buffer to be read
1208
1209Return type:
1210  :sized string: the read buffer
1211
1212Exceptions raised:
1213  :TypeError: invalid connection, invalid object,
1214    bad parameter type, or too many parameters
1215  :ValueError: if `size` is negative
1216  :IOError: object is not opened, or read error
1217
1218Description:
1219  This function allows to read data from a large object, starting at current
1220  position.
1221
1222Syntax::
1223
1224  write(string)
1225
1226Parameters:
1227  (sized) string - buffer to be written
1228
1229Return type:
1230  None
1231
1232Exceptions raised:
1233  :TypeError: invalid connection, bad parameter type, or too many parameters
1234  :IOError: object is not opened, or write error
1235
1236Description:
1237  This function allows to write data to a large object, starting at current
1238  position.
1239
1240Syntax::
1241
1242  seek(offset, whence)
1243
1244Parameters:
1245  :offset: position offset
1246  :whence: positional parameter
1247
1248Return type:
1249  :integer: new position in object
1250
1251Exceptions raised:
1252  :TypeError: binvalid connection or invalid object,
1253    bad parameter type, or too many parameters
1254  :IOError: object is not opened, or seek error
1255
1256Description:
1257  This method allows to move the position cursor in the large object. The
1258  whence parameter can be obtained by OR-ing the constants defined in the
1259  `pg` module (`SEEK_SET`, `SEEK_CUR`, `SEEK_END`).
1260
1261Syntax::
1262
1263  tell()
1264
1265Parameters:
1266  None
1267
1268Return type:
1269  :integer: current position in large object
1270
1271Exceptions raised:
1272  :TypeError: invalid connection or invalid object
1273  :TypeError: too many parameters
1274  :IOError: object is not opened, or seek error
1275
1276Description:
1277  This method allows to get the current position in the large object.
1278
1279Syntax::
1280
1281  unlink()
1282
1283Parameter:
1284  None
1285
1286Return type:
1287  None
1288
1289Exceptions raised:
1290  :TypeError: invalid connection or invalid object
1291  :TypeError: too many parameters
1292  :IOError: object is not closed, or unlink error
1293
1294Description:
1295  This methods unlinks (deletes) the PostgreSQL large object.
1296
1297size - gives the large object size
1298----------------------------------
1299
1300Syntax::
1301
1302  size()
1303
1304Parameters:
1305  None
1306
1307Return type:
1308  :integer: the large object size
1309
1310Exceptions raised:
1311  :TypeError: invalid connection or invalid object
1312  :TypeError: too many parameters
1313  :IOError: object is not opened, or seek/tell error
1314
1315Description:
1316  This (composite) method allows to get the size of a large object. It was
1317  implemented because this function is very useful for a web interfaced
1318  database. Currently, the large object needs to be opened first.
1319
1320export - saves a large object to a file
1321---------------------------------------
1322Syntax::
1323
1324  export(name)
1325
1326Parameters:
1327  :name: file to be created
1328
1329Return type:
1330  None
1331
1332Exceptions raised:
1333  :TypeError: invalid connection or invalid object,
1334    bad parameter type, or too many parameters
1335  :IOError:   object is not closed, or export error
1336
1337Description:
1338  This methods allows to dump the content of a large object in a very simple
1339  way. The exported file is created on the host of the program, not the
1340  server host.
1341
1342Object attributes
1343-----------------
1344`pglarge` objects define a read-only set of attributes that allow to get
1345some information about it. These attributes are:
1346
1347  :oid:   the OID associated with the object
1348  :pgcnx: the `pgobject` associated with the object
1349  :error: the last warning/error message of the connection
1350
1351.. caution:: *Be careful*:
1352  In multithreaded environments, `error` may be modified by another thread
1353  using the same pgobject. Remember these object are shared, not duplicated.
1354  You should provide some locking to be able if you want to check this.
1355  The `oid` attribute is very interesting because it allow you reuse the OID
1356  later, creating the `pglarge` object with a `pgobject` getlo() method call.
Note: See TracBrowser for help on using the repository browser.