# KInterbasDB Python Package - Python Wrapper for Core
#
# Version 3.1
#
# The following contributors hold Copyright (C) over their respective
# portions of code (see license.txt for details):
#
# [Original Author (maintained through version 2.0-0.3.1):]
#   1998-2001 [alex]  Alexander Kuznetsov   <alexan@users.sourceforge.net>
# [Maintainers (after version 2.0-0.3.1):]
#   2001-2002 [maz]   Marek Isalski         <kinterbasdb@maz.nu>
#   2002-2004 [dsr]   David Rushby          <woodsplitter@rocketmail.com>
# [Contributors:]
#   2001      [eac]   Evgeny A. Cherkashin  <eugeneai@icc.ru>
#   2001-2002 [janez] Janez Jere            <janez.jere@void.si>

#   The doc strings throughout this module explain what API *guarantees*
# kinterbasdb makes.
#   Notably, the fact that users can only rely on the return values of certain
# functions/methods to be sequences or mappings, not instances of a specific
# class.  This policy is still compliant with the DB API spec, and is more
# future-proof than implying that all of the classes defined herein can be
# relied upon not to change.  Now, only module contents in "PUBLIC ..."
# sections AND with names that do not begin with an underscore can be expected
# to have stable interfaces.

from __future__ import nested_scopes # Maintain compatibility with Python 2.1

__version__ = (3, 1, 0, 'final', 0)

import struct, sys, types, warnings, weakref

try:
    True, False
except NameError:
    # Maintain compatibility with Python 2.1 and 2.2.0:
    True = (1==1)
    False = (1==0)

# 2003.12.25: For FB 1.5 RC7 and later:
# Add the directory indicated in the registry as the default installation of
# Firebird to the *end* of the PATH.
if sys.platform.lower().startswith('win'):
    import _winreg, os, os.path

    reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
    try:
        try:
            dbInstPathsKey = _winreg.OpenKey(
                reg, r'SOFTWARE\Firebird Project\Firebird Server\Instances'
              )
            try:
                instPath = _winreg.QueryValueEx(dbInstPathsKey, 'DefaultInstance')[0]
            finally:
                dbInstPathsKey.Close()
        except WindowsError:
            # Versions of IB/FB prior to FB 1.5 RC7 don't have this reg entry,
            # but they install the client library into a system library
            # directory, so there's no problem.
            pass
        else:
            os.environ['PATH'] += os.pathsep + os.path.join(instPath, 'bin')
    finally:
        reg.Close()

# The underlying C module:
import _kinterbasdb as _k


# Initialize the k_exceptions so that other Python modules in kinterbasdb can
# have access to kinterbasdb's exceptions without a circular import.
import k_exceptions

Warning               = k_exceptions.Warning            = _k.Warning
Error                 = k_exceptions.Error              = _k.Error
InterfaceError        = k_exceptions.InterfaceError     = _k.InterfaceError
DatabaseError         = k_exceptions.DatabaseError      = _k.DatabaseError
DataError             = k_exceptions.DataError          = _k.DataError
OperationalError      = k_exceptions.OperationalError   = _k.OperationalError
IntegrityError        = k_exceptions.IntegrityError     = _k.IntegrityError
InternalError         = k_exceptions.InternalError      = _k.InternalError
ProgrammingError      = k_exceptions.ProgrammingError   = _k.ProgrammingError
NotSupportedError     = k_exceptions.NotSupportedError  = _k.NotSupportedError

_ALL_EXCEPTION_CLASSES = (
    Warning,
    Error,
    InterfaceError,
    DatabaseError,
    DataError,
    OperationalError,
    IntegrityError,
    InternalError,
    ProgrammingError,
    NotSupportedError,
  )


try:
    import thread
    _threads_supported = True
except ImportError:
    _threads_supported = False


# Exclude event handling if support for it is not compiled into the underlying
# C module:
_EVENT_HANDLING_SUPPORTED = hasattr(_k, 'event_conduit_new')


##########################################
##     PUBLIC CONSTANTS: BEGIN          ##
##########################################

apilevel = '2.0'
threadsafety = 1
paramstyle = 'qmark'

# Named positional constants to be used as indices into the description
# attribute of a cursor (these positions are defined by the DB API spec).
# For example:
#   nameOfFirstField = cursor.description[0][kinterbasdb.DESCRIPTION_NAME]

DESCRIPTION_NAME            = 0
DESCRIPTION_TYPE_CODE       = 1
DESCRIPTION_DISPLAY_SIZE    = 2
DESCRIPTION_INTERNAL_SIZE   = 3
DESCRIPTION_PRECISION       = 4
DESCRIPTION_SCALE           = 5
DESCRIPTION_NULL_OK         = 6

# Header constants defined by the C API of the database:
# (This implementation draws the constants' values from the database header
# files rather than relying on brittle literals.)

# Transaction parameter constants:
isc_tpb_consistency              =  _k.isc_tpb_consistency
isc_tpb_concurrency              =  _k.isc_tpb_concurrency
isc_tpb_shared                   =  _k.isc_tpb_shared
isc_tpb_protected                =  _k.isc_tpb_protected
isc_tpb_exclusive                =  _k.isc_tpb_exclusive
isc_tpb_wait                     =  _k.isc_tpb_wait
isc_tpb_nowait                   =  _k.isc_tpb_nowait
isc_tpb_read                     =  _k.isc_tpb_read
isc_tpb_write                    =  _k.isc_tpb_write
isc_tpb_lock_read                =  _k.isc_tpb_lock_read
isc_tpb_lock_write               =  _k.isc_tpb_lock_write
isc_tpb_verb_time                =  _k.isc_tpb_verb_time
isc_tpb_commit_time              =  _k.isc_tpb_commit_time
isc_tpb_ignore_limbo             =  _k.isc_tpb_ignore_limbo
isc_tpb_read_committed           =  _k.isc_tpb_read_committed
isc_tpb_autocommit               =  _k.isc_tpb_autocommit
isc_tpb_rec_version              =  _k.isc_tpb_rec_version
isc_tpb_no_rec_version           =  _k.isc_tpb_no_rec_version
isc_tpb_restart_requests         =  _k.isc_tpb_restart_requests
isc_tpb_no_auto_undo             =  _k.isc_tpb_no_auto_undo

# Default transaction parameter buffer:
default_tpb = (
      # isc_tpb_version3 is a *purely* infrastructural value.  kinterbasdb will
      # gracefully handle user-specified TPBs that don't start with
      # isc_tpb_version3 (as well as those that do start with it).
      _k.isc_tpb_version3

    + isc_tpb_concurrency
    + isc_tpb_shared
    + isc_tpb_wait
    + isc_tpb_write
    + isc_tpb_read_committed
    + isc_tpb_rec_version
  )

