source: trunk/docs/pg.txt @ 314

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

Add subclass example.

File size: 34.2 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, a)
844
845Parameters:
846  :table: name of table
847  :a:     a 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  Due to the way that this function works you will find inserts taking
859  longer and longer as your table gets bigger. To overcome this problem
860  simply add an index onto the OID of any table that you think may get
861  large over time. You may also consider using the inserttable() method
862  described in section 3.
863
864update - update a row in a database table
865-----------------------------------------
866Syntax::
867
868  update(table, a)
869
870Parameters:
871  :table: name of table
872  :a:     a dictionary of values
873
874Return type:
875  :dictionary: the new row
876
877Description:
878  Similar to insert but updates an existing row. The update is based
879  on the OID value as munged by get. The array returned is the
880  one sent modified to reflect any changes caused by the update due
881  to triggers, rules, defaults, etc.
882
883clear - clears row values in memory
884-----------------------------------
885Syntax::
886
887 clear(table, [a])
888
889Parameters:
890  :table: name of table
891  :a:     a dictionary of values
892
893Return type:
894  :dictionary: an empty row
895
896Description:
897  This method clears all the attributes to values determined by the types.
898  Numeric types are set to 0, Booleans are set to 'f', dates are set
899  to 'now()' and everything else is set to the empty string.
900  If the array argument is present, it is used as the array and any entries
901  matching attribute names are cleared with everything else left unchanged.
902
903delete - delete a row from a database table
904-------------------------------------------
905Syntax::
906
907  delete(table, [a])
908
909Parameters:
910  :table: name of table
911  :a:     a dictionary of values
912
913Returns:
914  None
915
916Description:
917  This method deletes the row from a table. It deletes based on the OID
918  as munged as described above.
919
920escape_string - escape a string for use within SQL
921--------------------------------------------------
922Syntax::
923
924  escape_string(string)
925
926Parameters:
927  :string: the string that is to be escaped
928
929Return type:
930  :str: the escaped string
931
932Description:
933  See the module function with the same name.
934
935escape_bytea - escape binary data for use within SQL as type `bytea`
936--------------------------------------------------------------------
937Syntax::
938
939  escape_bytea(datastring)
940
941Parameters:
942  :datastring: string containing the binary data that is to be escaped
943
944Return type:
945  :str: the escaped string
946
947Description:
948  See the module function with the same name.
949
950unescape_bytea -- unescape `bytea` data that has been retrieved as text
951-----------------------------------------------------------------------
952Syntax::
953
954  unescape_bytea(string)
955
956Parameters:
957  :datastring: the `bytea` data string that has been retrieved as text
958
959Return type:
960  :str: string containing the binary data
961
962Description:
963  See the module function with the same name.
964
965
966pgqueryobject methods
967=====================
968
969getresult - get query values as list of tuples
970-----------------------------------------------
971Syntax::
972
973  getresult()
974
975Parameters:
976  None
977
978Return type:
979  :list: result values as a list of tuples
980
981Exceptions raised:
982  :TypeError: too many parameters
983  :pg.InternalError: invalid previous result
984
985Description:
986  This method returns the list of the values returned by the query.
987  More information about this result may be accessed using listfields(),
988  fieldname() and fieldnum() methods.
989
990dictresult - get query values as list of dictionaries
991-----------------------------------------------------
992Syntax::
993
994  dictresult()
995
996Parameters:
997  None
998
999Return type:
1000  :list: result values as a list of dictionaries
1001
1002Exceptions raised:
1003  :TypeError: too many parameters
1004  :pg.InternalError: invalid previous result
1005
1006Description:
1007  This method returns the list of the values returned by the query
1008  with each tuple returned as a dictionary with the field names
1009  used as the dictionary index.
1010
1011
1012listfields - lists fields names of previous query result
1013--------------------------------------------------------
1014Syntax::
1015
1016  listfields()
1017
1018Parameters:
1019  None
1020
1021Return type:
1022  :list: field names
1023
1024Exceptions raised:
1025  :TypeError: too many parameters
1026  :pg.InternalError: invalid previous result, or lost connection
1027
1028Description:
1029  This method returns the list of names of the fields defined for the
1030  query result. The fields are in the same order as the result values.
1031
1032fieldname, fieldnum - field name/number conversion
1033--------------------------------------------------
1034Syntax::
1035
1036  fieldname(i)
1037
1038Parameters:
1039  :i: field number (integer)
1040
1041Return type:
1042  :string: field name
1043
1044Exceptions raised:
1045  :TypeError: invalid connection, bad parameter type, or too many parameters
1046  :ValueError: invalid field number
1047  :pg.InternalError: invalid previous result, or lost connection
1048
1049Description:
1050  This method allows to find a field name from its rank number. It can be
1051  useful for displaying a result. The fields are in the same order as the
1052  result values.
1053
1054Syntax::
1055
1056  fieldnum(name)
1057
1058Parameters:
1059  :name: field name (string)
1060
1061Return type:
1062  :integer: field number
1063
1064Exceptions raised:
1065  :TypeError: invalid connection, bad parameter type, or too many parameters
1066  :ValueError: unknown field name
1067  :pg.InternalError: invalid previous result, or lost connection
1068
1069Description:
1070  This method returns a field number from its name. It can be used to
1071  build a function that converts result list strings to their correct
1072  type, using a hardcoded table definition. The number returned is the
1073  field rank in the result values list.
1074
1075ntuples - return number of tuples in query object
1076-------------------------------------------------
1077Syntax::
1078
1079  ntuples()
1080
1081Parameters:
1082  None
1083
1084Return type:
1085  :integer: number of tuples in `pgqueryobject`
1086
1087Exceptions raised:
1088  :TypeError: Too many arguments.
1089
1090Description:
1091  This method returns the number of tuples found in a query.
1092
1093
1094Large objects: pglarge
1095======================
1096This object handles all the request concerning a PostgreSQL large object. It
1097embeds and hides all the "recurrent" variables (object OID and connection),
1098exactly in the same way `pgobjects` do, thus only keeping significant
1099parameters in function calls. It keeps a reference to the `pgobject` used for
1100its creation, sending requests though with its parameters. Any modification but
1101dereferencing the `pgobject` will thus affect the `pglarge` object.
1102Dereferencing the initial `pgobject` is not a problem since Python won't
1103deallocate it before the `pglarge` object dereference it.
1104All functions return a generic error message on call error, whatever the
1105exact error was. The `error` attribute of the object allow to get the exact
1106error message.
1107
1108See also the PostgreSQL programmer's guide for more information about the
1109large object interface.
1110
1111open - opens a large object
1112---------------------------
1113Syntax::
1114
1115  open(mode)
1116
1117Parameters:
1118  :mode: open mode definition (integer)
1119
1120Return type:
1121  None
1122
1123Exceptions raised:
1124  :TypeError: invalid connection, bad parameter type, or too many parameters
1125  :IOError: already opened object, or open error
1126
1127Description:
1128  This method opens a large object for reading/writing, in the same way than
1129  the Unix open() function. The mode value can be obtained by OR-ing the
1130  constants defined in the pgmodule (INV_READ, INV_WRITE).
1131
1132close - closes a large object
1133-----------------------------
1134Syntax::
1135
1136  close()
1137
1138Parameters:
1139  None
1140
1141Return type:
1142  None
1143
1144Exceptions raised:
1145  :TypeError: invalid connection
1146  :TypeError: too many parameters
1147  :IOError: object is not opened, or close error
1148
1149Description:
1150  This method closes a previously opened large object, in the same way than
1151  the Unix close() function.
1152
1153read, write, tell, seek, unlink - file like large object handling
1154-----------------------------------------------------------------
1155Syntax::
1156
1157  read(size)
1158
1159Parameters:
1160  :size: maximal size of the buffer to be read
1161
1162Return type:
1163  :sized string: the read buffer
1164
1165Exceptions raised:
1166  :TypeError: invalid connection, invalid object,
1167    bad parameter type, or too many parameters
1168  :ValueError: if `size` is negative
1169  :IOError: object is not opened, or read error
1170
1171Description:
1172  This function allows to read data from a large object, starting at current
1173  position.
1174
1175Syntax::
1176
1177  write(string)
1178
1179Parameters:
1180  (sized) string - buffer to be written
1181
1182Return type:
1183  None
1184
1185Exceptions raised:
1186  :TypeError: invalid connection, bad parameter type, or too many parameters
1187  :IOError: object is not opened, or write error
1188
1189Description:
1190  This function allows to write data to a large object, starting at current
1191  position.
1192
1193Syntax::
1194
1195  seek(offset, whence)
1196
1197Parameters:
1198  :offset: position offset
1199  :whence: positional parameter
1200
1201Return type:
1202  :integer: new position in object
1203
1204Exceptions raised:
1205  :TypeError: binvalid connection or invalid object,
1206    bad parameter type, or too many parameters
1207  :IOError: object is not opened, or seek error
1208
1209Description:
1210  This method allows to move the position cursor in the large object. The
1211  whence parameter can be obtained by OR-ing the constants defined in the
1212  `pg` module (`SEEK_SET`, `SEEK_CUR`, `SEEK_END`).
1213
1214Syntax::
1215
1216  tell()
1217
1218Parameters:
1219  None
1220
1221Return type:
1222  :integer: current position in large object
1223
1224Exceptions raised:
1225  :TypeError: invalid connection or invalid object
1226  :TypeError: too many parameters
1227  :IOError: object is not opened, or seek error
1228
1229Description:
1230  This method allows to get the current position in the large object.
1231
1232Syntax::
1233
1234  unlink()
1235
1236Parameter:
1237  None
1238
1239Return type:
1240  None
1241
1242Exceptions raised:
1243  :TypeError: invalid connection or invalid object
1244  :TypeError: too many parameters
1245  :IOError: object is not closed, or unlink error
1246
1247Description:
1248  This methods unlinks (deletes) the PostgreSQL large object.
1249
1250size - gives the large object size
1251----------------------------------
1252
1253Syntax::
1254
1255  size()
1256
1257Parameters:
1258  None
1259
1260Return type:
1261  :integer: the large object size
1262
1263Exceptions raised:
1264  :TypeError: invalid connection or invalid object
1265  :TypeError: too many parameters
1266  :IOError: object is not opened, or seek/tell error
1267
1268Description:
1269  This (composite) method allows to get the size of a large object. It was
1270  implemented because this function is very useful for a web interfaced
1271  database. Currently, the large object needs to be opened first.
1272
1273export - saves a large object to a file
1274---------------------------------------
1275Syntax::
1276
1277  export(name)
1278
1279Parameters:
1280  :name: file to be created
1281
1282Return type:
1283  None
1284
1285Exceptions raised:
1286  :TypeError: invalid connection or invalid object,
1287    bad parameter type, or too many parameters
1288  :IOError:   object is not closed, or export error
1289
1290Description:
1291  This methods allows to dump the content of a large object in a very simple
1292  way. The exported file is created on the host of the program, not the
1293  server host.
1294
1295Object attributes
1296-----------------
1297`pglarge` objects define a read-only set of attributes that allow to get
1298some information about it. These attributes are:
1299
1300  :oid:   the OID associated with the object
1301  :pgcnx: the `pgobject` associated with the object
1302  :error: the last warning/error message of the connection
1303
1304.. caution:: *Be careful*:
1305  In multithreaded environments, `error` may be modified by another thread
1306  using the same pgobject. Remember these object are shared, not duplicated.
1307  You should provide some locking to be able if you want to check this.
1308  The `oid` attribute is very interesting because it allow you reuse the OID
1309  later, creating the `pglarge` object with a `pgobject` getlo() method call.
Note: See TracBrowser for help on using the repository browser.