source: trunk/docs/pg.txt @ 315

Last change on this file since 315 was 315, checked in by darcy, 13 years ago

Allow keywords to be specified for insert, update and delete.
Document changes.
Add unit tests for changes.

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