# Database information constants:
isc_info_db_id                   =  _k.isc_info_db_id
isc_info_reads                   =  _k.isc_info_reads
isc_info_writes                  =  _k.isc_info_writes
isc_info_fetches                 =  _k.isc_info_fetches
isc_info_marks                   =  _k.isc_info_marks
isc_info_implementation          =  _k.isc_info_implementation
isc_info_version                 =  _k.isc_info_version
isc_info_base_level              =  _k.isc_info_base_level
isc_info_page_size               =  _k.isc_info_page_size
isc_info_num_buffers             =  _k.isc_info_num_buffers
isc_info_limbo                   =  _k.isc_info_limbo
isc_info_current_memory          =  _k.isc_info_current_memory
isc_info_max_memory              =  _k.isc_info_max_memory
isc_info_window_turns            =  _k.isc_info_window_turns
isc_info_license                 =  _k.isc_info_license
isc_info_allocation              =  _k.isc_info_allocation
isc_info_attachment_id           =  _k.isc_info_attachment_id
isc_info_read_seq_count          =  _k.isc_info_read_seq_count
isc_info_read_idx_count          =  _k.isc_info_read_idx_count
isc_info_insert_count            =  _k.isc_info_insert_count
isc_info_update_count            =  _k.isc_info_update_count
isc_info_delete_count            =  _k.isc_info_delete_count
isc_info_backout_count           =  _k.isc_info_backout_count
isc_info_purge_count             =  _k.isc_info_purge_count
isc_info_expunge_count           =  _k.isc_info_expunge_count
isc_info_sweep_interval          =  _k.isc_info_sweep_interval
isc_info_ods_version             =  _k.isc_info_ods_version
isc_info_ods_minor_version       =  _k.isc_info_ods_minor_version
isc_info_no_reserve              =  _k.isc_info_no_reserve
isc_info_logfile                 =  _k.isc_info_logfile
isc_info_cur_logfile_name        =  _k.isc_info_cur_logfile_name
isc_info_cur_log_part_offset     =  _k.isc_info_cur_log_part_offset
isc_info_num_wal_buffers         =  _k.isc_info_num_wal_buffers
isc_info_wal_buffer_size         =  _k.isc_info_wal_buffer_size
isc_info_wal_ckpt_length         =  _k.isc_info_wal_ckpt_length
isc_info_wal_cur_ckpt_interval   =  _k.isc_info_wal_cur_ckpt_interval
isc_info_wal_prv_ckpt_fname      =  _k.isc_info_wal_prv_ckpt_fname
isc_info_wal_prv_ckpt_poffset    =  _k.isc_info_wal_prv_ckpt_poffset
isc_info_wal_recv_ckpt_fname     =  _k.isc_info_wal_recv_ckpt_fname
isc_info_wal_recv_ckpt_poffset   =  _k.isc_info_wal_recv_ckpt_poffset
isc_info_wal_grpc_wait_usecs     =  _k.isc_info_wal_grpc_wait_usecs
isc_info_wal_num_io              =  _k.isc_info_wal_num_io
isc_info_wal_avg_io_size         =  _k.isc_info_wal_avg_io_size
isc_info_wal_num_commits         =  _k.isc_info_wal_num_commits
isc_info_wal_avg_grpc_size       =  _k.isc_info_wal_avg_grpc_size
isc_info_forced_writes           =  _k.isc_info_forced_writes
isc_info_user_names              =  _k.isc_info_user_names
isc_info_page_errors             =  _k.isc_info_page_errors
isc_info_record_errors           =  _k.isc_info_record_errors
isc_info_bpage_errors            =  _k.isc_info_bpage_errors
isc_info_dpage_errors            =  _k.isc_info_dpage_errors
isc_info_ipage_errors            =  _k.isc_info_ipage_errors
isc_info_ppage_errors            =  _k.isc_info_ppage_errors
isc_info_tpage_errors            =  _k.isc_info_tpage_errors
isc_info_set_page_buffers        =  _k.isc_info_set_page_buffers


# Following is a group of constants that should only be imported if the C
# portion of kinterbasdb was compiled against Interbase 6 or later.
if hasattr(_k, 'isc_info_db_sql_dialect'):
    isc_info_db_sql_dialect      =  _k.isc_info_db_sql_dialect
    # Mis-cased version of the above has now been deprecated and is maintained
    # only for compatibility:
    isc_info_db_SQL_dialect      =  _k.isc_info_db_SQL_dialect

    isc_info_db_read_only        =  _k.isc_info_db_read_only
    isc_info_db_size_in_pages    =  _k.isc_info_db_size_in_pages

# Only when compiled against Firebird 1.0 or later:
if hasattr(_k, 'frb_info_att_charset'):
    frb_info_att_charset         =  _k.frb_info_att_charset
    isc_info_db_class            =  _k.isc_info_db_class
    isc_info_firebird_version    =  _k.isc_info_firebird_version
    isc_info_oldest_transaction  =  _k.isc_info_oldest_transaction
    isc_info_oldest_active       =  _k.isc_info_oldest_active
    isc_info_oldest_snapshot     =  _k.isc_info_oldest_snapshot
    isc_info_next_transaction    =  _k.isc_info_next_transaction
    isc_info_db_provider         =  _k.isc_info_db_provider

# Only when compiled against Firebird 1.5 or later:
if hasattr(_k, 'isc_info_active_transactions'):
    isc_info_active_transactions =  _k.isc_info_active_transactions

##########################################
##     PUBLIC CONSTANTS: END            ##
##########################################


###################################################
## DYNAMIC TYPE TRANSLATION CONFIGURATION: BEGIN ##
###################################################
# Added deferred loading of dynamic type converters to facilitate the
# elimination of all dependency on the mx package.  The implementation is quite
# ugly due to backward compatibility constraints.

BASELINE_TYPE_TRANSLATION_FACILITIES = (
    # Date and time translator names:
    'date_conv_in', 'date_conv_out',
    'time_conv_in', 'time_conv_out',
    'timestamp_conv_in', 'timestamp_conv_out',

    # Fixed point translator names:
    'fixed_conv_in_imprecise', 'fixed_conv_in_precise',
    'fixed_conv_out_imprecise', 'fixed_conv_out_precise',

    # Optional unicode converters:
    'OPT:unicode_conv_in', 'OPT:unicode_conv_out',

    # DB API 2.0 standard date and time type constructors:
    'Date', 'Time', 'Timestamp',
    'DateFromTicks', 'TimeFromTicks', 'TimestampFromTicks',
  )

# The next three will be modified by the init function as appropriate:
_MINIMAL_TYPE_TRANS_TYPES = ('DATE', 'TIME', 'TIMESTAMP', 'FIXED',)
_NORMAL_TYPE_TRANS_IN = None
_NORMAL_TYPE_TRANS_OUT = None


_initialized = False
def init(type_conv=1):
    global _initialized, _MINIMAL_TYPE_TRANS_TYPES, \
           _NORMAL_TYPE_TRANS_IN, _NORMAL_TYPE_TRANS_OUT

    if _initialized:
        raise ProgrammingError('Cannot initialize module more than once.')

    globalz = globals()
    if not isinstance(type_conv, types.IntType):
        typeConvModule = type_conv
    else:
        typeConvOptions = {
              0: 'typeconv_naked',
              1: 'typeconv_backcompat', # the default
            100: 'typeconv_23plus',
          }
        chosenTypeConvModuleName = typeConvOptions[type_conv]
        typeConvModule = __import__('kinterbasdb.' + chosenTypeConvModuleName,
            globalz, locals(), (chosenTypeConvModuleName,)
          )
        if type_conv == 100:
            _MINIMAL_TYPE_TRANS_TYPES = _MINIMAL_TYPE_TRANS_TYPES + ('TEXT_UNICODE',)

    for name in BASELINE_TYPE_TRANSLATION_FACILITIES:
        # If the global context already has an entry for the name we're about
        # to load, don't overwrite the object, but hijack its implementation
        # (func_code) and perceived context (func_globals) instead.
        # The fact that the function object is *modifed* rather than replaced
        # is crucial to the preservation of compatibility with the
        # 'from kinterbasdb import *' form of importation.
        if not name.startswith('OPT:'):
            typeConvModuleMember = getattr(typeConvModule, name)
        else:
            # Members whose entries in BASELINE_TYPE_TRANSLATION_FACILITIES
            # begin with 'OPT:' are not required.
            name = name[4:]
            try:
                typeConvModuleMember = getattr(typeConvModule, name)
            except AttributeError:
                continue

        if not globalz.has_key(name):
            globalz[name] = typeConvModuleMember
        else:
            # fakeFunc was originally created by the
            # 'for _requiredDBAPIConstuctorName in ...:  exec ...'
            # loop at the module level.
            fakeFunc = globalz[name]
            realFunc = typeConvModuleMember
            fakeFunc.func_code = realFunc.func_code
            fakeFunc.func_globals.update(realFunc.func_globals)

    # Modify the initial, empty version of the DB API type singleton DATETIME,
    # transforming it into a fully functional version.
    # The fact that the object is *modifed* rather than replaced is crucial to
    # the preservation of compatibility with the 'from kinterbasdb import *'
    # form of importation.
    DATETIME.values = (
        # Date, Time, and Timestamp refer to functions just loaded from the
        # typeConvModule in the loop above.
        type(Date(2003,12,31)),
        type(Time(23,59,59)),
        type(Timestamp(2003,12,31,23,59,59))
      )

    _NORMAL_TYPE_TRANS_IN = {
        'DATE': date_conv_in,
        'TIME': time_conv_in,
        'TIMESTAMP': timestamp_conv_in,
        'FIXED': fixed_conv_in_imprecise,
      }
    _NORMAL_TYPE_TRANS_OUT = {
        'DATE': date_conv_out,
        'TIME': time_conv_out,
        'TIMESTAMP': timestamp_conv_out,
        'FIXED': fixed_conv_out_imprecise,
      }
    if type_conv == 100:
        _NORMAL_TYPE_TRANS_IN['TEXT_UNICODE'] = unicode_conv_in
        _NORMAL_TYPE_TRANS_OUT['TEXT_UNICODE'] = unicode_conv_out

    _initialized = True

