source: people/peter.buschman/backup_monitoring/dal/dbapi/dbapi20.txt@ 1095

Last change on this file since 1095 was 976, checked in by peter, on Dec 6, 2011 at 10:19:33 AM

Raw checkin of current NetBackup / TSM parsing code.

File size: 40.5 KB
Line 
1
2 Python Database API Specification v2.0
3
4---------------------------------------------------------------------------
5 http://www.python.org/peps/pep-0249.html
6---------------------------------------------------------------------------
7
8Introduction
9
10 This API has been defined to encourage similarity between the
11 Python modules that are used to access databases. By doing this,
12 we hope to achieve a consistency leading to more easily understood
13 modules, code that is generally more portable across databases,
14 and a broader reach of database connectivity from Python.
15
16 The interface specification consists of several sections:
17
18 * Module Interface
19 * Connection Objects
20 * Cursor Objects
21 * DBI Helper Objects
22 * Type Objects and Constructors
23 * Implementation Hints
24 * Major Changes from 1.0 to 2.0
25
26 Comments and questions about this specification may be directed
27 to the SIG for Database Interfacing with Python
28 (db-sig@python.org).
29
30 For more information on database interfacing with Python and
31 available packages see the Database Topic
32 Guide at http://www.python.org/topics/database/.
33
34 This document describes the Python Database API Specification 2.0
35 and a set of common optional extensions. The previous version 1.0
36 version is still available as reference, in PEP 248. Package
37 writers are encouraged to use this version of the specification as
38 basis for new interfaces.
39
40
41Module Interface
42
43 Access to the database is made available through connection
44 objects. The module must provide the following constructor for
45 these:
46
47 connect(parameters...)
48
49 Constructor for creating a connection to the database.
50 Returns a Connection Object. It takes a number of
51 parameters which are database dependent. [1]
52
53 These module globals must be defined:
54
55 apilevel
56
57 String constant stating the supported DB API level.
58 Currently only the strings '1.0' and '2.0' are allowed.
59
60 If not given, a DB-API 1.0 level interface should be
61 assumed.
62
63 threadsafety
64
65 Integer constant stating the level of thread safety the
66 interface supports. Possible values are:
67
68 0 Threads may not share the module.
69 1 Threads may share the module, but not connections.
70 2 Threads may share the module and connections.
71 3 Threads may share the module, connections and
72 cursors.
73
74 Sharing in the above context means that two threads may
75 use a resource without wrapping it using a mutex semaphore
76 to implement resource locking. Note that you cannot always
77 make external resources thread safe by managing access
78 using a mutex: the resource may rely on global variables
79 or other external sources that are beyond your control.
80
81 paramstyle
82
83 String constant stating the type of parameter marker
84 formatting expected by the interface. Possible values are
85 [2]:
86
87 'qmark' Question mark style,
88 e.g. '...WHERE name=?'
89 'numeric' Numeric, positional style,
90 e.g. '...WHERE name=:1'
91 'named' Named style,
92 e.g. '...WHERE name=:name'
93 'format' ANSI C printf format codes,
94 e.g. '...WHERE name=%s'
95 'pyformat' Python extended format codes,
96 e.g. '...WHERE name=%(name)s'
97
98 The module should make all error information available through
99 these exceptions or subclasses thereof:
100
101 Warning
102
103 Exception raised for important warnings like data
104 truncations while inserting, etc. It must be a subclass of
105 the Python StandardError (defined in the module
106 exceptions).
107
108 Error
109
110 Exception that is the base class of all other error
111 exceptions. You can use this to catch all errors with one
112 single 'except' statement. Warnings are not considered
113 errors and thus should not use this class as base. It must
114 be a subclass of the Python StandardError (defined in the
115 module exceptions).
116
117 InterfaceError
118
119 Exception raised for errors that are related to the
120 database interface rather than the database itself. It
121 must be a subclass of Error.
122
123 DatabaseError
124
125 Exception raised for errors that are related to the
126 database. It must be a subclass of Error.
127
128 DataError
129
130 Exception raised for errors that are due to problems with
131 the processed data like division by zero, numeric value
132 out of range, etc. It must be a subclass of DatabaseError.
133
134 OperationalError
135
136 Exception raised for errors that are related to the
137 database's operation and not necessarily under the control
138 of the programmer, e.g. an unexpected disconnect occurs,
139 the data source name is not found, a transaction could not
140 be processed, a memory allocation error occurred during
141 processing, etc. It must be a subclass of DatabaseError.
142
143 IntegrityError
144
145 Exception raised when the relational integrity of the
146 database is affected, e.g. a foreign key check fails. It
147 must be a subclass of DatabaseError.
148
149 InternalError
150
151 Exception raised when the database encounters an internal
152 error, e.g. the cursor is not valid anymore, the
153 transaction is out of sync, etc. It must be a subclass of
154 DatabaseError.
155
156 ProgrammingError
157
158 Exception raised for programming errors, e.g. table not
159 found or already exists, syntax error in the SQL
160 statement, wrong number of parameters specified, etc. It
161 must be a subclass of DatabaseError.
162
163 NotSupportedError
164
165 Exception raised in case a method or database API was used
166 which is not supported by the database, e.g. requesting a
167 .rollback() on a connection that does not support
168 transaction or has transactions turned off. It must be a
169 subclass of DatabaseError.
170
171 This is the exception inheritance layout:
172
173 StandardError
174 |__Warning
175 |__Error
176 |__InterfaceError
177 |__DatabaseError
178 |__DataError
179 |__OperationalError
180 |__IntegrityError
181 |__InternalError
182 |__ProgrammingError
183 |__NotSupportedError
184
185 Note: The values of these exceptions are not defined. They should
186 give the user a fairly good idea of what went wrong, though.
187
188
189
190Connection Objects
191
192 Connection Objects should respond to the following methods:
193
194 .close()
195
196 Close the connection now (rather than whenever __del__ is
197 called). The connection will be unusable from this point
198 forward; an Error (or subclass) exception will be raised
199 if any operation is attempted with the connection. The
200 same applies to all cursor objects trying to use the
201 connection. Note that closing a connection without
202 committing the changes first will cause an implicit
203 rollback to be performed.
204
205
206 .commit()
207
208 Commit any pending transaction to the database. Note that
209 if the database supports an auto-commit feature, this must
210 be initially off. An interface method may be provided to
211 turn it back on.
212
213 Database modules that do not support transactions should
214 implement this method with void functionality.
215
216 .rollback()
217
218 This method is optional since not all databases provide
219 transaction support. [3]
220
221 In case a database does provide transactions this method
222 causes the the database to roll back to the start of any
223 pending transaction. Closing a connection without
224 committing the changes first will cause an implicit
225 rollback to be performed.
226
227 .cursor()
228
229 Return a new Cursor Object using the connection. If the
230 database does not provide a direct cursor concept, the
231 module will have to emulate cursors using other means to
232 the extent needed by this specification. [4]
233
234
235
236Cursor Objects
237
238 These objects represent a database cursor, which is used to
239 manage the context of a fetch operation. Cursors created from
240 the same connection are not isolated, i.e., any changes
241 done to the database by a cursor are immediately visible by the
242 other cursors. Cursors created from different connections can
243 or can not be isolated, depending on how the transaction support
244 is implemented (see also the connection's rollback() and commit()
245 methods.)
246
247 Cursor Objects should respond to the following methods and
248 attributes:
249
250 .description
251
252 This read-only attribute is a sequence of 7-item
253 sequences. Each of these sequences contains information
254 describing one result column: (name, type_code,
255 display_size, internal_size, precision, scale,
256 null_ok). The first two items (name and type_code) are
257 mandatory, the other five are optional and must be set to
258 None if meaningfull values are not provided.
259
260 This attribute will be None for operations that
261 do not return rows or if the cursor has not had an
262 operation invoked via the executeXXX() method yet.
263
264 The type_code can be interpreted by comparing it to the
265 Type Objects specified in the section below.
266
267 .rowcount
268
269 This read-only attribute specifies the number of rows that
270 the last executeXXX() produced (for DQL statements like
271 'select') or affected (for DML statements like 'update' or
272 'insert').
273
274 The attribute is -1 in case no executeXXX() has been
275 performed on the cursor or the rowcount of the last
276 operation is not determinable by the interface. [7]
277
278 Note: Future versions of the DB API specification could
279 redefine the latter case to have the object return None
280 instead of -1.
281
282 .callproc(procname[,parameters])
283
284 (This method is optional since not all databases provide
285 stored procedures. [3])
286
287 Call a stored database procedure with the given name. The
288 sequence of parameters must contain one entry for each
289 argument that the procedure expects. The result of the
290 call is returned as modified copy of the input
291 sequence. Input parameters are left untouched, output and
292 input/output parameters replaced with possibly new values.
293
294 The procedure may also provide a result set as
295 output. This must then be made available through the
296 standard fetchXXX() methods.
297
298 .close()
299
300 Close the cursor now (rather than whenever __del__ is
301 called). The cursor will be unusable from this point
302 forward; an Error (or subclass) exception will be raised
303 if any operation is attempted with the cursor.
304
305 .execute(operation[,parameters])
306
307 Prepare and execute a database operation (query or
308 command). Parameters may be provided as sequence or
309 mapping and will be bound to variables in the operation.
310 Variables are specified in a database-specific notation
311 (see the module's paramstyle attribute for details). [5]
312
313 A reference to the operation will be retained by the
314 cursor. If the same operation object is passed in again,
315 then the cursor can optimize its behavior. This is most
316 effective for algorithms where the same operation is used,
317 but different parameters are bound to it (many times).
318
319 For maximum efficiency when reusing an operation, it is
320 best to use the setinputsizes() method to specify the
321 parameter types and sizes ahead of time. It is legal for
322 a parameter to not match the predefined information; the
323 implementation should compensate, possibly with a loss of
324 efficiency.
325
326 The parameters may also be specified as list of tuples to
327 e.g. insert multiple rows in a single operation, but this
328 kind of usage is depreciated: executemany() should be used
329 instead.
330
331 Return values are not defined.
332
333 .executemany(operation,seq_of_parameters)
334
335 Prepare a database operation (query or command) and then
336 execute it against all parameter sequences or mappings
337 found in the sequence seq_of_parameters.
338
339 Modules are free to implement this method using multiple
340 calls to the execute() method or by using array operations
341 to have the database process the sequence as a whole in
342 one call.
343
344 Use of this method for an operation which produces one or
345 more result sets constitutes undefined behavior, and the
346 implementation is permitted (but not required) to raise
347 an exception when it detects that a result set has been
348 created by an invocation of the operation.
349
350 The same comments as for execute() also apply accordingly
351 to this method.
352
353 Return values are not defined.
354
355 .fetchone()
356
357 Fetch the next row of a query result set, returning a
358 single sequence, or None when no more data is
359 available. [6]
360
361 An Error (or subclass) exception is raised if the previous
362 call to executeXXX() did not produce any result set or no
363 call was issued yet.
364
365 fetchmany([size=cursor.arraysize])
366
367 Fetch the next set of rows of a query result, returning a
368 sequence of sequences (e.g. a list of tuples). An empty
369 sequence is returned when no more rows are available.
370
371 The number of rows to fetch per call is specified by the
372 parameter. If it is not given, the cursor's arraysize
373 determines the number of rows to be fetched. The method
374 should try to fetch as many rows as indicated by the size
375 parameter. If this is not possible due to the specified
376 number of rows not being available, fewer rows may be
377 returned.
378
379 An Error (or subclass) exception is raised if the previous
380 call to executeXXX() did not produce any result set or no
381 call was issued yet.
382
383 Note there are performance considerations involved with
384 the size parameter. For optimal performance, it is
385 usually best to use the arraysize attribute. If the size
386 parameter is used, then it is best for it to retain the
387 same value from one fetchmany() call to the next.
388
389 .fetchall()
390
391 Fetch all (remaining) rows of a query result, returning
392 them as a sequence of sequences (e.g. a list of tuples).
393 Note that the cursor's arraysize attribute can affect the
394 performance of this operation.
395
396 An Error (or subclass) exception is raised if the previous
397 call to executeXXX() did not produce any result set or no
398 call was issued yet.
399
400 .nextset()
401
402 (This method is optional since not all databases support
403 multiple result sets. [3])
404
405 This method will make the cursor skip to the next
406 available set, discarding any remaining rows from the
407 current set.
408
409 If there are no more sets, the method returns
410 None. Otherwise, it returns a true value and subsequent
411 calls to the fetch methods will return rows from the next
412 result set.
413
414 An Error (or subclass) exception is raised if the previous
415 call to executeXXX() did not produce any result set or no
416 call was issued yet.
417
418 .arraysize
419
420 This read/write attribute specifies the number of rows to
421 fetch at a time with fetchmany(). It defaults to 1 meaning
422 to fetch a single row at a time.
423
424 Implementations must observe this value with respect to
425 the fetchmany() method, but are free to interact with the
426 database a single row at a time. It may also be used in
427 the implementation of executemany().
428
429 .setinputsizes(sizes)
430
431 This can be used before a call to executeXXX() to
432 predefine memory areas for the operation's parameters.
433
434 sizes is specified as a sequence -- one item for each
435 input parameter. The item should be a Type Object that
436 corresponds to the input that will be used, or it should
437 be an integer specifying the maximum length of a string
438 parameter. If the item is None, then no predefined memory
439 area will be reserved for that column (this is useful to
440 avoid predefined areas for large inputs).
441
442 This method would be used before the executeXXX() method
443 is invoked.
444
445 Implementations are free to have this method do nothing
446 and users are free to not use it.
447
448 .setoutputsize(size[,column])
449
450 Set a column buffer size for fetches of large columns
451 (e.g. LONGs, BLOBs, etc.). The column is specified as an
452 index into the result sequence. Not specifying the column
453 will set the default size for all large columns in the
454 cursor.
455
456 This method would be used before the executeXXX() method
457 is invoked.
458
459 Implementations are free to have this method do nothing
460 and users are free to not use it.
461
462
463
464Type Objects and Constructors
465
466 Many databases need to have the input in a particular format for
467 binding to an operation's input parameters. For example, if an
468 input is destined for a DATE column, then it must be bound to the
469 database in a particular string format. Similar problems exist
470 for "Row ID" columns or large binary items (e.g. blobs or RAW
471 columns). This presents problems for Python since the parameters
472 to the executeXXX() method are untyped. When the database module
473 sees a Python string object, it doesn't know if it should be bound
474 as a simple CHAR column, as a raw BINARY item, or as a DATE.
475
476 To overcome this problem, a module must provide the constructors
477 defined below to create objects that can hold special values.
478 When passed to the cursor methods, the module can then detect the
479 proper type of the input parameter and bind it accordingly.
480
481 A Cursor Object's description attribute returns information about
482 each of the result columns of a query. The type_code must compare
483 equal to one of Type Objects defined below. Type Objects may be
484 equal to more than one type code (e.g. DATETIME could be equal to
485 the type codes for date, time and timestamp columns; see the
486 Implementation Hints below for details).
487
488 The module exports the following constructors and singletons:
489
490 Date(year,month,day)
491
492 This function constructs an object holding a date value.
493
494 Time(hour,minute,second)
495
496 This function constructs an object holding a time value.
497
498 Timestamp(year,month,day,hour,minute,second)
499
500 This function constructs an object holding a time stamp
501 value.
502
503 DateFromTicks(ticks)
504
505 This function constructs an object holding a date value
506 from the given ticks value (number of seconds since the
507 epoch; see the documentation of the standard Python time
508 module for details).
509
510 TimeFromTicks(ticks)
511
512 This function constructs an object holding a time value
513 from the given ticks value (number of seconds since the
514 epoch; see the documentation of the standard Python time
515 module for details).
516
517 TimestampFromTicks(ticks)
518
519 This function constructs an object holding a time stamp
520 value from the given ticks value (number of seconds since
521 the epoch; see the documentation of the standard Python
522 time module for details).
523
524 Binary(string)
525
526 This function constructs an object capable of holding a
527 binary (long) string value.
528
529
530 STRING
531
532 This type object is used to describe columns in a database
533 that are string-based (e.g. CHAR).
534
535 BINARY
536
537 This type object is used to describe (long) binary columns
538 in a database (e.g. LONG, RAW, BLOBs).
539
540 NUMBER
541
542 This type object is used to describe numeric columns in a
543 database.
544
545 DATETIME
546
547 This type object is used to describe date/time columns in
548 a database.
549
550 ROWID
551
552 This type object is used to describe the "Row ID" column
553 in a database.
554
555 SQL NULL values are represented by the Python None singleton on
556 input and output.
557
558 Note: Usage of Unix ticks for database interfacing can cause
559 troubles because of the limited date range they cover.
560
561
562
563Implementation Hints for Module Authors
564
565 * The preferred object types for the date/time objects are those
566 defined in the mxDateTime package. It provides all necessary
567 constructors and methods both at Python and C level.
568
569 * The preferred object type for Binary objects are the
570 buffer types available in standard Python starting with
571 version 1.5.2. Please see the Python documentation for
572 details. For information about the the C interface have a
573 look at Include/bufferobject.h and
574 Objects/bufferobject.c in the Python source
575 distribution.
576
577 * Starting with Python 2.3, module authors can also use the object
578 types defined in the standard datetime module for date/time
579 processing. However, it should be noted that this does not
580 expose a C API like mxDateTime does which means that integration
581 with C based database modules is more difficult.
582
583 * Here is a sample implementation of the Unix ticks based
584 constructors for date/time delegating work to the generic
585 constructors:
586
587 import time
588
589 def DateFromTicks(ticks):
590 return apply(Date,time.localtime(ticks)[:3])
591
592 def TimeFromTicks(ticks):
593 return apply(Time,time.localtime(ticks)[3:6])
594
595 def TimestampFromTicks(ticks):
596 return apply(Timestamp,time.localtime(ticks)[:6])
597
598 * This Python class allows implementing the above type
599 objects even though the description type code field yields
600 multiple values for on type object:
601
602 class DBAPITypeObject:
603 def __init__(self,*values):
604 self.values = values
605 def __cmp__(self,other):
606 if other in self.values:
607 return 0
608 if other < self.values:
609 return 1
610 else:
611 return -1
612
613 The resulting type object compares equal to all values
614 passed to the constructor.
615
616 * Here is a snippet of Python code that implements the exception
617 hierarchy defined above:
618
619 import exceptions
620
621 class Error(exceptions.StandardError):
622 pass
623
624 class Warning(exceptions.StandardError):
625 pass
626
627 class InterfaceError(Error):
628 pass
629
630 class DatabaseError(Error):
631 pass
632
633 class InternalError(DatabaseError):
634 pass
635
636 class OperationalError(DatabaseError):
637 pass
638
639 class ProgrammingError(DatabaseError):
640 pass
641
642 class IntegrityError(DatabaseError):
643 pass
644
645 class DataError(DatabaseError):
646 pass
647
648 class NotSupportedError(DatabaseError):
649 pass
650
651 In C you can use the PyErr_NewException(fullname,
652 base, NULL) API to create the exception objects.
653
654
655
656Optional DB API Extensions
657
658 During the lifetime of DB API 2.0, module authors have often
659 extended their implementations beyond what is required by this DB
660 API specification. To enhance compatibility and to provide a clean
661 upgrade path to possible future versions of the specification,
662 this section defines a set of common extensions to the core DB API
663 2.0 specification.
664
665 As with all DB API optional features, the database module authors
666 are free to not implement these additional attributes and methods
667 (using them will then result in an AttributeError) or to raise a
668 NotSupportedError in case the availability can only be checked at
669 run-time.
670
671 It has been proposed to make usage of these extensions optionally
672 visible to the programmer by issuing Python warnings through the
673 Python warning framework. To make this feature useful, the warning
674 messages must be standardized in order to be able to mask them. These
675 standard messages are referred to below as "Warning Message".
676
677 Cursor Attribute .rownumber
678
679 This read-only attribute should provide the current 0-based
680 index of the cursor in the result set or None if the index cannot
681 be determined.
682
683 The index can be seen as index of the cursor in a sequence (the
684 result set). The next fetch operation will fetch the row
685 indexed by .rownumber in that sequence.
686
687 Warning Message: "DB-API extension cursor.rownumber used"
688
689 Connection Attributes .Error, .ProgrammingError, etc.
690
691 All exception classes defined by the DB API standard should be
692 exposed on the Connection objects are attributes (in addition
693 to being available at module scope).
694
695 These attributes simplify error handling in multi-connection
696 environments.
697
698 Warning Message: "DB-API extension connection.<exception> used"
699
700 Cursor Attributes .connection
701
702 This read-only attribute return a reference to the Connection
703 object on which the cursor was created.
704
705 The attribute simplifies writing polymorph code in
706 multi-connection environments.
707
708 Warning Message: "DB-API extension cursor.connection used"
709
710 Cursor Method .scroll(value[,mode='relative'])
711
712 Scroll the cursor in the result set to a new position according
713 to mode.
714
715 If mode is 'relative' (default), value is taken as offset to
716 the current position in the result set, if set to 'absolute',
717 value states an absolute target position.
718
719 An IndexError should be raised in case a scroll operation would
720 leave the result set. In this case, the cursor position is left
721 undefined (ideal would be to not move the cursor at all).
722
723 Note: This method should use native scrollable cursors, if
724 available , or revert to an emulation for forward-only
725 scrollable cursors. The method may raise NotSupportedErrors to
726 signal that a specific operation is not supported by the
727 database (e.g. backward scrolling).
728
729 Warning Message: "DB-API extension cursor.scroll() used"
730
731 Cursor Attribute .messages
732
733 This is a Python list object to which the interface appends
734 tuples (exception class, exception value) for all messages
735 which the interfaces receives from the underlying database for
736 this cursor.
737
738 The list is cleared by all standard cursor methods calls (prior
739 to executing the call) except for the .fetchXXX() calls
740 automatically to avoid excessive memory usage and can also be
741 cleared by executing "del cursor.messages[:]".
742
743 All error and warning messages generated by the database are
744 placed into this list, so checking the list allows the user to
745 verify correct operation of the method calls.
746
747 The aim of this attribute is to eliminate the need for a
748 Warning exception which often causes problems (some warnings
749 really only have informational character).
750
751 Warning Message: "DB-API extension cursor.messages used"
752
753 Connection Attribute .messages
754
755 Same as cursor.messages except that the messages in the list
756 are connection oriented.
757
758 The list is cleared automatically by all standard connection
759 methods calls (prior to executing the call) to avoid excessive
760 memory usage and can also be cleared by executing "del
761 connection.messages[:]".
762
763 Warning Message: "DB-API extension connection.messages used"
764
765 Cursor Method .next()
766
767 Return the next row from the currently executing SQL statement
768 using the same semantics as .fetchone(). A StopIteration
769 exception is raised when the result set is exhausted for Python
770 versions 2.2 and later. Previous versions don't have the
771 StopIteration exception and so the method should raise an
772 IndexError instead.
773
774 Warning Message: "DB-API extension cursor.next() used"
775
776 Cursor Method .__iter__()
777
778 Return self to make cursors compatible to the iteration protocol.
779
780 Warning Message: "DB-API extension cursor.__iter__() used"
781
782 Cursor Attribute .lastrowid
783
784 This read-only attribute provides the rowid of the last
785 modified row (most databases return a rowid only when a single
786 INSERT operation is performed). If the operation does not set
787 a rowid or if the database does not support rowids, this
788 attribute should be set to None.
789
790 The semantics of .lastrowid are undefined in case the last
791 executed statement modified more than one row, e.g. when
792 using INSERT with .executemany().
793
794 Warning Message: "DB-API extension cursor.lastrowid used"
795
796
797
798Optional Error Handling Extension
799
800 The core DB API specification only introduces a set of exceptions
801 which can be raised to report errors to the user. In some cases,
802 exceptions may be too disruptive for the flow of a program or even
803 render execution impossible.
804
805 For these cases and in order to simplify error handling when
806 dealing with databases, database module authors may choose to
807 implement user defineable error handlers. This section describes a
808 standard way of defining these error handlers.
809
810 Cursor/Connection Attribute .errorhandler
811
812 Read/write attribute which references an error handler to call
813 in case an error condition is met.
814
815 The handler must be a Python callable taking the following
816 arguments: errorhandler(connection, cursor, errorclass,
817 errorvalue) where connection is a reference to the connection
818 on which the cursor operates, cursor a reference to the cursor
819 (or None in case the error does not apply to a cursor),
820 errorclass is an error class which to instantiate using
821 errorvalue as construction argument.
822
823 The standard error handler should add the error information to
824 the appropriate .messages attribute (connection.messages or
825 cursor.messages) and raise the exception defined by the given
826 errorclass and errorvalue parameters.
827
828 If no errorhandler is set (the attribute is None), the standard
829 error handling scheme as outlined above, should be applied.
830
831 Warning Message: "DB-API extension .errorhandler used"
832
833 Cursors should inherit the .errorhandler setting from their
834 connection objects at cursor creation time.
835
836
837
838Frequently Asked Questions
839
840 The database SIG often sees reoccurring questions about the DB API
841 specification. This section covers some of the issues people
842 sometimes have with the specification.
843
844 Question:
845
846 How can I construct a dictionary out of the tuples returned by
847 .fetchxxx():
848
849 Answer:
850
851 There are several existing tools available which provide
852 helpers for this task. Most of them use the approach of using
853 the column names defined in the cursor attribute .description
854 as basis for the keys in the row dictionary.
855
856 Note that the reason for not extending the DB API specification
857 to also support dictionary return values for the .fetchxxx()
858 methods is that this approach has several drawbacks:
859
860 * Some databases don't support case-sensitive column names or
861 auto-convert them to all lowercase or all uppercase
862 characters.
863
864 * Columns in the result set which are generated by the query
865 (e.g. using SQL functions) don't map to table column names
866 and databases usually generate names for these columns in a
867 very database specific way.
868
869 As a result, accessing the columns through dictionary keys
870 varies between databases and makes writing portable code
871 impossible.
872
873
874
875Major Changes from Version 1.0 to Version 2.0
876
877 The Python Database API 2.0 introduces a few major changes
878 compared to the 1.0 version. Because some of these changes will
879 cause existing DB API 1.0 based scripts to break, the major
880 version number was adjusted to reflect this change.
881
882 These are the most important changes from 1.0 to 2.0:
883
884 * The need for a separate dbi module was dropped and the
885 functionality merged into the module interface itself.
886
887 * New constructors and Type Objects were added for date/time
888 values, the RAW Type Object was renamed to BINARY. The
889 resulting set should cover all basic data types commonly
890 found in modern SQL databases.
891
892 * New constants (apilevel, threadlevel, paramstyle) and
893 methods (executemany, nextset) were added to provide better
894 database bindings.
895
896 * The semantics of .callproc() needed to call stored
897 procedures are now clearly defined.
898
899 * The definition of the .execute() return value changed.
900 Previously, the return value was based on the SQL statement
901 type (which was hard to implement right) -- it is undefined
902 now; use the more flexible .rowcount attribute
903 instead. Modules are free to return the old style return
904 values, but these are no longer mandated by the
905 specification and should be considered database interface
906 dependent.
907
908 * Class based exceptions were incorporated into the
909 specification. Module implementors are free to extend the
910 exception layout defined in this specification by
911 subclassing the defined exception classes.
912
913 Post-publishing additions to the DB API 2.0 specification:
914
915 * Additional optional DB API extensions to the set of
916 core functionality were specified.
917
918
919
920Open Issues
921
922 Although the version 2.0 specification clarifies a lot of
923 questions that were left open in the 1.0 version, there are still
924 some remaining issues which should be addressed in future
925 versions:
926
927 * Define a useful return value for .nextset() for the case where
928 a new result set is available.
929
930 * Create a fixed point numeric type for use as loss-less
931 monetary and decimal interchange format.
932
933
934
935Footnotes
936
937 [1] As a guideline the connection constructor parameters should be
938 implemented as keyword parameters for more intuitive use and
939 follow this order of parameters:
940
941 dsn Data source name as string
942 user User name as string (optional)
943 password Password as string (optional)
944 host Hostname (optional)
945 database Database name (optional)
946
947 E.g. a connect could look like this:
948
949 connect(dsn='myhost:MYDB',user='guido',password='234$')
950
951 [2] Module implementors should prefer 'numeric', 'named' or
952 'pyformat' over the other formats because these offer more
953 clarity and flexibility.
954
955 [3] If the database does not support the functionality required
956 by the method, the interface should throw an exception in
957 case the method is used.
958
959 The preferred approach is to not implement the method and
960 thus have Python generate an AttributeError in
961 case the method is requested. This allows the programmer to
962 check for database capabilities using the standard
963 hasattr() function.
964
965 For some dynamically configured interfaces it may not be
966 appropriate to require dynamically making the method
967 available. These interfaces should then raise a
968 NotSupportedError to indicate the non-ability
969 to perform the roll back when the method is invoked.
970
971 [4] a database interface may choose to support named cursors by
972 allowing a string argument to the method. This feature is
973 not part of the specification, since it complicates
974 semantics of the .fetchXXX() methods.
975
976 [5] The module will use the __getitem__ method of the parameters
977 object to map either positions (integers) or names (strings)
978 to parameter values. This allows for both sequences and
979 mappings to be used as input.
980
981 The term "bound" refers to the process of binding an input
982 value to a database execution buffer. In practical terms,
983 this means that the input value is directly used as a value
984 in the operation. The client should not be required to
985 "escape" the value so that it can be used -- the value
986 should be equal to the actual database value.
987
988 [6] Note that the interface may implement row fetching using
989 arrays and other optimizations. It is not
990 guaranteed that a call to this method will only move the
991 associated cursor forward by one row.
992
993 [7] The rowcount attribute may be coded in a way that updates
994 its value dynamically. This can be useful for databases that
995 return usable rowcount values only after the first call to
996 a .fetchXXX() method.
997
998
999Acknowledgements
1000
1001 Many thanks go to Andrew Kuchling who converted the Python
1002 Database API Specification 2.0 from the original HTML format into
1003 the PEP format.
1004
1005
1006Copyright
1007
1008 This document has been placed in the Public Domain.
1009
1010
1011
Note: See TracBrowser for help on using the repository browser.