source: trunk/docs/pg.txt @ 328

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

If available, use decimal.Decimal for numeric types.

File size: 35.3 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
307.. caution:: It is especially important to do proper escaping when
308  handling strings that were received from an untrustworthy source.
309  Otherwise there is a security risk: you are vulnerable to "SQL injection"
310  attacks wherein unwanted SQL commands are fed to your database.
311
312Example::
313
314  name = raw_input("Name? ")
315  phone = con.query("select phone from employees"
316    " where name='%s'" % escape_string(name)).getresult()
317
318escape_bytea - escape binary data for use within SQL as type `bytea`
319--------------------------------------------------------------------
320Syntax::
321
322  escape_bytea(datastring)
323
324Parameters:
325  :datastring: string containing the binary data that is to be escaped
326
327Return type:
328  :str: the escaped string
329
330Exceptions raised:
331  :TypeError: bad argument type, or too many arguments
332
333Description:
334  Escapes binary data for use within an SQL command with the type `bytea`.
335  As with `escape_string`, this is only used when inserting data directly
336  into an SQL command string.
337
338Example::
339
340  picture = file('garfield.gif', 'rb').read()
341  con.query("update pictures set img='%s' where name='Garfield'"
342    % escape_bytea(picture))
343
344unescape_bytea -- unescape `bytea` data that has been retrieved as text
345-----------------------------------------------------------------------
346Syntax::
347
348  unescape_bytea(string)
349
350Parameters:
351  :datastring: the `bytea` data string that has been retrieved as text
352
353Return type:
354  :str: string containing the binary data
355
356Exceptions raised:
357  :TypeError: bad argument type, or too many arguments
358
359Description:
360  Converts an escaped string representation of binary data into binary
361  data - the reverse of `escape_bytea`. This is needed when retrieving
362  `bytea` data with the `getresult()` or `dictresult()` method.
363
364Example::
365
366  picture = unescape_bytea(con.query(
367    "select img from pictures where name='Garfield'").getresult[0][0])
368  file('garfield.gif', 'wb').write(picture)
369
370set_decimal -- set a decimal type to be used for numeric values
371---------------------------------------------------------------
372Syntax::
373
374  set_decimal(class)
375
376Parameters:
377  :class: the Python class to be used for PostgreSQL numeric values
378
379Description:
380  This function can be used to specify the Python class that shall be
381  used by PyGreSQL to hold PostgreSQL numeric values. The default class
382  is decimal.Decimal if available, otherwise the float type is used.
383
384Module constants
385----------------
386Some constants are defined in the module dictionary.
387They are intended to be used as parameters for methods calls.
388You should refer to the libpq description in the PostgreSQL user manual
389for more information about them. These constants are:
390
391:version, __version__: constants that give the current version.
392:INV_READ, INV_WRITE: large objects access modes,
393  used by `(pgobject.)locreate` and `(pglarge.)open`
394:SEEK_SET, SEEK_CUR, SEEK_END: positional flags,
395  used by `(pglarge.)seek`
396
397
398Connection objects: pgobject
399============================
400This object handles a connection to a PostgreSQL database. It embeds and
401hides all the parameters that define this connection, thus just leaving really
402significant parameters in function calls.
403
404.. caution:: Some methods give direct access to the connection socket.
405  *Do not use them unless you really know what you are doing.*
406  If you prefer disabling them,
407  set the -DNO_DIRECT option in the Python setup file.
408
409  **These methods are specified by the tag [DA].**
410
411.. note:: Some other methods give access to large objects
412  (refer to PostgreSQL user manual for more information about these).
413  If you want to forbid access to these from the module,
414  set the -DNO_LARGE option in the Python setup file.
415
416  **These methods are specified by the tag [LO].**
417
418query - executes a SQL command string
419-------------------------------------
420Syntax::
421
422  query(command)
423
424Parameters:
425  :command: SQL command (string)
426
427Return type:
428  :pgqueryobject, None: result values
429
430Exceptions raised:
431  :TypeError: bad argument type, or too many arguments
432  :ValueError: empty SQL query or lost connection
433  :pg.ProgrammingError: error in query
434  :pg.InternalError': error during query processing
435
436Description:
437  This method simply sends a SQL query to the database. If the query is
438  an insert statement, the return value is the OID of the newly
439  inserted row. If it is otherwise a query that does not return a result
440  (i.e., is not a some kind of SELECT statement), it returns `None`.
441  Otherwise, it returns a `pgqueryobject` that can be accessed via the
442  `getresult()` or `dictresult()` method or simply printed.
443
444reset - resets the connection
445-----------------------------
446Syntax::
447
448  reset()
449
450Parameters:
451  None
452
453Return type:
454  None
455
456Exceptions raised:
457  :TypeError: too many (any) arguments
458
459Description:
460  This method resets the current database connection.
461
462cancel - abandon processing of current SQL command
463--------------------------------------------------
464Syntax::
465
466  cancel()
467
468Parameters:
469  None
470
471Return type:
472  None
473
474Exceptions raised:
475  :TypeError: too many (any) arguments
476
477Description:
478  This method requests that the server abandon processing
479  of the current SQL command.
480
481close - close the database connection
482-------------------------------------
483Syntax::
484
485  close()
486
487Parameters:
488  None
489
490Return type:
491  None
492
493Exceptions raised:
494  :TypeError: too many (any) arguments
495
496Description:
497  This method closes the database connection. The connection will
498  be closed in any case when the connection is deleted but this
499  allows you to explicitly close it. It is mainly here to allow
500  the DB-SIG API wrapper to implement a close function.
501
502fileno - returns the socket used to connect to the database
503-----------------------------------------------------------
504Syntax::
505
506  fileno()
507
508Parameters:
509  None
510
511Exceptions raised:
512  :TypeError: too many (any) arguments
513
514Description:
515  This method returns the underlying socket id used to connect
516  to the database. This is useful for use in select calls, etc.
517
518getnotify - gets the last notify from the server
519------------------------------------------------
520Syntax::
521
522  getnotify()
523
524Parameters:
525  None
526
527Return type:
528  :tuple, None: last notify from server
529
530Exceptions raised:
531  :TypeError: too many parameters
532  :TypeError: invalid connection
533
534Description:
535  This methods try to get a notify from the server (from the SQL statement
536  NOTIFY). If the server returns no notify, the methods returns None.
537  Otherwise, it returns a tuple (couple) `(relname, pid)`, where `relname`
538  is the name of the notify and `pid` the process id of the connection that
539  triggered the notify. Remember to do a listen query first otherwise
540  getnotify() will always return `None`.
541
542inserttable - insert a list into a table
543----------------------------------------
544Syntax::
545
546  inserttable(table, values)
547
548Parameters:
549  :table: the table name (string)
550  :values: list of rows values (list)
551
552Return type:
553  None
554
555Exceptions raised:
556  :TypeError: invalid connection, bad argument type, or too many arguments
557  :MemoryError: insert buffer could not be allocated
558  :ValueError: unsupported values
559
560Description:
561  This method allow to *quickly* insert large blocks of data in a table:
562  It inserts the whole values list into the given table. Internally, it
563  uses the COPY command of the PostgreSQL database. The list is a list
564  of tuples/lists that define the values for each inserted row. The rows
565  values may contain string, integer, long or double (real) values.
566
567.. caution:: *Be very careful*:
568  This method doesn't typecheck the fields according to the table definition;
569  it just look whether or not it knows how to handle such types.
570
571putline - writes a line to the server socket [DA]
572-------------------------------------------------
573Syntax::
574
575  putline(line)
576
577Parameters:
578  :line: line to be written (string)
579
580Return type:
581  None
582
583Exceptions raised:
584  :TypeError: invalid connection, bad parameter type, or too many parameters
585
586Description:
587  This method allows to directly write a string to the server socket.
588
589getline - gets a line from server socket [DA]
590---------------------------------------------
591Syntax::
592
593  getline()
594
595Parameters:
596  None
597
598Return type:
599  :string: the line read
600
601Exceptions raised:
602  :TypeError: invalid connection
603  :TypeError: too many parameters
604  :MemoryError: buffer overflow
605
606Description:
607  This method allows to directly read a string from the server socket.
608
609endcopy - synchronizes client and server [DA]
610---------------------------------------------
611Syntax::
612
613  endcopy()
614
615Parameters:
616  None
617
618Return type:
619  None
620
621Exceptions raised:
622  :TypeError: invalid connection
623  :TypeError: too many parameters
624
625Description:
626  The use of direct access methods may desynchonize client and server.
627  This method ensure that client and server will be synchronized.
628
629locreate - create a large object in the database [LO]
630-----------------------------------------------------
631Syntax::
632
633  locreate(mode)
634
635Parameters:
636  :mode: large object create mode
637
638Return type:
639  :pglarge: object handling the PostGreSQL large object
640
641Exceptions raised:
642
643  :TypeError: invalid connection, bad parameter type, or too many parameters
644  :pg.OperationalError: creation error
645
646Description:
647  This method creates a large object in the database. The mode can be defined
648  by OR-ing the constants defined in the pg module (INV_READ, INV_WRITE and
649  INV_ARCHIVE). Please refer to PostgreSQL user manual for a description of
650  the mode values.
651
652getlo - build a large object from given oid [LO]
653------------------------------------------------
654Syntax::
655
656  getlo(oid)
657
658Parameters:
659  :oid: OID of the existing large object (integer)
660
661Return type:
662  :pglarge: object handling the PostGreSQL large object
663
664Exceptions raised:
665  :TypeError:  invalid connection, bad parameter type, or too many parameters
666  :ValueError: bad OID value (0 is invalid_oid)
667
668Description:
669  This method allows to reuse a formerly created large object through the
670  `pglarge` interface, providing the user have its OID.
671
672loimport - import a file to a large object [LO]
673-----------------------------------------------
674Syntax::
675
676  loimport(name)
677
678Parameters:
679  :name: the name of the file to be imported (string)
680
681Return type:
682  :pglarge: object handling the PostGreSQL large object
683
684Exceptions raised:
685  :TypeError: invalid connection, bad argument type, or too many arguments
686  :pg.OperationalError: error during file import
687
688Description:
689  This methods allows to create large objects in a very simple way. You just
690  give the name of a file containing the data to be use.
691
692Object attributes
693-----------------
694Every `pgobject` defines a set of read-only attributes that describe the
695connection and its status. These attributes are:
696
697  :host:    the host name of the server (string)
698  :port:    the port of the server (integer)
699  :db:      the selected database (string)
700  :options: the connection options (string)
701  :tty:     the connection debug terminal (string)
702  :user:    user name on the database system (string)
703  :status:  the status of the connection (integer: 1 - OK, 0 - bad)
704  :error:   the last warning/error message from the server (string)
705
706
707The DB wrapper class
708====================
709The `pgobject` methods are wrapped in the class `DB`.
710The preferred way to use this module is as follows::
711
712  import pg
713
714  db = pg.DB(...) # see below
715
716  for r in db.query( # just for example
717      """SELECT foo,bar
718         FROM foo_bar_table
719         WHERE foo !~ bar"""
720      ).dictresult():
721
722      print '%(foo)s %(bar)s' % r
723
724This class can be subclassed as in this example::
725
726  import pg
727
728  class DB_ride(pg.DB):
729    """This class encapsulates the database functions and the specific
730       methods for the ride database."""
731
732    def __init__(self):
733        """Opens a database connection to the rides database"""
734
735        pg.DB.__init__(self, dbname = 'ride')
736        self.query("""SET DATESTYLE TO 'ISO'""")
737
738    [Add or override methods here]
739
740The following describes the methods and variables of this class.
741
742Initialization
743--------------
744The DB class is initialized with the same arguments as the connect
745function described in section 2. It also initializes a few
746internal variables. The statement ``db = DB()`` will open the
747local database with the name of the user just like connect() does.
748
749pkey - return the primary key of a table
750----------------------------------------
751Syntax::
752
753  pkey(table)
754
755Parameters:
756  :table: name of table
757
758Return type:
759  :string: Name of the field which is the primary key of the table
760
761Description:
762  This method returns the primary key of a table. Note that this raises
763  an exception if the table does not have a primary key.
764
765get_databases - get list of databases in the system
766---------------------------------------------------
767Syntax::
768
769  get_databases()
770
771Parameters:
772  None
773
774Return type:
775  :list: all databases in the system
776
777Description:
778  Although you can do this with a simple select, it is added here for
779  convenience.
780
781get_relations - get list of relations in connected database
782-----------------------------------------------------------
783Syntax::
784
785  get_relations(kinds)
786
787Parameters:
788  :kinds: a string or sequence of type letters
789
790Description:
791  The type letters are `r` = ordinary table, `i` = index, `S` = sequence,
792  `v` = view, `c` = composite type, `s` = special, `t` = TOAST table.
793  If `kinds` is None or an empty string, all relations are returned (this is
794  also the default). Although you can do this with a simple select, it is
795  added here for convenience.
796
797get_tables - get list of tables in connected database
798-----------------------------------------------------
799Syntax::
800
801  get_tables()
802
803Parameters:
804  None
805
806Returns:
807  :list: all tables in connected database
808
809Description:
810  Although you can do this with a simple select, it is added here for
811  convenience.
812
813get_attnames - get the attribute names of a table
814-------------------------------------------------
815Syntax::
816
817  get_attnames(table)
818
819Parameters:
820  :table: name of table
821
822Returns:
823  :dictionary:  The keys are the attribute names,
824    the values are the type names of the attributes.
825
826Description:
827  Given the name of a table, digs out the set of attribute names.
828
829get - get a row from a database table or view
830---------------------------------------------
831Syntax::
832
833 get(table, arg, [keyname])
834
835Parameters:
836  :table:   name of table or view
837  :arg:     either a dictionary or the value to be looked up
838  :keyname: name of field to use as key (optional)
839
840Return type:
841  :dictionary: The keys are the attribute names,
842    the values are the row values.
843
844Description:
845  This method is the basic mechanism to get a single row. It assumes
846  that the key specifies a unique row. If keyname is not specified
847  then the primary key for the table is used. If `arg` is a dictionary
848  then the value for the key is taken from it and it is modified to
849  include the new values, replacing existing values where necessary.
850  The OID is also put into the dictionary, but in order to allow the
851  caller to work with multiple tables, it is munged as `oid(schema.table)`.
852
853insert - insert a row into a database table
854-------------------------------------------
855Syntax::
856
857  insert(table, [d,] [key = val, ...])
858
859Parameters:
860  :table: name of table
861  :d:     optional dictionary of values
862
863Return type:
864  :integer: the OID of the newly inserted row
865
866Description:
867  This method inserts values into the table specified filling in the
868  values from the dictionary. It then reloads the dictionary with the
869  values from the database. This causes the dictionary to be updated
870  with values that are modified by rules, triggers, etc.
871
872  If the optional dictionary is not supplied then the required values
873  must be included as keyword/value pairs.  If a dictionary is supplied
874  then any keywords provided will be added to or replace the entry in
875  the dictionary.
876
877  Due to the way that this function works you will find inserts taking
878  longer and longer as your table gets bigger. To overcome this problem
879  simply add an index onto the OID of any table that you think may get
880  large over time. You may also consider using the inserttable() method
881  described in section 3.
882
883update - update a row in a database table
884-----------------------------------------
885Syntax::
886
887  update(table, [d,] [key = val, ...])
888
889Parameters:
890  :table: name of table
891  :d:     optional dictionary of values
892
893Return type:
894  :dictionary: the new row
895
896Description:
897  Similar to insert but updates an existing row. The update is based
898  on the OID value as munged by get. The array returned is the
899  one sent modified to reflect any changes caused by the update due
900  to triggers, rules, defaults, etc.
901
902  Like insert, the dictionary is optional and updates will be performed
903  on the fields in the keywords.  There must be an OID or primary key
904  either in the dictionary where the OID must be munged, or in the keywords
905  where it can be simply the string "oid".
906
907clear - clears row values in memory
908-----------------------------------
909Syntax::
910
911 clear(table, [a])
912
913Parameters:
914  :table: name of table
915  :a:     optional dictionary of values
916
917Return type:
918  :dictionary: an empty row
919
920Description:
921  This method clears all the attributes to values determined by the types.
922  Numeric types are set to 0, Booleans are set to 'f', dates are set
923  to 'now()' and everything else is set to the empty string.
924  If the array argument is present, it is used as the array and any entries
925  matching attribute names are cleared with everything else left unchanged.
926
927  If the dictionary is not supplied a new one is created.
928
929delete - delete a row from a database table
930-------------------------------------------
931Syntax::
932
933  delete(table, [d,] [key = val, ...])
934
935Parameters:
936  :table: name of table
937  :d:     optional dictionary of values
938
939Returns:
940  None
941
942Description:
943  This method deletes the row from a table. It deletes based on the OID
944  as munged as described above.  Alternatively, the keyword "oid" can
945  be used to specify the OID.
946
947escape_string - escape a string for use within SQL
948--------------------------------------------------
949Syntax::
950
951  escape_string(string)
952
953Parameters:
954  :string: the string that is to be escaped
955
956Return type:
957  :str: the escaped string
958
959Description:
960  See the module function with the same name.
961
962escape_bytea - escape binary data for use within SQL as type `bytea`
963--------------------------------------------------------------------
964Syntax::
965
966  escape_bytea(datastring)
967
968Parameters:
969  :datastring: string containing the binary data that is to be escaped
970
971Return type:
972  :str: the escaped string
973
974Description:
975  See the module function with the same name.
976
977unescape_bytea -- unescape `bytea` data that has been retrieved as text
978-----------------------------------------------------------------------
979Syntax::
980
981  unescape_bytea(string)
982
983Parameters:
984  :datastring: the `bytea` data string that has been retrieved as text
985
986Return type:
987  :str: string containing the binary data
988
989Description:
990  See the module function with the same name.
991
992
993pgqueryobject methods
994=====================
995
996getresult - get query values as list of tuples
997-----------------------------------------------
998Syntax::
999
1000  getresult()
1001
1002Parameters:
1003  None
1004
1005Return type:
1006  :list: result values as a list of tuples
1007
1008Exceptions raised:
1009  :TypeError: too many parameters
1010  :pg.InternalError: invalid previous result
1011
1012Description:
1013  This method returns the list of the values returned by the query.
1014  More information about this result may be accessed using listfields(),
1015  fieldname() and fieldnum() methods.
1016
1017dictresult - get query values as list of dictionaries
1018-----------------------------------------------------
1019Syntax::
1020
1021  dictresult()
1022
1023Parameters:
1024  None
1025
1026Return type:
1027  :list: result values as a list of dictionaries
1028
1029Exceptions raised:
1030  :TypeError: too many parameters
1031  :pg.InternalError: invalid previous result
1032
1033Description:
1034  This method returns the list of the values returned by the query
1035  with each tuple returned as a dictionary with the field names
1036  used as the dictionary index.
1037
1038
1039listfields - lists fields names of previous query result
1040--------------------------------------------------------
1041Syntax::
1042
1043  listfields()
1044
1045Parameters:
1046  None
1047
1048Return type:
1049  :list: field names
1050
1051Exceptions raised:
1052  :TypeError: too many parameters
1053  :pg.InternalError: invalid previous result, or lost connection
1054
1055Description:
1056  This method returns the list of names of the fields defined for the
1057  query result. The fields are in the same order as the result values.
1058
1059fieldname, fieldnum - field name/number conversion
1060--------------------------------------------------
1061Syntax::
1062
1063  fieldname(i)
1064
1065Parameters:
1066  :i: field number (integer)
1067
1068Return type:
1069  :string: field name
1070
1071Exceptions raised:
1072  :TypeError: invalid connection, bad parameter type, or too many parameters
1073  :ValueError: invalid field number
1074  :pg.InternalError: invalid previous result, or lost connection
1075
1076Description:
1077  This method allows to find a field name from its rank number. It can be
1078  useful for displaying a result. The fields are in the same order as the
1079  result values.
1080
1081Syntax::
1082
1083  fieldnum(name)
1084
1085Parameters:
1086  :name: field name (string)
1087
1088Return type:
1089  :integer: field number
1090
1091Exceptions raised:
1092  :TypeError: invalid connection, bad parameter type, or too many parameters
1093  :ValueError: unknown field name
1094  :pg.InternalError: invalid previous result, or lost connection
1095
1096Description:
1097  This method returns a field number from its name. It can be used to
1098  build a function that converts result list strings to their correct
1099  type, using a hardcoded table definition. The number returned is the
1100  field rank in the result values list.
1101
1102ntuples - return number of tuples in query object
1103-------------------------------------------------
1104Syntax::
1105
1106  ntuples()
1107
1108Parameters:
1109  None
1110
1111Return type:
1112  :integer: number of tuples in `pgqueryobject`
1113
1114Exceptions raised:
1115  :TypeError: Too many arguments.
1116
1117Description:
1118  This method returns the number of tuples found in a query.
1119
1120
1121Large objects: pglarge
1122======================
1123This object handles all the request concerning a PostgreSQL large object. It
1124embeds and hides all the "recurrent" variables (object OID and connection),
1125exactly in the same way `pgobjects` do, thus only keeping significant
1126parameters in function calls. It keeps a reference to the `pgobject` used for
1127its creation, sending requests though with its parameters. Any modification but
1128dereferencing the `pgobject` will thus affect the `pglarge` object.
1129Dereferencing the initial `pgobject` is not a problem since Python won't
1130deallocate it before the `pglarge` object dereference it.
1131All functions return a generic error message on call error, whatever the
1132exact error was. The `error` attribute of the object allow to get the exact
1133error message.
1134
1135See also the PostgreSQL programmer's guide for more information about the
1136large object interface.
1137
1138open - opens a large object
1139---------------------------
1140Syntax::
1141
1142  open(mode)
1143
1144Parameters:
1145  :mode: open mode definition (integer)
1146
1147Return type:
1148  None
1149
1150Exceptions raised:
1151  :TypeError: invalid connection, bad parameter type, or too many parameters
1152  :IOError: already opened object, or open error
1153
1154Description:
1155  This method opens a large object for reading/writing, in the same way than
1156  the Unix open() function. The mode value can be obtained by OR-ing the
1157  constants defined in the pgmodule (INV_READ, INV_WRITE).
1158
1159close - closes a large object
1160-----------------------------
1161Syntax::
1162
1163  close()
1164
1165Parameters:
1166  None
1167
1168Return type:
1169  None
1170
1171Exceptions raised:
1172  :TypeError: invalid connection
1173  :TypeError: too many parameters
1174  :IOError: object is not opened, or close error
1175
1176Description:
1177  This method closes a previously opened large object, in the same way than
1178  the Unix close() function.
1179
1180read, write, tell, seek, unlink - file like large object handling
1181-----------------------------------------------------------------
1182Syntax::
1183
1184  read(size)
1185
1186Parameters:
1187  :size: maximal size of the buffer to be read
1188
1189Return type:
1190  :sized string: the read buffer
1191
1192Exceptions raised:
1193  :TypeError: invalid connection, invalid object,
1194    bad parameter type, or too many parameters
1195  :ValueError: if `size` is negative
1196  :IOError: object is not opened, or read error
1197
1198Description:
1199  This function allows to read data from a large object, starting at current
1200  position.
1201
1202Syntax::
1203
1204  write(string)
1205
1206Parameters:
1207  (sized) string - buffer to be written
1208
1209Return type:
1210  None
1211
1212Exceptions raised:
1213  :TypeError: invalid connection, bad parameter type, or too many parameters
1214  :IOError: object is not opened, or write error
1215
1216Description:
1217  This function allows to write data to a large object, starting at current
1218  position.
1219
1220Syntax::
1221
1222  seek(offset, whence)
1223
1224Parameters:
1225  :offset: position offset
1226  :whence: positional parameter
1227
1228Return type:
1229  :integer: new position in object
1230
1231Exceptions raised:
1232  :TypeError: binvalid connection or invalid object,
1233    bad parameter type, or too many parameters
1234  :IOError: object is not opened, or seek error
1235
1236Description:
1237  This method allows to move the position cursor in the large object. The
1238  whence parameter can be obtained by OR-ing the constants defined in the
1239  `pg` module (`SEEK_SET`, `SEEK_CUR`, `SEEK_END`).
1240
1241Syntax::
1242
1243  tell()
1244
1245Parameters:
1246  None
1247
1248Return type:
1249  :integer: current position in large object
1250
1251Exceptions raised:
1252  :TypeError: invalid connection or invalid object
1253  :TypeError: too many parameters
1254  :IOError: object is not opened, or seek error
1255
1256Description:
1257  This method allows to get the current position in the large object.
1258
1259Syntax::
1260
1261  unlink()
1262
1263Parameter:
1264  None
1265
1266Return type:
1267  None
1268
1269Exceptions raised:
1270  :TypeError: invalid connection or invalid object
1271  :TypeError: too many parameters
1272  :IOError: object is not closed, or unlink error
1273
1274Description:
1275  This methods unlinks (deletes) the PostgreSQL large object.
1276
1277size - gives the large object size
1278----------------------------------
1279
1280Syntax::
1281
1282  size()
1283
1284Parameters:
1285  None
1286
1287Return type:
1288  :integer: the large object size
1289
1290Exceptions raised:
1291  :TypeError: invalid connection or invalid object
1292  :TypeError: too many parameters
1293  :IOError: object is not opened, or seek/tell error
1294
1295Description:
1296  This (composite) method allows to get the size of a large object. It was
1297  implemented because this function is very useful for a web interfaced
1298  database. Currently, the large object needs to be opened first.
1299
1300export - saves a large object to a file
1301---------------------------------------
1302Syntax::
1303
1304  export(name)
1305
1306Parameters:
1307  :name: file to be created
1308
1309Return type:
1310  None
1311
1312Exceptions raised:
1313  :TypeError: invalid connection or invalid object,
1314    bad parameter type, or too many parameters
1315  :IOError:   object is not closed, or export error
1316
1317Description:
1318  This methods allows to dump the content of a large object in a very simple
1319  way. The exported file is created on the host of the program, not the
1320  server host.
1321
1322Object attributes
1323-----------------
1324`pglarge` objects define a read-only set of attributes that allow to get
1325some information about it. These attributes are:
1326
1327  :oid:   the OID associated with the object
1328  :pgcnx: the `pgobject` associated with the object
1329  :error: the last warning/error message of the connection
1330
1331.. caution:: *Be careful*:
1332  In multithreaded environments, `error` may be modified by another thread
1333  using the same pgobject. Remember these object are shared, not duplicated.
1334  You should provide some locking to be able if you want to check this.
1335  The `oid` attribute is very interesting because it allow you reuse the OID
1336  later, creating the `pglarge` object with a `pgobject` getlo() method call.
Note: See TracBrowser for help on using the repository browser.