def _ensureInitialized():
    if not _initialized:
        init()
    # We now know the module has been initialized; replace this function's
    # implementation with a no-op.
    def noop(): pass
    _ensureInitialized.func_code = noop.func_code

for _requiredDBAPIConstuctorName in (
    'Date', 'Time', 'Timestamp',
    'DateFromTicks', 'TimeFromTicks', 'TimestampFromTicks',
  ):
    # The initialization of type converters (in function init) will replace
    # the dummy implementations created here with versions that needn't check
    # whether the module has been "initialized".
    #
    # Note that only the function *implementations* (func_code) created here
    # will be replaced; the functions objects themselves will not be replaced.
    # This is crucial to the preservation of compatibility with the
    # 'from kinterbasdb import *' form of importation.
    exec '''\
def %s(*args, **kwargs):
    _ensureInitialized()
    return globals()['%s'](*args, **kwargs)
''' % (_requiredDBAPIConstuctorName, _requiredDBAPIConstuctorName)


###################################################
## DYNAMIC TYPE TRANSLATION CONFIGURATION: END   ##
###################################################


############################################
## PUBLIC DB-API TYPE CONSTRUCTORS: BEGIN ##
############################################

# All date/time constructors are loaded dynamically by the init function.

# Changed from buffer to str in 3.1, with the possible addition of a lazy BLOB
# reader at some point in the future:
Binary = str


# DBAPITypeObject implementation is the DB API's suggested implementation.
class DBAPITypeObject:
    def __init__(self, *values):
        self.values = values
    def __cmp__(self, other):
        if other in self.values:
            return 0
        if other < self.values:
            return 1
        else:
            return -1


STRING = DBAPITypeObject(types.StringType, types.UnicodeType)

BINARY = DBAPITypeObject(types.StringType, types.BufferType)

NUMBER = DBAPITypeObject(types.IntType, types.LongType, types.FloatType)

# DATETIME is loaded in a deferred manner (in the init function); this initial
# version remains empty only temporarily.
DATETIME = DBAPITypeObject()

ROWID = DBAPITypeObject()

############################################
## PUBLIC DB-API TYPE CONSTRUCTORS: END   ##
############################################


###################################################################
##     GLOBAL VARIABLES (IN THE TRADITIONAL SENSE): BEGIN        ##
###################################################################

if _EVENT_HANDLING_SUPPORTED:
    # Use this lock to enforce the current one-event-waiting-thread-per-process
    # limitation (which is a limitation in the database client library, not in
    # kinterbasdb):
    if _threads_supported:
        _eventLock = thread.allocate_lock()

###################################################################
##     GLOBAL VARIABLES (IN THE TRADITIONAL SENSE): END          ##
###################################################################


##########################################
##     PUBLIC FUNCTIONS: BEGIN          ##
##########################################

def connect(*args, **keywords_args):
    """
      Minimal arguments: keyword args $dsn, $user, and $password.
      Establishes a kinterbasdb.Connection to a database.  See the docstring
    of kinterbasdb.Connection for details.
    """
    return Connection(*args, **keywords_args)


def create_database(*args):
    """
      Creates a new database with the supplied "CREATE DATABASE" statement.
      Returns an active kinterbasdb.Connection to the newly created database.

    Parameters:
    $sql: string containing the CREATE DATABASE statement.  Note that you may
       need to specify a username and password as part of this statement (see
       the Firebird SQL Reference for syntax).
    $dialect: (optional) the SQL dialect under which to execute the statement
    """
    _ensureInitialized()

    # For a more general-purpose immediate execution facility (the non-"CREATE
    # DATABASE" variant of isc_dsql_execute_immediate, for those who care), see
    # Connection.execute_immediate.

    C_con = _k.create_database(*args)
    return Connection(_ConnectionObject=C_con)


def raw_byte_to_int(raw_byte):
    """
      Convert the byte in the single-character Python string $raw_byte into a
    Python integer.  This function is essentially equivalent to the built-in
    function ord, but is different in intent (see the database_info function).
    """
    _ensureInitialized()

    if len(raw_byte) != 1:
        raise ValueError('raw_byte must be exactly one byte, not %d bytes.' % len(raw_byte))
    return struct.unpack('b', raw_byte)[0]


##########################################
##     PUBLIC FUNCTIONS: END            ##
##########################################


##########################################
##     PUBLIC CLASSES: BEGIN            ##
##########################################

class Connection:
    """
      Represents a connection between the database client (the Python process)
    and the database server.

      The basic behavior of this class is documented by the Python DB API
    Specification 2.0; this docstring covers only some extensions.  Also see
    the KInterbasDB Usage Guide (docs/usage.html).

    Attributes:
    $dialect (read-only):
       The Interbase SQL dialect of the connection.  One of:
         1 for Interbase < 6.0
         2 for "migration mode"
         3 for Interbase >= 6.0 and Firebird (the default)

    $precision_mode (read/write): (DEPRECATED)
         precision_mode is deprecated in favor of dynamic type translation
       (see the [set|get]_type_trans_[in|out] methods, and the Usage Guide).
       ---
         precision_mode 0 (the default) represents database fixed point values
       (NUMERIC/DECIMAL fields) as Python floats, potentially losing precision.
         precision_mode 1 represents database fixed point values as scaled
       Python integers, preserving precision.
         For more information, see the KInterbasDB Usage Guide.

    $server_version (read-only):
         The version string of the database server to which this connection
       is connected.

    $default_tpb (read/write):
         The transaction parameter buffer (TPB) that will be used by default
       for new transactions opened in the context of this connection.
         For more information, see the KInterbasDB Usage Guide.
    """

    def __init__(self, *args, **keywords_args):
        # self._C_con is the instance of ConnectionType that represents this
        # connection in the underlying C module _k.

        _ensureInitialized()

        # Optional DB API Extension: Make the module's exception classes
        # available as connection attributes to ease cross-module portability:
        for exc_class in _ALL_EXCEPTION_CLASSES:
            setattr(self, exc_class.__name__, exc_class)

        # Inherit the module-level default TPB.
        self.default_tpb = default_tpb

        # Allow other code WITHIN THIS MODULE to obtain an instance of
        # ConnectionType some other way and provide it to us instead of us
        # creating one via attach_db.  (The create_database function uses this
        # facility, for example.)
        if keywords_args.has_key('_ConnectionObject'):
            self._C_con = keywords_args['_ConnectionObject']
        else:
            n_nonkeyword = len(args)
            n_keyword = len(keywords_args)

            if n_nonkeyword == 0 and n_keyword == 0:
                raise ProgrammingError(
                    'connect() requires at least 3 keyword arguments.'
                  )
            elif n_keyword > 0 and n_nonkeyword == 0:
                source_dict = keywords_args # The typical case.
            else:
                # This case is for backward compatibility ONLY:
                warnings.warn('The non-keyword-argument form of the connect()'
                    ' function is deprecated.  Use'
                    ' connect(dsn=..., user=..., password=...) rather than'
                    ' connect(..., ..., ...)',
                    DeprecationWarning
                  )
                if n_keyword > 0:
                    raise ProgrammingError('Do not specify both non-keyword'
                        ' args and keyword args (keyword-only is preferred).'
                      )
                elif n_nonkeyword != 3:
                    raise ProgrammingError('If using non-keyword args, must'
                        ' provide exactly 3: dsn, user, password.'
                      )
                else:
                    # Transform the argument tuple into an argument dict.
                    source_dict = {'dsn': args[0], 'user': args[1], 'password': args[2]}

            # Pre-render the requisite buffers (plus the dialect), then send
            # them down to the C level.  _k.attach_db() will give us a C-level
            # connection structure (self._C_con, of type ConnectionType) in
            # return.  self will then spend the rest of its insignificant life
            # serving as a proxy for _C_con.
            (dsn, dpb, dialect) = self._build_connect_structures(**source_dict)
            self._C_con = _k.attach_db(dsn, dpb, dialect)

        self._normalize_type_trans()
        # 2003.03.30: Moved precision_mode up to the Python level (it's deprecated).
        self._precision_mode = 0

        # 2003.10.06:
        # This list will contain weak references to cursors created on this
        # connection.  When this connection is close()d explicitly by the client
        # programmer or garbage collected without having been explicitly
        # close()d, it will ask its remaining cursors to close() themselves
        # before the attachment to the database is severed, in order to avoid a
        # situation in which the cursors need to call isc_dsql_free_statement
        # but no longer have the necessary context, which is provided by their
        # connection.
        self._cursors = []


    def _build_connect_structures(self,
        dsn=None, user=None, password=None, host=None, database=None,
        role=None, charset=None, dialect=0
      ):
        # Build <<DSN>>:begin:
        if (   (not dsn and not host and not database)
            or (dsn and (host or database))
            or (host and not database)
          ):
            raise ProgrammingError(
                "Must supply one of:\n"
                " 1. keyword argument dsn='host:/path/to/database'\n"
                " 2. both keyword arguments host='host' and database='/path/to/database'\n"
                " 3. only keyword argument database='/path/to/database'"
              )

        if not dsn:
            if host and host.endswith(':'):
                raise ProgrammingError('Host must not end with a colon.'
                    ' You should specify host="%s" rather than host="%s".'
                    % (host[:-1], host)
                  )
            elif host:
                dsn = '%s:%s' % (host, database)
            else:
                dsn = database

        assert dsn, 'Internal error in _build_connect_structures DSN preparation.'
        # Build <<DSN>>:end

        # Build <<DPB>>:begin:
        # Build the database parameter buffer.  $dpb is a list of raw strings
        # that will be rolled up into a single raw string and passed,
        # ultimately, to the C function isc_attach_database as the 'dpb'
        # argument.

        # Start with requisite DPB boilerplate, a single byte that informs the
        # database API what version of DPB it's dealing with:
        dpb = [ struct.pack('c', _k.isc_dpb_version1) ]

        def add_str(code_as_byte, s):
            # Append a string parameter to the end of the DPB.  A string
            # parameter is represented in the DPB by the following binary
            # sequence:
            #  - a byte code telling the purpose of the upcoming string
            #  - a byte telling the length of the upcoming string
            #  - the string itself
            # See IB 6 API guide page 44 for documentation of WTF is going on here.
            s_len = len(s)
            if s_len >= 256:
                # Because the length is denoted in the DPB by a single byte.
                raise ProgrammingError('Individual component of database'
                    ' parameter buffer is too large.  Components must be less'
                    ' than 256 bytes.'
                  )
            format = 'cc%ds' % s_len # like 'cc50s' for a 50-byte string
            dpb.append( struct.pack(format, code_as_byte, chr(s_len), s) )

        if user:
            add_str(_k.isc_dpb_user_name, user)
        if password:
            add_str(_k.isc_dpb_password, password)
        if role:
            add_str(_k.isc_dpb_sql_role_name, role)

        self.charset = (charset and charset) or None
        if charset:
            add_str(_k.isc_dpb_lc_ctype, charset)

        # Roll dpb up into a single raw string (That's "buffer" to you, sonny.)
        dpb = ''.join(dpb)
        # Build <<DPB>>:end

        # Leave dialect alone; the C code will validate it.
        return (dsn, dpb, dialect)


    def __del__(self):
        # This method should not call close().
        self._forcibly_close_cursors()
        self._close_physical_connection(raiseExceptionOnError=False)


    def drop_database(self):
        """
          Drops the database to which this connection is attached.

          Unlike plain file deletion, this method behaves responsibly, in that
        it removes shadow files and other ancillary files for this database.
        """
        self._ensure_group_membership(False, "Cannot drop database via"
            " connection that is part of a ConnectionGroup."
          )
        _k.drop_database(self._C_con)


    def begin(self, tpb=None):
        """
          Starts a transaction explicitly.  This is never *required*; a
        transaction will be started implicitly if necessary.

        Parameters:
        $tpb: Optional transaction parameter buffer (TPB) populated with
            kinterbasdb.isc_tpb_* constants.  See the Interbase API guide for
            these constants' meanings.
        """
        if self.group is not None:
            self.group.begin()
            return

        if tpb is None:
            _k.begin(self._C_con, self.default_tpb)
        else:
            tpb = _validateTPB(tpb) # 2004.04.19
            _k.begin(self._C_con, tpb)


    def prepare(self):
        """
          Manually triggers the first phase of a two-phase commit (2PC).  Use
        of this method is optional; if preparation is not triggered manually,
        it will be performed implicitly by commit() in a 2PC.
          See also the method ConnectionGroup.prepare.
        """
        if self.group is not None:
            self.group.prepare()
            return

        _k.prepare(self._C_con)


    def commit(self, retaining=False):
        """
          Commits (permanently applies the actions that have taken place as
        part of) the active transaction.

        Parameters:
          $retaining (optional boolean that defaults to False):
              If True, the transaction is immediately cloned after it has been
            committed.  This retains system resources associated with the
            transaction and leaves undisturbed the state of any cursors open on
            this connection.  In effect, retaining commit keeps the transaction
            "open" across commits.
              See IB 6 API Guide pages 75 and 291 for more info.
        """
        if self.group is not None:
            self.group.commit(retaining=retaining)
            return

        _k.commit(self._C_con, retaining)


    def savepoint(self, name):
        """
          Establishes a SAVEPOINT named $name.
          To rollback to this SAVEPOINT, use rollback(savepoint=name).

          Example:
            con.savepoint('BEGINNING_OF_SOME_SUBTASK')
            ...
            con.rollback(savepoint='BEGINNING_OF_SOME_SUBTASK')
        """
        self.execute_immediate('SAVEPOINT ' + name)


    def rollback(self, retaining=False, savepoint=None):
        """
          Rolls back (cancels the actions that have taken place as part of) the
        active transaction.

        Parameters:
          $retaining (optional boolean that defaults to False):
              If True, the transaction is immediately cloned after it has been
            rolled back.  This retains system resources associated with the
            transaction and leaves undisturbed the state of any cursors open on
            this connection.  In effect, retaining rollback keeps the
            transaction "open" across rollbacks.
              See IB 6 API Guide pages 75 and 373 for more info.
          $savepoint (string name of the SAVEPOINT):
              If a savepoint name is supplied, only rolls back as far as that
            savepoint, rather than rolling back the entire transaction.
        """
        if savepoint is None:
            if self.group is not None:
                self.group.rollback(retaining=retaining)
                return

            _k.rollback(self._C_con, retaining)
        else:
            self.execute_immediate('ROLLBACK TO ' + savepoint)


    def execute_immediate(self, sql):
        """
          Executes a statement without caching its prepared form.  The statement
        must NOT be of a type that returns a result set.

          In most cases (especially cases in which the same statement--perhaps
        a parameterized statement--is executed repeatedly), it is better to
        create a cursor using the connection's cursor() method, then execute
        the statement using one of the cursor's execute methods.
        """
        self._ensure_transaction()

        _k.execute_immediate(self._C_con, sql)


    def database_info(self, request, result_type):
        """
          Wraps the Interbase C API function isc_database_info.

          For documentation, see the IB 6 API Guide section entitled
        "Requesting information about an attachment" (p. 51).

          Note that this method is a VERY THIN wrapper around the IB C API
        function isc_database_info.  This method does NOT attempt to interpret
        its results except with regard to whether they are a string or an
        integer.

          For example, requesting isc_info_user_names will return a string
        containing a raw succession of length-name pairs.  A thicker wrapper
        might interpret those raw results and return a Python tuple, but it
        would need to handle a multitude of special cases in order to cover
        all possible isc_info_* items.

          Note:  Some of the information available through this method would be
        more easily retrieved with the Services API (see submodule
        kinterbasdb.services).

        Parameters:
        $result_type must be either:
           's' if you expect a string result, or
           'i' if you expect an integer result
        """
        # Note:  Server-side implementation for most of isc_database_info is in
        # jrd/inf.cpp.
        res = _k.database_info(self._C_con, request, result_type)

        # 2004.12.12:
        # The result buffers for a few request codes don't follow the generic
        # conventions, so we need to return their full contents rather than
        # omitting the initial infrastructural bytes.
        if result_type == 's' and request not in _DATABASE_INFO__KNOWN_LOW_LEVEL_EXCEPTIONS:
            res = res[3:]

        return res


    def cursor(self):
        """
          Creates new cursor that operates within the context of this connection.
        """
        cur = Cursor(self)
        self._cursors.append( weakref.ref(cur) )
        return cur


    def close(self):
        "Closes the connection to the database server."
        self._ensure_group_membership(False, "Cannot close a connection that"
            " is a member of a ConnectionGroup."
          )
        self._forcibly_close_cursors()
        self._close_physical_connection(raiseExceptionOnError=True)

    def _forcibly_close_cursors(self):
        # For an explanation of this method's purpose, see the comment in the
        # constructor regarding self._cursors.
        if hasattr(self, '_cursors'):
            for cur_weakref in self._cursors:
                cur = cur_weakref()
                if cur is not None and _k and _k.is_purportedly_open(cur._C_cursor):
                    cur.close()
            del self._cursors

    def _close_physical_connection(self, raiseExceptionOnError=True):
        # Sever the physical connection to the database server and replace our
        # underyling _kinterbasdb.ConnectionType object with a null instance
        # of that type, so that post-close() method calls on this connection
        # will raise ProgrammingErrors, as required by the DB API Spec.
        if hasattr(self, '_C_con'):
            if _k and _k.is_purportedly_open(self._C_con):
                _k.close_connection(self._C_con)
                self._C_con = _k.null_connection
            elif raiseExceptionOnError:
                raise ProgrammingError('Connection is already closed.')


    def _has_db_handle(self):
        return self._C_con != _k.null_connection


    def _has_transaction(self):
        # Does this connection currently have an active transaction (including
        # a distributed transaction)?
        return _k.has_transaction(self._C_con)

    def _ensure_transaction(self):
        if self._has_transaction():
            return
        if self.group is None:
            self.begin()
        else:
            self.group.begin()


    def _normalize_type_trans(self):
        # Set the type translation dictionaries to their "normal" form--the
        # minumum required for standard kinterbasdb operation.
        self.set_type_trans_in(_NORMAL_TYPE_TRANS_IN)
        self.set_type_trans_out(_NORMAL_TYPE_TRANS_OUT)

    def _enforce_min_trans(self, trans_dict, translator_source):
        #   Any $trans_dict that the Python programmer supplies for a Connection
        # must have entries for at least the types listed in
        # _MINIMAL_TYPE_TRANS_TYPES, because kinterbasdb uses dynamic type
        # translation even if it is not explicitly configured by the Python
        # client programmer.
        #   The Cursor.set_type_trans* methods need not impose the same
        # requirement, because "translator resolution" will bubble upward from
        # the cursor to its connection.
        #   This method inserts the required translators into the incoming
        # $trans_dict if that $trans_dict does not already contain them.
        # Note that $translator_source will differ between in/out translators.
        for type_name in _MINIMAL_TYPE_TRANS_TYPES:
            if not trans_dict.has_key(type_name):
                trans_dict[type_name] = translator_source[type_name]

    def set_type_trans_out(self, trans_dict):
        """
          Changes the outbound type translation map.
          For more information, see the "Dynamic Type Translation" section of
        the KInterbasDB Usage Guide.
        """
        _trans_require_dict(trans_dict)
        self._enforce_min_trans(trans_dict, _NORMAL_TYPE_TRANS_OUT)
        trans_return_types = _make_output_translator_return_type_dict_from_trans_dict(trans_dict)
        return _k.set_con_type_trans_out(self._C_con, trans_dict, trans_return_types)

    def get_type_trans_out(self):
        """
          Retrieves the outbound type translation map.
          For more information, see the "Dynamic Type Translation" section of
        the KInterbasDB Usage Guide.
        """
        return _k.get_con_type_trans_out(self._C_con)

    def set_type_trans_in(self, trans_dict):
        """
          Changes the inbound type translation map.
          For more information, see the "Dynamic Type Translation" section of
        the KInterbasDB Usage Guide.
        """
        _trans_require_dict(trans_dict)
        self._enforce_min_trans(trans_dict, _NORMAL_TYPE_TRANS_IN)
        return _k.set_con_type_trans_in(self._C_con, trans_dict)

    def get_type_trans_in(self):
        """
          Retrieves the inbound type translation map.
          For more information, see the "Dynamic Type Translation" section of
        the KInterbasDB Usage Guide.
        """
        return _k.get_con_type_trans_in(self._C_con)


    # Exclude event handling methods if support for them is not compiled into
    # the underlying C module:
    if _EVENT_HANDLING_SUPPORTED:
        def event_conduit(self, event_names):
            if not _threads_supported:
                raise NotSupportedError("This Python installation is not"
                    " compiled with thread support, so kinterbasdb's event"
                    " support is unavailable."
                  )

            if self._C_con is _k.null_connection:
                raise ProgrammingError("Cannot open event conduit on closed connection.")

            # Only one event-waiting-thread per process is supported by the DB
            # client library; kinterbasdb reflects this.
            #   Try to acquire the single thread lock that serializes all
            # EventConduits.  If that acquisition attempt is not *immediately*
            # successful, it must be because there's already an active
            # EventConduit.
            if _eventLock.acquire(0) == 0:
                raise NotSupportedError("This version of kinterbasdb does not"
                    " support listening for events with more than one"
                    " EventConduit per process.  Within this process, there is"
                    " already an active EventConduit; you must close() it"
                    " before creating a new one."
                  )

            try:
                if hasattr(self, '_hasActiveConduit'):
                    if self._hasActiveConduit:
                        raise ProgrammingError("Only one EventConduit can be"
                            " allocated per Connection; one is already"
                            " allocated for this connection.  Use the"
                            " EventConduit.close() method to release the old"
                            " conduit before allocating another."
                          )

                conduit = EventConduit(event_names, self)
                self._hasActiveConduit = True

                return conduit
            except:
                # Notice that in the non-exceptional case, the _eventLock is
                # *not* released until the Connection._event_conduit_released()
                # method is called by the active EventConduit as it "dies".
                _eventLock.release()
                raise

        def _event_conduit_released(self, conduit):
            # The event conduit associated with this connection will call this
            # method when it ceases to be active.
            self._hasActiveConduit = False
            _eventLock.release()


    def __getattr__(self, attr):
        if attr == "dialect":
            return _k.get_dialect(self._C_con)
        elif attr == "precision_mode":
            # 2003.04.02: postpone this warning until a later version:
            #warnings.warn(
            #    'precision_mode is deprecated in favor of dynamic type'
            #    ' translation (see the [set|get]_type_trans_[in|out] methods).',
            #    DeprecationWarning
            #  )
            return self._precision_mode
        elif attr == "server_version":
            rawVersion = self.database_info(isc_info_version, 's')
            # As defined by the IB 6 API Guide, the first byte is the constant
            # 1; the second byte contains the size of the server_version string
            # in bytes.
            return rawVersion[2:2 + raw_byte_to_int(rawVersion[1])]
        elif attr == "group":
            return _k.get_group(self._C_con)
        else:
            try:
                return self.__dict__[attr]
            except KeyError:
                raise AttributeError(
                    "Connection instance has no attribute '%s'" % attr
                  )


    def __setattr__(self, attr, value):
        if attr == "dialect":
            _k.set_dialect(self._C_con, value)
        elif attr == "precision_mode":
            # 2003.04.02: postpone this warning until a later version:
            #warnings.warn(
            #    'precision_mode is deprecated in favor of dynamic type'
            #    ' translation (see the [set|get]_type_trans_[in|out] methods).',
            #    DeprecationWarning
            #  )
            if value not in (0,1):
                raise ValueError('precision_mode must be 0 or 1')

            # Preserve the previous DTT settings to the greatest extent possible
            # (although dynamic type translation and the precision_mode
            # attribute really aren't meant to be used together).
            trans_in = self.get_type_trans_in()
            trans_out = self.get_type_trans_out()

            if value == 0: # imprecise:
                trans_in['FIXED']  = fixed_conv_in_imprecise
                trans_out['FIXED'] = fixed_conv_out_imprecise
            else: # precise:
                trans_in['FIXED']  = fixed_conv_in_precise
                trans_out['FIXED'] = fixed_conv_out_precise
            self.set_type_trans_in(trans_in)
            self.set_type_trans_out(trans_out)

            self._precision_mode = value
        elif attr == "server_version":
            raise AttributeError("server_version is a read-only attribute")
        elif attr == "group":
            raise AttributeError("group is a read-only attribute")
        elif attr == "charset":
            # Allow the "charset" attribute to be set the first time (by the
            # constructor), but never again.
            if hasattr(self, "charset"):
                raise AttributeError("charset is a read-only attribute")
            else:
                self.__dict__[attr] = value
        elif attr == "default_tpb": # 2004.04.19
            self.__dict__["default_tpb"] = _validateTPB(value)
        else:
            self.__dict__[attr] = value


    def _set_group(self, group):
        # This package-private method allows ConnectionGroup's membership
        # management functionality to bypass the conceptually read-only nature
        # of the Connection.group property.
        if group is not None:
            assert _k.get_group(self._C_con) is None
        # Unless the group is being cleared (set to None), pass a *WEAK*
        # reference down to the C level (otherwise, even the cyclic garbage
        # collector can't collect ConnectionGroups or their Connections because
        # the Connections' references are held at the C level, not the Python
        # level).
        if group is None:
            _k.set_group(self._C_con, None)
        else:
            _k.set_group(self._C_con, weakref.proxy(group))


    def _ensure_group_membership(self, must_be_member, err_msg):
        if must_be_member:
            if self.group is None:
                raise ProgrammingError(err_msg)
        else:
            if not hasattr(self, 'group'):
                return
            if self.group is not None:
                raise ProgrammingError(err_msg)



class ConnectionGroup: # Added 2003.04.27 to support distributed transactions.
    # XXX: Discuss the (lack of) threadsafety of ConnectionGroup in the docs.

    # XXX: Adding two connections to the same database freezes the DB client
    # library.  However, I've no way to detect with certainty whether any given
    # con1 and con2 are connected to the same database, what with database
    # aliases, IP host name aliases, remote-vs-local protocols, etc.
    # Therefore, a warning must be added to the docs.

    def __init__(self, connections=()):
        _ensureInitialized()

        self._cons = []
        self._trans_handle = None

        for con in connections:
            self.add(con)


    def __del__(self):
        self.disband()


    def disband(self):
        # Notice that the ConnectionGroup rollback()s itself BEFORE releasing
        # its Connection references.
        if getattr(self, '_trans_handle', None) is not None:
            self.rollback()
        if hasattr(self, '_cons'):
            self.clear()


    # Membership methods:
    def add(self, con):
        ### CONTRAINTS ON $con: ###
        # con must be an instance of kinterbasdb.Connection:
        if not isinstance(con, Connection):
            raise TypeError('con must be an instance of kinterbasdb.Connection')
        # con cannot already be a member of this group:
        if con in self:
            raise ProgrammingError('con is already a member of this group.')
        # con cannot belong to more than one group at a time:
        if con.group:
            raise ProgrammingError('con is already a member of another group;'
                ' it cannot belong to more than one group at once.'
              )
        # con cannot be added if it has an active transaction:
        if con._has_transaction():
            raise ProgrammingError('con already has an active transaction;'
                ' that must be resolved before con can join this group.'
              )
        # con must be connected to a database; it must not have been closed.
        if not con._has_db_handle():
            raise ProgrammingError('con has been closed; it cannot join a group.')

        ### CONTRAINTS ON $self: ###
        # self cannot accept new members while self has an unresolved transaction:
        self._require_transaction_state(False,
            'Cannot add connection to group that has an unresolved transaction.'
          )
        # self cannot have more than _k.DIST_TRANS_MAX_DATABASES members:
        if self.count() > _k.DIST_TRANS_MAX_DATABASES - 1:
            raise ProgrammingError('The database engine limits the number of'
                ' database handles that can participate in a single distributed'
                ' transaction to %d or fewer; this group already has %d'
                ' members.'
                % (_k.DIST_TRANS_MAX_DATABASES, self.count())
              )

        ### CONTRAINTS FINISHED ###

        # Can't set con.group directly (read-only); must use package-private method.
        con._set_group(self)
        self._cons.append(con)


    def remove(self, con):
        if con not in self:
            raise ProgrammingError('con is not a member of this group.')
        # The following assertion was invalidated by the introduction of weak refs:
        #assert con.group is self
        self._require_transaction_state(False,
            'Cannot remove connection from group that has an unresolved transaction.'
          )

        con._set_group(None)
        self._cons.remove(con)


    def clear(self):
        self._require_transaction_state(False,
            'Cannot clear group that has an unresolved transaction.'
          )
        for con in self.members():
            self.remove(con)
        assert self.count() == 0


    def members(self):
        return self._cons[:] # return a *copy* of the internal list


    def count(self):
        return len(self._cons)


    def contains(self, con):
        return con in self._cons
    __contains__ = contains # alias to support the 'in' operator


    def __iter__(self):
        return iter(self._cons)


    # Transactional methods:
    def _require_transaction_state(self, must_be_active, err_msg=''):
        trans_handle = self._trans_handle
        if (
               (must_be_active and trans_handle is None)
            or (not must_be_active and trans_handle is not None)
          ):
            raise ProgrammingError(err_msg)


    def _require_non_empty_group(self, operation_name):
        if self.count() == 0:
            raise ProgrammingError('Cannot %s distributed transaction with'
                ' an empty ConnectionGroup.' % operation_name
              )


    def begin(self):
        self._require_transaction_state(False,
            'Must resolve current transaction before starting another.'
          )
        self._require_non_empty_group('start')
        self._trans_handle = _k.distributed_begin(self._cons)


    def prepare(self):
        """
          Manually triggers the first phase of a two-phase commit (2PC).  Use
        of this method is optional; if preparation is not triggered manually,
        it will be performed implicitly by commit() in a 2PC.
        """
        self._require_non_empty_group('prepare')
        self._require_transaction_state(True,
            'This group has no transaction to prepare.'
          )

        _k.distributed_prepare(self._trans_handle)


    def commit(self, retaining=False):
        self._require_non_empty_group('commit')
        # The consensus among Python DB API experts is that transactions should
        # always be started implicitly, even if that means allowing a commit()
        # or rollback() without an actual transaction.
        if self._trans_handle is None:
            return

        _k.distributed_commit(self._trans_handle, retaining)
        self._trans_handle = None


    def rollback(self, retaining=False):
        self._require_non_empty_group('roll back')
        # The consensus among Python DB API experts is that transactions should
        # always be started implicitly, even if that means allowing a commit()
        # or rollback() without an actual transaction.
        if self._trans_handle is None:
            return

        _k.distributed_rollback(self._trans_handle, retaining)
        self._trans_handle = None


# Exclude EventConduit if support for it is not compiled into the underlying C
# library:
if _EVENT_HANDLING_SUPPORTED:
    class EventConduit:
        def __init__(self, event_names, connection):
            """
              Parameters:
              $event_names: a sequence of event names (strings) for which this
                conduit will wait when the wait() method is called.
              $connection: the kinterbasdb.Connection with which this conduit is
                to be associated.
            """
            _ensureInitialized()

            if isinstance(event_names, types.StringType):
                raise ProgrammingError("event_names must be a sequence of"
                    " strings, but not a string itself."
                  )

            if len(event_names) == 0:
                raise ProgrammingError("Can't wait for zero events.")

            if len(event_names) > _k.MAX_EVENT_NAMES:
                raise ProgrammingError("The database engine is limited to"
                    " waiting for %d or fewer events at a time."
                    % _k.MAX_EVENT_NAMES
                  )

            if 0 != len([n for n in event_names if not isinstance(n, types.StringType)]):
                raise ProgrammingError("All event names must be strings.")

            self._con = connection
            self._C_conduit = _k.event_conduit_new(
                event_names, connection._C_con
              )


        def __del__(self):
            self.close()


        def wait(self, timeout=0.0):
            """
              Waits for the occurrence of one or more of the events whose names
            were supplied in constructor parameter $event_names.

            Parameters:
              $timeout is a float indicating the number of seconds to wait
            before timing out, or 0.0 (the default) to wait infinitely.

            Returns:
              A dictionary that maps (event name -> occurence count), or None
            if the wait timed out.
            """
            self._requireValidState()
            return _k.event_conduit_wait(self._C_conduit, timeout)


        def flush(self):
            """
              After the first wait() call, event notifications continue to
            accumulate asynchronously within the conduit until the conduit is
            close()d, regardless of whether the Python programmer continues to
            call wait() to receive those notifications.
              This method allows the Python programmer to manually clear any
            event notifications that have queued up since the last wait() call.

            Returns:
              The number of event notifications that were flushed from the queue.
            """
            self._requireValidState()
            return _k.event_conduit_flush_queue(self._C_conduit)


        def close(self):
            """
              Cancels the request for this conduit to be informed of events,
            clearing the way for another event conduit to register to be
            informed of events (via the Connection.event_conduit() method).
              After this method has been called, this EventConduit object
            is useless, and should be discarded.
            """
            try:
                # Must not assume that self._C_conduit is present, because the
                # event_conduit_new call in the constructor may have failed:
                if hasattr(self, '_C_conduit'):
                    _k.event_conduit_cancel(self._C_conduit)
                    del self._C_conduit
            finally:
                # Inform the Connection with which this Conduit is associated that
                # this Conduit is no longer "active".
                if hasattr(self, '_con'):
                    self._con._event_conduit_released(self)
                    del self._con


        def _requireValidState(self):
            if not hasattr(self, '_C_conduit'):
                raise ProgrammingError("This EventConduit has been close()d;"
                    " it can no longer be used."
                  )
            if not hasattr(self, '_con') or self._con._C_con is _k.null_connection:
                raise ProgrammingError("The Connection associated with this"
                    " EventConduit has been closed; this conduit can no longer"
                    " be used."
                  )


class Cursor:
    """
      Represents a database cursor that operates within the context of a Connection.

      Cursors are typically used to send SQL statements to the database (via one
    of the 'execute*' methods) and to retrieve the results of those statements
    (via one of the 'fetch*' methods).

      The behavior of this class is further documented by the Python DB API
    Specification 2.0.

    Attribute and method notes:
    $description:
      kinterbasdb makes ABSOLUTELY NO GUARANTEES about the description attribute
    of a cursor except those required by the Python Database API Specification
    2.0 (that is, description is either None or a sequence of 7-item sequences).
      Therefore, client programmers should NOT rely on description being an
    instance of a particular class or type.

    $rowcount:
      The rowcount attribute is defined only in order to conform to the Python
    Database API Specification 2.0.
      The value of the rowcount attribute is initially -1, and it never changes,
    because the Interbase/Firebird C API does not support the determination of
    the number of rows affected by an executed statement.

    $fetch* methods:
      kinterbasdb makes ABSOLUTELY NO GUARANTEES about the return value of the
    fetch(one|many|all) methods except that it is a sequence indexed by field
    position, and no guarantees about the return value of the
    fetch(one|many|all)map methods except that it is a mapping of field name
    to field value.
      Therefore, client programmers should NOT rely on the return value being
    an instance of a particular class or type.

    $arraysize:
      The arraysize attribute is defined only in order to conform to the Python
    Database API Specification 2.0.
      The Interbase/Firebird C API does not provide a facility for bulk fetch,
    so the value of the arraysize attribute does not affect perfomance at all.
    The Python DB API specification still requires that arraysize be present,
    and that the fetchmany() method take its value into account if fetchmany()'s
    optional $size parameter is not specified.
    """

    def __init__(self, _con):
        _ensureInitialized()

        # The instance of Python class Connection that represents the database
        # connection within the context of which this cursor operates:
        self._con = weakref.proxy(_con) # 2003.10.27: Switched to weak ref.

        # The instance of C type CursorType that represents this cursor in _k:
        self._C_cursor = _k.cursor(self._con._C_con)

        # cursor attributes required by the Python DB API 2.0:
        self.description = None

        self.arraysize = 1


    def __getattr__(self, attr):
        # The read-only 'connection' attribute is one of the "Optional DB API
        # Extensions" documented in PEP-249.
        if attr == 'connection':
            return self._con
        elif attr == 'name':
            return _k.get_cursor_name(self._C_cursor)
        elif attr == 'rowcount':
            return _k.get_rowcount(self._C_cursor)
        else:
            try:
                return self.__dict__[attr]
            except KeyError:
                raise AttributeError(
                    "Cursor instance has no attribute '%s'" % attr
                  )


    def __setattr__(self, attr, value):
        # The read-only 'connection' attribute is one of the "Optional DB API
        # Extensions" documented in PEP-249.
        if attr == 'connection':
            raise AttributeError("connection is a read-only attribute")
        elif attr == 'name':
            _k.set_cursor_name(self._C_cursor, value)
        elif attr == 'rowcount':
            raise AttributeError("rowcount is a read-only attribute")
        else:
            self.__dict__[attr] = value


    def __iter__(self):
        "The default iterator returns sequences, not mappings."
        return self.iter()


    def iter(self):
        return iter(self.fetchone, None)


    def itermap(self):
        """
          Returns an iterator of (field name -> field value) mappings for the
        remaining rows available from this cursor.
        """
        return iter(self.fetchonemap, None)


    def setinputsizes(self, sizes):
        """
          Defined for compatibility with the DB API specification, but currently
        does nothing.
        """
        pass


    def setoutputsize(self, size, column=None):
        """
          Defined for compatibility with the DB API specification, but currently
        does nothing.
        """
        pass


    def execute(self, sql, params=()):
        """
          The behavior of this method is explained by the Python DB API
        Specification 2.0.
        """
        self._ensure_transaction()

        # If a non-virtual rowcount has been set (an attribute that'll take
        # precedence over the __getattr__-based rowcount), delete it before
        # executing another statement.
        # For an explanation of this behavior, see comments in the executemany
        # method.
        if self.__dict__.has_key('rowcount'):
            del self.rowcount

        self.description = _k.execute(self._C_cursor, sql, params)
        # Note that this method does not return anything; use the fetch* methods
        # to retrieve the results of the just-executed SQL statement.


    def executemany(self, sql, manySetsOfParameters):
        """
          The behavior of this method is explained by the Python DB API
        Specification 2.0.
        """
        self._ensure_transaction()

        totalRowcount = 0
        for setOfParameters in manySetsOfParameters:
            self.description = _k.execute(self._C_cursor, sql, setOfParameters)
            totalRowcount += self.rowcount

        # In order to force cur.rowcount to return the total rowcount of the
        # executemany call rather than the rowcount of only the last execute
        # call, store the total rowcount as an attribute that'll take precedence
        # over the __getattr__-based rowcount.
        # Any new execute call will delete this non-virtual rowcount figure.
        self.__dict__['rowcount'] = totalRowcount


    def _ensure_transaction(self):
        # Ensure that the connection associated with this cursor has an active
        # transaction.
        self._con._ensure_transaction()


    def set_type_trans_out(self, trans_dict):
        _trans_require_dict(trans_dict)
        trans_return_types = _make_output_translator_return_type_dict_from_trans_dict(trans_dict)
        return _k.set_cur_type_trans_out(self._C_cursor, trans_dict, trans_return_types)

    def get_type_trans_out(self):
        return _k.get_cur_type_trans_out(self._C_cursor)

    def set_type_trans_in(self, trans_dict):
        _trans_require_dict(trans_dict)
        return _k.set_cur_type_trans_in(self._C_cursor, trans_dict)

    def get_type_trans_in(self):
        return _k.get_cur_type_trans_in(self._C_cursor)


    # The next two methods are used by the other fetch methods to retrieve an
    # individual row as either a sequence (_fetch) or a mapping (_fetchmap).
    def _fetch(self):
        row = _k.fetch(self._C_cursor)
        return row or None

    def _fetchmap(self):
        row = self._fetch()
        if not row:
            return None
        return _RowMapping(self.description, row)


    # Generic fetch(one|many|all) methods parameterized by fetchMethod so that
    # their logical structure can be reused for both conventional sequence
    # fetch and mapping fetch:
    def _fetchone(self, fetchMethod):
        return fetchMethod()


    def _fetchmany(self, size, fetchMethod):
        if size is None:
            size = self.arraysize
        elif size <= 0:
            raise ProgrammingError("The size parameter of the fetchmany or"
                " fetchmanymap method (which specifies the number of rows to"
                " fetch) must be greater than zero.  It is an optional"
                " parameter, so it can be left unspecifed, in which case it"
                " will default to the value of the cursor's arraysize"
                " attribute."
              )

        manyRows = []
        i = 0
        while i < size:
            row = fetchMethod()
            if row is None:
                break
            manyRows.append(row)
            i += 1

        return manyRows


    def _fetchall(self, fetchMethod):
        allRows = []
        while True:
            row = fetchMethod()
            if row is None:
                break
            allRows.append(row)

        return allRows


    # The public fetch methods:
    def fetchone(self):
        """
          The behavior of this method is explained by the Python DB API
        Specification 2.0.
        """
        return self._fetchone(self._fetch)


    def fetchonemap(self):
        """
          This method is just like fetchone, except that it returns a mapping
        of field name to field value, rather than a sequence.
        """
        return self._fetchone(self._fetchmap)


    def fetchmany(self, size=None):
        """
          The behavior of this method is explained by the Python DB API
        Specification 2.0.
        """
        return self._fetchmany(size, self._fetch)


    def fetchmanymap(self, size=None):
        """
          This method is just like fetchmany, except that it returns a sequence
        of mappings of field name to field value, rather than a sequence of
        sequences.
        """
        return self._fetchmany(size, self._fetchmap)


    def fetchall(self):
        """
          The behavior of this method is explained by the Python DB API
        Specification 2.0.
        """
        return self._fetchall(self._fetch)


    def fetchallmap(self):
        """
          This method is just like fetchall, except that it returns a sequence
        of mappings of field name to field value, rather than a sequence of
        sequences.
        """
        return self._fetchall(self._fetchmap)


    def close(self):
        """
          The behavior of this method is explained by the Python DB API
        Specification 2.0.
        """
        _k.close_cursor(self._C_cursor)


    def callproc(self, procname, params=()):
        """
          The behavior of this method is explained by the Python DB API
        Specification 2.0.
        """
        sql = 'EXECUTE PROCEDURE %s ' % procname
        if params:
            # Add a series of N comma-delimited question marks, where
            # N = len(params).
            sql += ','.join( ('?',) * len(params) )

        self.execute(sql, params)

        # The database engine doesn't support input/output parameters or
        # in-place memory-modified output parameters (it's like Python in this
        # regard), so return the input parameter sequence unmodified.
        # With this database engine, it's kind of silly to return anything from
        # this method, but the DB API Spec requires it.
        # To retrieve the *results* of the procedure call, use the fetch*
        # methods, as specified by the DB API Spec.
        return params


##########################################
##     PUBLIC CLASSES: END              ##
##########################################

class _RowMapping:
    """
      An internal kinterbasdb class that wraps a row of results in order to map
    field name to field value.

      kinterbasdb makes ABSOLUTELY NO GUARANTEES about the return value of the
    fetch(one|many|all) methods except that it is a sequence indexed by field
    position, and no guarantees about the return value of the
    fetch(one|many|all)map methods except that it is a mapping of field name
    to field value.
      Therefore, client programmers should NOT rely on the return value being
    an instance of a particular class or type.
    """

    def __init__(self, description, row):
        self._description = description
        fields = self._fields = {}
        pos = 0
        for fieldSpec in description:
            # It's possible for a result set from the database engine to return
            # multiple fields with the same name, but kinterbasdb's key-based
            # row interface only honors the first (thus setdefault, which won't
            # store the position if it's already present in self._fields).
            fields.setdefault(fieldSpec[DESCRIPTION_NAME], row[pos])
            pos += 1


    def __len__(self):
        return len(self._fields)


    def __getitem__(self, fieldName):
        fields = self._fields
        # Straightforward, unnormalized lookup will work if the fieldName is
        # already uppercase and/or if it refers to a database field whose
        # name is case-sensitive.
        if fields.has_key(fieldName):
            return fields[fieldName]
        else:
            if fieldName.startswith('"') and fieldName.endswith('"'):
                # Quoted name; leave the case of the field name untouched, but
                # strip the quotes.
                fieldNameNormalized = fieldName[1:-1]
            else:
                # Everything else is normalized to uppercase to support
                # case-insensitive lookup.
                fieldNameNormalized = fieldName.upper()
            try:
                return fields[fieldNameNormalized]
            except KeyError:
                raise KeyError('Result set has no field named "%s".  The field'
                    ' name must be one of: (%s)'
                    % (fieldName, ', '.join(fields.keys()))
                  )


    def get(self, fieldName, defaultValue=None):
        try:
            return self[fieldName]
        except KeyError:
            return defaultValue


    def __contains__(self, fieldName):
        try:
            self[fieldName]
        except KeyError:
            return False
        else:
            return True


    def __str__(self):
        # Return an easily readable dump of this row's field names and their
        # corresponding values.
        return '<result set row with %s>' % ', '.join([
            '%s = %s' % (fieldName, self[fieldName])
            for fieldName in self._fields.keys()
          ])


    def keys(self):
        # Note that this is an *ordered* list of keys.
        return [fieldSpec[DESCRIPTION_NAME] for fieldSpec in self._description]


    def values(self):
        # Note that this is an *ordered* list of values.
        return [self[fieldName] for fieldName in self.keys()]


    def items(self):
        return [(fieldName, self[fieldName]) for fieldName in self.keys()]


    if sys.version_info >= (2,2):
        import _py21incompat
        _py21incompat.init(globals())
        iterkeys = _py21incompat._RowMapping__iterkeys
        __iter__ = iterkeys
        itervalues = _py21incompat._RowMapping__itervalues
        iteritems = _py21incompat._RowMapping__iteritems


def _trans_require_dict(obj):
    if not isinstance(obj, types.DictType):
        raise TypeError(
            "The dynamic type translation table must be a dictionary, not a %s"
            % ( (hasattr(obj, '__class__') and obj.__class__.__name__)
                or str(type(obj))
              )
          )


# 2003.10.16:
_OUT_TRANS_FUNC_SAMPLE_ARGS = {
    'TEXT':             'sample',
    'TEXT_UNICODE':     ('sample', 3),
    'BLOB':             'sample',
    'INTEGER':          1,
    'FLOATING':         1.0,
    'FIXED':            (10, -1),
    'DATE':             (2003,12,31),
    'TIME':             (23,59,59),
    'TIMESTAMP':        (2003,12,31,23,59,59),
  }

def _make_output_translator_return_type_dict_from_trans_dict(trans_dict):
    # Calls each output translator in trans_dict, passing the translator sample
    # arguments and recording its return type.
    # Returns a mapping of translator key -> return type.
    trans_return_types = {}
    for (trans_key, trans_func) in trans_dict.items():
        if trans_func is None:
            # Don't make an entry for "naked" translators; the Cursor.description
            # creation code will fall back on the default type.
            continue
        try:
            sample_arg = _OUT_TRANS_FUNC_SAMPLE_ARGS[trans_key]
        except KeyError:
            raise ProgrammingError(
                "Cannot translate type '%s'. Type must be one of %s."
                % (trans_key, _OUT_TRANS_FUNC_SAMPLE_ARGS.keys())
              )
        return_val = trans_func(sample_arg)
        return_type = type(return_val)
        trans_return_types[trans_key] = return_type
    return trans_return_types


# 2004.04.07: A 'isinstance(x, basestring)' predicate compatible with < 2.3.
if sys.version_info < (2,3):
    def _is_basestring(x):
        return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType)
else:
    def _is_basestring(x):
        return isinstance(x, basestring)


# 2004.04.19:
def _validateTPB(tpb):
    if not (isinstance(tpb, types.StringType) and len(tpb) > 0):
        raise ProgrammingError('TPB must be non-unicode string of length > 0')
    # The kinterbasdb documentation promises (or at least strongly implies)
    # that if the user tries to set a TPB that does not begin with
    # isc_tpb_version3, kinterbasdb will automatically supply that
    # infrastructural value.  This promise might cause problems in the future,
    # when isc_tpb_version3 is superseded.  A possible solution would be to
    # check the first byte against all known isc_tpb_versionX version flags,
    # like this:
    #   if tpb[0] not in (_k.isc_tpb_version3, ..., _k.isc_tpb_versionN):
    #      tpb = _k.isc_tpb_version3 + tpb
    # That way, compatibility with old versions of the DB server would be
    # maintained, but client code could optionally specify a newer TPB version.
    if tpb[0] != _k.isc_tpb_version3:
        tpb = _k.isc_tpb_version3 + tpb
    return tpb


_DATABASE_INFO__KNOWN_LOW_LEVEL_EXCEPTIONS = ( # Added 2004.12.12
    isc_info_user_names,
  )
