Sophie

Sophie

distrib > Mageia > 1 > i586 > by-pkgid > f8b7d8f355d7618a0725431daef6c72f > files > 92

kinterbasdb-3.3.0-0.mga1.i586.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Native Database Engine Features and Extensions Beyond the Python DB API &mdash; KInterbasDB v3.3.0 documentation</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '3.3.0',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="top" title="KInterbasDB v3.3.0 documentation" href="index.html" />
    <link rel="next" title="Concurrency" href="concurrency.html" />
    <link rel="prev" title="Compliance to Python Database API 2.0" href="python-db-api-compliance.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="concurrency.html" title="Concurrency"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="python-db-api-compliance.html" title="Compliance to Python Database API 2.0"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">KInterbasDB v3.3.0 documentation</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  
  <div class="section" id="native-database-engine-features-and-extensions-beyond-the-python-db-api">
<h1>Native Database Engine Features and Extensions Beyond the Python DB API<a class="headerlink" href="#native-database-engine-features-and-extensions-beyond-the-python-db-api" title="Permalink to this headline">¶</a></h1>
<div class="section" id="programmatic-database-creation-and-deletion">
<h2>Programmatic Database Creation and Deletion<a class="headerlink" href="#programmatic-database-creation-and-deletion" title="Permalink to this headline">¶</a></h2>
<p>The Firebird engine stores a database in a fairly straightforward
manner: as a single file or, if desired, as a segmented group of
files.</p>
<p>The engine supports dynamic database creation via the SQL statement
<cite>CREATE DATABASE</cite>.</p>
<p>The engine also supports dropping (deleting) databases dynamically,
but dropping is a more complicated operation than creating, for
several reasons: an existing database may be in use by users other
than the one who requests the deletion, it may have supporting objects
such as temporary sort files, and it may even have dependent shadow
databases. Although the database engine recognizes a <cite>DROP DATABASE</cite>
SQL statement, support for that statement is limited to the <cite>isql</cite>
command-line administration utility. However, the engine supports the
deletion of databases via an API call, which KInterbasDB exposes to
Python (see below).</p>
<p>KInterbasDB supports dynamic database creation and deletion via the
module-level function <a title="kinterbasdb.create_database" class="reference internal" href="#kinterbasdb.create_database"><tt class="xref docutils literal"><span class="pre">kinterbasdb.create_database()</span></tt></a> and the method
<a title="kinterbasdb.Connection.drop_database" class="reference internal" href="#kinterbasdb.Connection.drop_database"><tt class="xref docutils literal"><span class="pre">drop_database()</span></tt></a>. These are documented below,
then demonstrated by a brief example.</p>
<dl class="function">
<dt id="kinterbasdb.create_database">
<!--[kinterbasdb.create_database]--><tt class="descclassname">kinterbasdb.</tt><tt class="descname">create_database</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.create_database" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a database according to the supplied <cite>CREATE DATABASE</cite> SQL
statement. Returns an open connection to the newly created database.</p>
<p>Arguments:</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Sql:</th><td class="field-body">string containing the <cite>CREATE DATABASE</cite> statement. Note that
this statement may need to include a username and password.</td>
</tr>
<tr class="field"><th class="field-name">Dialect:</th><td class="field-body"><cite>optional</cite> - the SQL dialect under which to execute the
statement (defaults to <cite>3</cite>).</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Connection.drop_database">
<!--[kinterbasdb.Connection.drop_database]--><tt class="descclassname">Connection.</tt><tt class="descname">drop_database</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.drop_database" title="Permalink to this definition">¶</a></dt>
<dd><p>Deletes the database to which the connection is attached.</p>
<p>This method performs the database deletion in a responsible fashion.
Specifically, it:</p>
<ul class="simple">
<li>raises an <cite>OperationalError</cite> instead of deleting the database if
there are other active connections to the database</li>
<li>deletes supporting files and logs in addition to the primary
database file(s)</li>
</ul>
<p>This method has no arguments.</p>
<p>Example program:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">create_database</span><span class="p">(</span>
      <span class="s">&quot;create database &#39;/temp/db.db&#39; user &#39;sysdba&#39; password &#39;pass&#39;&quot;</span>
      <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">drop_database</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="advanced-transaction-control">
<h2>Advanced Transaction Control<a class="headerlink" href="#advanced-transaction-control" title="Permalink to this headline">¶</a></h2>
<p>For the sake of simplicity, KInterbasDB lets the Python programmer
ignore transaction management to the greatest extent allowed by the
Python Database API Specification 2.0. The specification says, &#8220;if the
database supports an auto-commit feature, this must be initially off&#8221;.
At a minimum, therefore, it is necessary to call the <cite>commit</cite> method
of the connection in order to persist any changes made to the
database. Transactions left unresolved by the programmer will be
<a href="#id1"><span class="problematic" id="id2">`</span></a>rollback`ed when the connection is garbage collected.</p>
<p>Remember that because of <a class="reference external" href="http://philip.greenspun.com/panda/databases-choosing#acid">ACID</a>,
every data manipulation operation in the Firebird database engine
takes place in the context of a transaction, including operations
that are conceptually &#8220;read-only&#8221;, such as a typical <cite>SELECT</cite>.
The client programmer of KInterbasDB establishes a transaction
implicitly by using any SQL execution method, such as
<a title="kinterbasdb.Connection.execute_immediate" class="reference external" href="python-db-api-compliance.html#kinterbasdb.Connection.execute_immediate"><tt class="xref docutils literal"><span class="pre">execute_immediate()</span></tt></a>,
<a title="Cursor.execute" class="reference external" href="Python-DB-API-2.0.html#Cursor.execute"><tt class="xref docutils literal"><span class="pre">Cursor.execute()</span></tt></a>, or <a title="Cursor.callproc" class="reference external" href="Python-DB-API-2.0.html#Cursor.callproc"><tt class="xref docutils literal"><span class="pre">Cursor.callproc()</span></tt></a>.</p>
<p>Although KInterbasDB allows the programmer to pay little attention to
transactions, it also exposes the full complement of the database
engine&#8217;s advanced transaction control features: transaction
parameters, retaining transactions, savepoints, and distributed
transactions.</p>
<div class="section" id="explicit-transaction-start">
<h3>Explicit transaction start<a class="headerlink" href="#explicit-transaction-start" title="Permalink to this headline">¶</a></h3>
<p>In addition to the implicit transaction initiation required by
Python Database API, KInterbasDB allows the programmer to
start transactions explicitly via the <cite>Connection.begin</cite> method.</p>
<dl class="method">
<dt id="kinterbasdb.Connection.begin">
<!--[kinterbasdb.Connection.begin]--><tt class="descclassname">Connection.</tt><tt class="descname">begin</tt><big>(</big><em>tpb</em><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.begin" title="Permalink to this definition">¶</a></dt>
<dd><p>Starts a transaction explicitly. This is never <em>required</em>; a
transaction will be started implicitly if necessary.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Tpb:</th><td class="field-body">Optional transaction parameter buffer (TPB) populated with
<cite>kinterbasdb.isc_tpb_*</cite> constants. See the Firebird API guide
for these constants&#8217; meanings.</td>
</tr>
</tbody>
</table>
</dd></dl>

</div>
<div class="section" id="transaction-parameters">
<h3>Transaction Parameters<a class="headerlink" href="#transaction-parameters" title="Permalink to this headline">¶</a></h3>
<p>The database engine offers the client programmer an optional facility
called <em>transaction parameter buffers</em> (TPBs) for tweaking the
operating characteristics of the transactions he initiates. These
include characteristics such as whether the transaction has read and
write access to tables, or read-only access, and whether or not other
simultaneously active transactions can share table access with the
transaction.</p>
<p>Connections have a <tt class="xref docutils literal"><span class="pre">default_tpb</span></tt> attribute that can be changed to set
the default TPB for all transactions subsequently started on the
connection. Alternatively, if the programmer only wants to set the TPB
for a single transaction, he can start a transaction explicitly via
the <a title="kinterbasdb.Connection.begin" class="reference internal" href="#kinterbasdb.Connection.begin"><tt class="xref docutils literal"><span class="pre">begin()</span></tt></a> method and pass a TPB for
that single transaction.</p>
<p>For details about TPB construction, see the Firebird API documentation.
In particular, the <tt class="docutils literal"><span class="pre">ibase.h</span></tt> supplied with Firebird contains all
possible TPB elements &#8211; single bytes that the C API defines as
constants whose names begin with <cite>isc_tpb_</cite>. KInterbasDB makes all of
those TPB constants available (under the same names) as module-level
constants in the form of single-character strings. A transaction
parameter <em>buffer</em> is handled in C as a character array; KInterbasDB
requires that TPBs be constructed as Python strings. Since the
constants in the <cite>kinterbasdb.isc_tpb_*</cite> family are single-character
Python strings, they can simply be concatenated to create a TPB.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">This method requires good knowledge of <cite>tpc_block</cite> structure and
proper order of various parameters, as Firebird engine will raise an error
when badly structured block would be used. Also definition of <cite>table
reservation</cite> parameters is uncomfortable as you&#8217;ll need to mix binary codes
with table names passed as Pascal strings (characters preceded by string length).</p>
</div>
<p>The following program uses explicit transaction initiation and TPB
construction to establish an unobtrusive transaction for read-only
access to the database:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>

<span class="c"># Construct a TPB by concatenating single-character strings (bytes)</span>
<span class="c"># from the kinterbasdb.isc_tpb_* family.</span>
<span class="n">customTPB</span> <span class="o">=</span> <span class="p">(</span>
      <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_tpb_read</span>
    <span class="o">+</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_tpb_read_committed</span>
    <span class="o">+</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_tpb_rec_version</span>
  <span class="p">)</span>

<span class="c"># Explicitly start a transaction with the custom TPB:</span>
<span class="n">con</span><span class="o">.</span><span class="n">begin</span><span class="p">(</span><span class="n">tpb</span><span class="o">=</span><span class="n">customTPB</span><span class="p">)</span>

<span class="c"># Now read some data using cursors:</span>
<span class="o">...</span>

<span class="c"># Commit the transaction with the custom TPB.  Future transactions</span>
<span class="c"># opened on con will not use a custom TPB unless it is explicitly</span>
<span class="c"># passed to con.begin every time, as it was above, or</span>
<span class="c"># con.default_tpb is changed to the custom TPB, as in:</span>
<span class="c">#   con.default_tpb = customTPB</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
</pre></div>
</div>
<p>For convenient and safe construction of custom <cite>tpb_block</cite>, KInterbasDB provides
special utility class <cite>TPB</cite>.</p>
<dl class="class">
<dt id="kinterbasdb.TPB">
<!--[kinterbasdb.TPB]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">TPB</tt><a class="headerlink" href="#kinterbasdb.TPB" title="Permalink to this definition">¶</a></dt>
<dd><dl class="attribute">
<dt id="kinterbasdb.TPB.access_mode">
<!--[kinterbasdb.TPB.access_mode]--><tt class="descname">access_mode</tt><a class="headerlink" href="#kinterbasdb.TPB.access_mode" title="Permalink to this definition">¶</a></dt>
<dd>Required access mode. Default <cite>isc_tpb_write</cite>.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.TPB.isolation_level">
<!--[kinterbasdb.TPB.isolation_level]--><tt class="descname">isolation_level</tt><a class="headerlink" href="#kinterbasdb.TPB.isolation_level" title="Permalink to this definition">¶</a></dt>
<dd>Required Transaction Isolation Level. Default <cite>isc_tpb_concurrency</cite>.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.TPB.lock_resolution">
<!--[kinterbasdb.TPB.lock_resolution]--><tt class="descname">lock_resolution</tt><a class="headerlink" href="#kinterbasdb.TPB.lock_resolution" title="Permalink to this definition">¶</a></dt>
<dd>Required lock resolution method. Default <cite>isc_tpb_wait</cite>.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.TPB.lock_timeout">
<!--[kinterbasdb.TPB.lock_timeout]--><tt class="descname">lock_timeout</tt><a class="headerlink" href="#kinterbasdb.TPB.lock_timeout" title="Permalink to this definition">¶</a></dt>
<dd>Required lock timeout. Default <cite>None</cite>.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.TPB.table_reservation">
<!--[kinterbasdb.TPB.table_reservation]--><tt class="descname">table_reservation</tt><a class="headerlink" href="#kinterbasdb.TPB.table_reservation" title="Permalink to this definition">¶</a></dt>
<dd><p>Table reservation specification. Default <cite>None</cite>.
Instead of changing the value of the table_reservation object itself,
you must change its <em>elements</em> by manipulating it as though it were
a dictionary that mapped &#8220;TABLE_NAME&#8221;: (sharingMode, accessMode)
For example:</p>
<div class="highlight-python"><pre>tpbBuilder.table_reservation["MY_TABLE"] =
  (kinterbasdb.isc_tpb_protected, kinterbasdb.isc_tpb_lock_write)</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.TPB.render">
<!--[kinterbasdb.TPB.render]--><tt class="descname">render</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.TPB.render" title="Permalink to this definition">¶</a></dt>
<dd>Returns valid <cite>transaction parameter block</cite> according to current
values of member attributes.</dd></dl>

</dd></dl>

<div class="highlight-python"><pre>import kinterbasdb

con = kinterbasdb.connect(dsn='localhost:/temp/test.db', user='sysdba', password='pass')

# Use TPB to construct valid transaction parameter block
# from the kinterbasdb.isc_tpb_* family.
customTPB = TPB()
customTPB.access_mode = kinterbasdb.isc_tpb_read
customTPB.isolation_level = kinterbasdb.isc_tpb_read_committed
    + kinterbasdb.isc_tpb_rec_version

# Explicitly start a transaction with the custom TPB:
con.begin(tpb=customTPB.render())

# Now read some data using cursors:
...

# Commit the transaction with the custom TPB.  Future transactions
# opened on con will not use a custom TPB unless it is explicitly
# passed to con.begin every time, as it was above, or
# con.default_tpb is changed to the custom TPB, as in:
#   con.default_tpb = customTPB.render()
con.commit()</pre>
</div>
<p>If you want to build only <cite>table reservation</cite> part of <cite>tpb</cite> (for example
to add to various custom built parameter blocks), you can use class
<cite>TableReservation</cite> instead <cite>TPB</cite>.</p>
<dl class="class">
<dt id="kinterbasdb.TableReservation">
<!--[kinterbasdb.TableReservation]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">TableReservation</tt><a class="headerlink" href="#kinterbasdb.TableReservation" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a <cite>dictionary-like</cite> class, where keys are table names and values
must be tuples of access parameters, i.e. &#8220;TABLE_NAME&#8221;: (sharingMode, accessMode)</p>
<dl class="method">
<dt id="kinterbasdb.TableReservation.render">
<!--[kinterbasdb.TableReservation.render]--><tt class="descname">render</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.TableReservation.render" title="Permalink to this definition">¶</a></dt>
<dd>Returns propely formatted table reservation part of <cite>transaction parameter
block</cite> according to current values.</dd></dl>

</dd></dl>

<p>Conenction object also exposes two methods that return infromation about
current transaction:</p>
<dl class="class">
<dt id="kinterbasdb.Connection">
<!--[kinterbasdb.Connection]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">Connection</tt><a class="headerlink" href="#kinterbasdb.Connection" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="kinterbasdb.Connection.trans_info">
<!--[kinterbasdb.Connection.trans_info]--><tt class="descname">trans_info</tt><big>(</big><em>request</em><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.trans_info" title="Permalink to this definition">¶</a></dt>
<dd><p>Pythonic wrapper around <a title="kinterbasdb.Connection.transaction_info" class="reference internal" href="#kinterbasdb.Connection.transaction_info"><tt class="xref docutils literal"><span class="pre">transaction_info()</span></tt></a> call.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Request:</th><td class="field-body">One or more information request codes (see transaction_info
for details). Multiple codes must be passed as tuple.</td>
</tr>
</tbody>
</table>
<p>Returns decoded response(s) for specified request code(s). When multiple requests
are passed, returns a dictionary where key is the request code and value is the
response from server.</p>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Connection.transaction_info">
<!--[kinterbasdb.Connection.transaction_info]--><tt class="descname">transaction_info</tt><big>(</big><em>request</em>, <em>result_type</em><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.transaction_info" title="Permalink to this definition">¶</a></dt>
<dd><p>Thin wrapper around Firebird API <cite>isc_transaction_info</cite> call. This function
returns information about active transaction. Raises <cite>ProgrammingError</cite>
exception when transaction is not active.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Request:</th><td class="field-body"><p class="first">One from the next constants:</p>
<blockquote>
<ul class="simple">
<li>isc_info_tra_id</li>
<li>isc_info_tra_oldest_interesting</li>
<li>isc_info_tra_oldest_snapshot</li>
<li>isc_info_tra_oldest_active</li>
<li>isc_info_tra_isolation</li>
<li>isc_info_tra_access</li>
<li>isc_info_tra_lock_timeout</li>
</ul>
</blockquote>
<p>See Firebird API Guide for details.</p>
</td>
</tr>
<tr class="field"><th class="field-name">Result_type:</th><td class="field-body"><p class="first">String code for result type:</p>
<ul class="last simple">
<li>&#8216;i&#8217; for Integer</li>
<li>&#8216;s&#8217; fro String</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="retaining-operations">
<h3>Retaining Operations<a class="headerlink" href="#retaining-operations" title="Permalink to this headline">¶</a></h3>
<p>The <cite>commit</cite> and <cite>rollback</cite> methods of <cite>kinterbasdb.Connection</cite> accept
an optional boolean parameter <cite>retaining</cite> (default <cite>False</cite>) to
indicate whether to recycle the transactional context of the
transaction being resolved by the method call.</p>
<p>If <cite>retaining</cite> is <cite>True</cite>, the infrastructural support for the
transaction active at the time of the method call will be &#8220;retained&#8221;
(efficiently and transparently recycled) after the database server has
committed or rolled back the conceptual transaction.</p>
<p>In code that commits or rolls back frequently, &#8220;retaining&#8221; the
transaction yields considerably better performance. However, retaining
transactions must be used cautiously because they can interfere with
the server&#8217;s ability to garbage collect old record versions. For
details about this issue, read the &#8220;Garbage&#8221; section of <a class="reference external" href="http://www.ibphoenix.com/main.nfs?a=ibphoenix&amp;s=1123236035:18161&amp;page=ibp_expert4">this document</a> by Ann Harrison.</p>
<p>For more information about retaining transactions, see Firebird documentation.</p>
</div>
<div class="section" id="savepoints">
<h3>Savepoints<a class="headerlink" href="#savepoints" title="Permalink to this headline">¶</a></h3>
<p>Firebird 1.5 introduced support for transaction savepoints. Savepoints
are named, intermediate control points within an open transaction that
can later be rolled back to, without affecting the preceding work.
Multiple savepoints can exist within a single unresolved transaction,
providing &#8220;multi-level undo&#8221; functionality.</p>
<p>Although Firebird savepoints are fully supported from SQL alone via
the <cite>SAVEPOINT &#8216;name&#8217;</cite> and <cite>ROLLBACK TO &#8216;name&#8217;</cite> statements,
KInterbasDB also exposes savepoints at the Python API level for the
sake of convenience.</p>
<dl class="method">
<dt id="kinterbasdb.Connection.savepoint">
<!--[kinterbasdb.Connection.savepoint]--><tt class="descclassname">Connection.</tt><tt class="descname">savepoint</tt><big>(</big><em>name</em><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.savepoint" title="Permalink to this definition">¶</a></dt>
<dd>Establishes a savepoint with the specified <cite>name</cite>. To roll back to a
specific savepoint, call the <a title="kinterbasdb.Connection.rollback" class="reference external" href="python-db-api-compliance.html#kinterbasdb.Connection.rollback"><tt class="xref docutils literal"><span class="pre">rollback()</span></tt></a>
method and provide a value (the name of the savepoint) for the optional
<cite>savepoint</cite> parameter. If the <cite>savepoint</cite> parameter of
<a title="kinterbasdb.Connection.rollback" class="reference external" href="python-db-api-compliance.html#kinterbasdb.Connection.rollback"><tt class="xref docutils literal"><span class="pre">rollback()</span></tt></a> is not specified, the active
transaction is cancelled in its entirety, as required by the Python
Database API Specification.</dd></dl>

<p>The following program demonstrates savepoint manipulation via the
KInterbasDB API, rather than raw SQL.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table test_savepoints (a integer)&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="k">print</span> <span class="s">&#39;Before the first savepoint, the contents of the table are:&#39;</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test_savepoints&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39; &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into test_savepoints values (?)&quot;</span><span class="p">,</span> <span class="p">[</span><span class="mf">1</span><span class="p">])</span>
<span class="n">con</span><span class="o">.</span><span class="n">savepoint</span><span class="p">(</span><span class="s">&#39;A&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;After savepoint A, the contents of the table are:&#39;</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test_savepoints&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39; &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into test_savepoints values (?)&quot;</span><span class="p">,</span> <span class="p">[</span><span class="mf">2</span><span class="p">])</span>
<span class="n">con</span><span class="o">.</span><span class="n">savepoint</span><span class="p">(</span><span class="s">&#39;B&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;After savepoint B, the contents of the table are:&#39;</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test_savepoints&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39; &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into test_savepoints values (?)&quot;</span><span class="p">,</span> <span class="p">[</span><span class="mf">3</span><span class="p">])</span>
<span class="n">con</span><span class="o">.</span><span class="n">savepoint</span><span class="p">(</span><span class="s">&#39;C&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;After savepoint C, the contents of the table are:&#39;</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test_savepoints&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39; &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">con</span><span class="o">.</span><span class="n">rollback</span><span class="p">(</span><span class="n">savepoint</span><span class="o">=</span><span class="s">&#39;A&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;After rolling back to savepoint A, the contents of the table are:&#39;</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test_savepoints&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39; &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">con</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;After rolling back entirely, the contents of the table are:&#39;</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test_savepoints&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39; &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>
</div>
<p>The output of the example program is shown below.</p>
<div class="highlight-python"><pre>Before the first savepoint, the contents of the table are:
  []
After savepoint A, the contents of the table are:
  [(1,)]
After savepoint B, the contents of the table are:
  [(1,), (2,)]
After savepoint C, the contents of the table are:
  [(1,), (2,), (3,)]
After rolling back to savepoint A, the contents of the table are:
  [(1,)]
After rolling back entirely, the contents of the table are:
  []</pre>
</div>
</div>
<div class="section" id="using-multiple-transactions-with-the-same-connection">
<h3>Using multiple transactions with the same connection<a class="headerlink" href="#using-multiple-transactions-with-the-same-connection" title="Permalink to this headline">¶</a></h3>
<p>
<span class="versionmodified">New in version 3.3.</span></p>
<p>Python Database API 2.0 was created with assumption that connection
can support only one transactions per single connection. However,
Firebird can support multiple independent transactions that can run
simultaneously within single connection / attachment to the database.
This feature is very important, as applications may require multiple
transaction openned simultaneously to perform various tasks, which
would require to open multiple connections and thus consume more
resources than necessary.</p>
<p>KInterbasDB surfaces this Firebird feature through new class
<a title="kinterbasdb.Transaction" class="reference internal" href="#kinterbasdb.Transaction"><tt class="xref docutils literal"><span class="pre">Transaction</span></tt></a> and extensions to
<a title="kinterbasdb.Connection" class="reference internal" href="#kinterbasdb.Connection"><tt class="xref docutils literal"><span class="pre">Connection</span></tt></a> and <a title="kinterbasdb.Cursor" class="reference internal" href="#kinterbasdb.Cursor"><tt class="xref docutils literal"><span class="pre">Cursor</span></tt></a>
classes.</p>
<dl class="class">
<dt>
class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">Connection</tt></dt>
<dd><dl class="method">
<dt id="kinterbasdb.Connection.trans">
<!--[kinterbasdb.Connection.trans]--><tt class="descname">trans</tt><big>(</big><em>tpb=None</em><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.trans" title="Permalink to this definition">¶</a></dt>
<dd>Creates a new Transaction that operates within the context of this
connection.  Cursors can be created within that Transaction via its
.cursor() method.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.Connection.transactions">
<!--[kinterbasdb.Connection.transactions]--><tt class="descname">transactions</tt><a class="headerlink" href="#kinterbasdb.Connection.transactions" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>read-only property</cite></p>
<p>List of non-close()d <cite>Transaction</cite> objects associated
with this <cite>Connection</cite>. An element of this list may represent a resolved or
unresolved physical transaction. Once a <cite>Transaction</cite> object has been
created, it is only removed from the Connection&#8217;s tracker if the
Transaction&#8217;s <cite>close()</cite> method is called (<cite>Transaction.__del__</cite> triggers
an implicit close() call if necessary), or (obviously) if the Connection
itself is close()d. The initial implementation will not make any guarantees
about the order of the Transactions in this list.</p>
</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.Connection.main_transaction">
<!--[kinterbasdb.Connection.main_transaction]--><tt class="descname">main_transaction</tt><a class="headerlink" href="#kinterbasdb.Connection.main_transaction" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>read-only property</cite></p>
<p>Transaction object that represents the DB-API implicit transaction.
The implementation guarantees that the same Transaction object will be
reused across all DB-API transactions during the lifetime of the Connection.</p>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Connection.prepare">
<!--[kinterbasdb.Connection.prepare]--><tt class="descname">prepare</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.prepare" title="Permalink to this definition">¶</a></dt>
<dd>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
<a class="reference internal" href="#distributed-transactions">Distributed Transactions</a> section for details.</dd></dl>

</dd></dl>

<dl class="class">
<dt id="kinterbasdb.Cursor">
<!--[kinterbasdb.Cursor]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">Cursor</tt><a class="headerlink" href="#kinterbasdb.Cursor" title="Permalink to this definition">¶</a></dt>
<dd><dl class="attribute">
<dt id="kinterbasdb.Cursor.transaction">
<!--[kinterbasdb.Cursor.transaction]--><tt class="descname">transaction</tt><a class="headerlink" href="#kinterbasdb.Cursor.transaction" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>read-only property</cite></p>
<p>Transaction with which this Cursor is associated. <cite>None</cite> if the Transaction has
been close()d, or if the Cursor has been close()d.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="kinterbasdb.Transaction">
<!--[kinterbasdb.Transaction]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">Transaction</tt><a class="headerlink" href="#kinterbasdb.Transaction" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="kinterbasdb.Transaction.__init__">
<!--[kinterbasdb.Transaction.__init__]--><tt class="descname">__init__</tt><big>(</big><em>connection</em>, <em>tpb=None</em><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.__init__" title="Permalink to this definition">¶</a></dt>
<dd>Constructor requires open <a title="kinterbasdb.Connection" class="reference internal" href="#kinterbasdb.Connection"><tt class="xref docutils literal"><span class="pre">Connection</span></tt></a> object and optional
<cite>tpb</cite> specification.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.Transaction.connection">
<!--[kinterbasdb.Transaction.connection]--><tt class="descname">connection</tt><a class="headerlink" href="#kinterbasdb.Transaction.connection" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>read-only property</cite></p>
<p>Connection object on which this Transaction is based.
When the Connection&#8217;s close() method is called, all Transactions that depend
on the connection will also be implicitly close()d. If a Transaction has been
close()d, its connection property will be None.</p>
</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.Transaction.closed">
<!--[kinterbasdb.Transaction.closed]--><tt class="descname">closed</tt><a class="headerlink" href="#kinterbasdb.Transaction.closed" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>read-only property</cite></p>
<p><cite>True</cite> if Transaction has been closed (explicitly or implicitly).</p>
</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.Transaction.n_physical">
<!--[kinterbasdb.Transaction.n_physical]--><tt class="descname">n_physical</tt><a class="headerlink" href="#kinterbasdb.Transaction.n_physical" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>read-only property (int)</cite></p>
<p>Number of physical transactions that have been executed via this Transaction
object during its lifetime.</p>
</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.Transaction.resolution">
<!--[kinterbasdb.Transaction.resolution]--><tt class="descname">resolution</tt><a class="headerlink" href="#kinterbasdb.Transaction.resolution" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>read-only property (int)</cite></p>
<p><cite>Zero</cite> if this Transaction object is currently managing an open physical transaction.
<cite>One</cite> if the physical transaction has been resolved normally. Note that this is an int
property rather than a bool, and is named <cite>resolution</cite> rather than <cite>resolved</cite>, so that
the non-zero values other than one can be assigned to convey specific information about
the state of the transaction, in a future implementation (consider distributed
transaction prepared state, limbo state, etc.).</p>
</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.Transaction.cursors">
<!--[kinterbasdb.Transaction.cursors]--><tt class="descname">cursors</tt><a class="headerlink" href="#kinterbasdb.Transaction.cursors" title="Permalink to this definition">¶</a></dt>
<dd>List of non-close()d Cursor objects associated with this Transaction. When
Transaction&#8217;s close() method is called, whether explicitly or implicitly, it will
implicitly close() each of its Cursors. Current implementation do not make any
guarantees about the order of the Cursors in this list.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.begin">
<!--[kinterbasdb.Transaction.begin]--><tt class="descname">begin</tt><big>(</big><em>tpb</em><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.begin" title="Permalink to this definition">¶</a></dt>
<dd>See <a title="kinterbasdb.Connection.begin" class="reference internal" href="#kinterbasdb.Connection.begin"><tt class="xref docutils literal"><span class="pre">Connection.begin()</span></tt></a> for details.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.commit">
<!--[kinterbasdb.Transaction.commit]--><tt class="descname">commit</tt><big>(</big><em>retaining=False</em><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.commit" title="Permalink to this definition">¶</a></dt>
<dd>See <a title="kinterbasdb.Connection.commit" class="reference external" href="python-db-api-compliance.html#kinterbasdb.Connection.commit"><tt class="xref docutils literal"><span class="pre">kinterbasdb.Connection.commit()</span></tt></a> for details.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.close">
<!--[kinterbasdb.Transaction.close]--><tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.close" title="Permalink to this definition">¶</a></dt>
<dd>Permanently closes the Transaction object and severs its associations with other
objects. If the physical transaction is unresolved when this method is called,
a rollback() will be performed first.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.prepare">
<!--[kinterbasdb.Transaction.prepare]--><tt class="descname">prepare</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.prepare" title="Permalink to this definition">¶</a></dt>
<dd>See <a title="kinterbasdb.Connection.prepare" class="reference internal" href="#kinterbasdb.Connection.prepare"><tt class="xref docutils literal"><span class="pre">Connection.prepare()</span></tt></a> for details.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.rollback">
<!--[kinterbasdb.Transaction.rollback]--><tt class="descname">rollback</tt><big>(</big><em>retaining=False</em><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.rollback" title="Permalink to this definition">¶</a></dt>
<dd>See <a title="kinterbasdb.Connection.rollback" class="reference external" href="python-db-api-compliance.html#kinterbasdb.Connection.rollback"><tt class="xref docutils literal"><span class="pre">kinterbasdb.Connection.rollback()</span></tt></a> for details.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.savepoint">
<!--[kinterbasdb.Transaction.savepoint]--><tt class="descname">savepoint</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.savepoint" title="Permalink to this definition">¶</a></dt>
<dd>See <a title="kinterbasdb.Connection.savepoint" class="reference internal" href="#kinterbasdb.Connection.savepoint"><tt class="xref docutils literal"><span class="pre">Connection.savepoint()</span></tt></a> for details.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.trans_info">
<!--[kinterbasdb.Transaction.trans_info]--><tt class="descname">trans_info</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.trans_info" title="Permalink to this definition">¶</a></dt>
<dd>See <a title="kinterbasdb.Connection.trans_info" class="reference internal" href="#kinterbasdb.Connection.trans_info"><tt class="xref docutils literal"><span class="pre">Connection.trans_info()</span></tt></a> for details.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.transaction_info">
<!--[kinterbasdb.Transaction.transaction_info]--><tt class="descname">transaction_info</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.transaction_info" title="Permalink to this definition">¶</a></dt>
<dd>See <a title="kinterbasdb.Connection.transaction_info" class="reference internal" href="#kinterbasdb.Connection.transaction_info"><tt class="xref docutils literal"><span class="pre">Connection.transaction_info()</span></tt></a> for details.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Transaction.cursor">
<!--[kinterbasdb.Transaction.cursor]--><tt class="descname">cursor</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Transaction.cursor" title="Permalink to this definition">¶</a></dt>
<dd>Creates a new Cursor that will operate in the context of this Transaction.
The association between a Cursor and its Transaction is set when the Cursor
is created, and cannot be changed during the lifetime of that Cursor.
See <a title="Connection.cursor" class="reference external" href="Python-DB-API-2.0.html#Connection.cursor"><tt class="xref docutils literal"><span class="pre">Connection.cursor()</span></tt></a> for more details.</dd></dl>

</dd></dl>

<p>If you don&#8217;t want multiple transactions, you can use implicit transaction object
associated with <cite>Connection</cite> and control it via transaction-management and cursor
methods of the <a title="Connection" class="reference external" href="Python-DB-API-2.0.html#Connection"><tt class="xref docutils literal"><span class="pre">Connection</span></tt></a>.</p>
<p>Alternatively, you can directly access the implicit transaction exposed as
<a title="kinterbasdb.Connection.main_transaction" class="reference internal" href="#kinterbasdb.Connection.main_transaction"><tt class="xref docutils literal"><span class="pre">main_transaction</span></tt></a> and control it via its
transaction-management methods.</p>
<p>To use additional transactions, create new <a title="kinterbasdb.Transaction" class="reference internal" href="#kinterbasdb.Transaction"><tt class="xref docutils literal"><span class="pre">Transaction</span></tt></a> object
calling <a title="kinterbasdb.Connection.trans" class="reference internal" href="#kinterbasdb.Connection.trans"><tt class="xref docutils literal"><span class="pre">Connection.trans()</span></tt></a> method.</p>
</div>
<div class="section" id="distributed-transactions">
<h3>Distributed Transactions<a class="headerlink" href="#distributed-transactions" title="Permalink to this headline">¶</a></h3>
<p>Distributed transactions are transactions that span multiple databases. KInterbasDB
provides this Firebird feature through <cite>ConnectionGroup</cite> class.</p>
<dl class="class">
<dt id="kinterbasdb.ConnectionGroup">
<!--[kinterbasdb.ConnectionGroup]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">ConnectionGroup</tt><a class="headerlink" href="#kinterbasdb.ConnectionGroup" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="kinterbasdb.ConnectionGroup.__init__">
<!--[kinterbasdb.ConnectionGroup.__init__]--><tt class="descname">__init__</tt><big>(</big><em>connections=()</em><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.__init__" title="Permalink to this definition">¶</a></dt>
<dd>Constructor accepts optional list of database connections.
Connections cannot be in closed state.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.disband">
<!--[kinterbasdb.ConnectionGroup.disband]--><tt class="descname">disband</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.disband" title="Permalink to this definition">¶</a></dt>
<dd>Forcefully deletes all connections from connection group.
If transaction is active, it&#8217;s canceled (rollback).</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.add">
<!--[kinterbasdb.ConnectionGroup.add]--><tt class="descname">add</tt><big>(</big><em>con</em><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.add" title="Permalink to this definition">¶</a></dt>
<dd>Adds active connection to the group. If connection altready
belong to this or any other ConnectionGroup, has active
transaction, or timeout for it is defined, an exception
is raised. Group also cannot accept new members when in
unresolved transactions.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.remove">
<!--[kinterbasdb.ConnectionGroup.remove]--><tt class="descname">remove</tt><big>(</big><em>con</em><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.remove" title="Permalink to this definition">¶</a></dt>
<dd>Removes specified connection from group. Raises an exception
if connection doesn&#8217;t belong to this group or if group has
unresolved transaction.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.clear">
<!--[kinterbasdb.ConnectionGroup.clear]--><tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.clear" title="Permalink to this definition">¶</a></dt>
<dd>Removes all connections from group. Raises an exception
if group has unresolved transaction.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.members">
<!--[kinterbasdb.ConnectionGroup.members]--><tt class="descname">members</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.members" title="Permalink to this definition">¶</a></dt>
<dd>Returns list of connection objects that belong to this group.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.count">
<!--[kinterbasdb.ConnectionGroup.count]--><tt class="descname">count</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.count" title="Permalink to this definition">¶</a></dt>
<dd>Returns number of connection objects that belong to this group.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.contains">
<!--[kinterbasdb.ConnectionGroup.contains]--><tt class="descname">contains</tt><big>(</big><em>con</em><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.contains" title="Permalink to this definition">¶</a></dt>
<dd>Returns True if specified connection belong to this group.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.begin">
<!--[kinterbasdb.ConnectionGroup.begin]--><tt class="descname">begin</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.begin" title="Permalink to this definition">¶</a></dt>
<dd>Starts distributed transaction over member connections.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.commit">
<!--[kinterbasdb.ConnectionGroup.commit]--><tt class="descname">commit</tt><big>(</big><em>retaining=False</em><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.commit" title="Permalink to this definition">¶</a></dt>
<dd>Commits distributed transaction over member connections using 2PC.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.prepare">
<!--[kinterbasdb.ConnectionGroup.prepare]--><tt class="descname">prepare</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.prepare" title="Permalink to this definition">¶</a></dt>
<dd>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.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.ConnectionGroup.rollback">
<!--[kinterbasdb.ConnectionGroup.rollback]--><tt class="descname">rollback</tt><big>(</big><em>retaining=False</em><big>)</big><a class="headerlink" href="#kinterbasdb.ConnectionGroup.rollback" title="Permalink to this definition">¶</a></dt>
<dd>Rollbacks distributed transaction over member connections.</dd></dl>

</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">While a <cite>Connection</cite> belongs to a <cite>ConnectionGroup</cite>, any calls
to the connection&#8217;s transactional methods ( <cite>begin</cite>, <cite>prepare</cite>,
<cite>commit</cite>, <cite>rollback</cite>) will &#8220;bubble upward&#8221; to apply to the distributed
transaction shared by the group as a whole.</p>
</div>
<p class="rubric">Pitfalls and Limitations</p>
<ul class="simple">
<li>Never add more than one connection to the same database to the same
<cite>ConnectionGroup</cite>!</li>
<li>Current implementation works only with connection objects and their main
transactions. Secondary transaction objects obrained from connection cannot
participate in distributed transaction.</li>
</ul>
<p><strong>Example:</strong></p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="c"># Establish multiple connections the usual way:</span>
<span class="n">con1</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;weasel:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>
<span class="n">con2</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;coyote:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>

<span class="c"># Create a ConnectionGroup to associate multiple connections in such a</span>
<span class="c"># way that they can participate in a distributed transaction.</span>
<span class="c"># !!!</span>
<span class="c"># NO TWO MEMBERS OF A SINGLE CONNECTIONGROUP SHOULD BE ATTACHED TO THE SAME DATABASE!</span>
<span class="c"># !!!</span>
<span class="n">group</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">ConnectionGroup</span><span class="p">(</span> <span class="n">connections</span><span class="o">=</span><span class="p">(</span><span class="n">con1</span><span class="p">,</span><span class="n">con2</span><span class="p">)</span> <span class="p">)</span>

<span class="c"># Start a distributed transaction involving all of the members of the group</span>
<span class="c"># (con1 and con2 in this case) with one of the following approaches:</span>
<span class="c">#   - Call  group.begin()</span>
<span class="c">#   - Call  con1.begin(); the operation will &quot;bubble upward&quot; and apply to the group.</span>
<span class="c">#   - Call  con2.begin(); the operation will &quot;bubble upward&quot; and apply to the group.</span>
<span class="c">#   - Just start executing some SQL statements on either con1 or con2.</span>
<span class="c">#     A transaction will be started implicitly; it will be a distributed</span>
<span class="c">#     transaction because con1 and con2 are members of a ConnectionGroup.</span>
<span class="n">group</span><span class="o">.</span><span class="n">begin</span><span class="p">()</span>

<span class="c"># Perform some database changes the usual way (via cursors on con1 and con2):</span>
<span class="o">...</span>

<span class="c"># Commit or roll back the distributed transaction by calling the commit</span>
<span class="c"># or rollback method of the ConnectionGroup itself, or the commit or</span>
<span class="c"># rollback method of any member connection (con1 or con2 in this case).</span>
<span class="n">group</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="c"># Unless you want to perform another distributed transaction, disband the</span>
<span class="c"># group so that member connections can operate independently again.</span>
<span class="n">group</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="prepared-statements">
<h2>Prepared Statements<a class="headerlink" href="#prepared-statements" title="Permalink to this headline">¶</a></h2>
<p>When you define a Python function, the interpreter initially parses
the textual representation of the function and generates a binary
equivalent called bytecode. The bytecode representation can then be
executed directly by the Python interpreter any number of times and
with a variety of parameters, but the human-oriented textual
definition of the function never need be parsed again.</p>
<p>Database engines perform a similar series of steps when executing a
SQL statement. Consider the following series of statements:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into the_table (a,b,c) values (&#39;aardvark&#39;, 1, 0.1)&quot;</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into the_table (a,b,c) values (&#39;zymurgy&#39;, 2147483647, 99999.999)&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If there are many statements in that series, wouldn&#8217;t it make sense to
&#8220;define a function&#8221; to insert the provided &#8220;parameters&#8221; into the
predetermined fields of the predetermined table, instead of forcing
the database engine to parse each statement anew and figure out what
database entities the elements of the statement refer to? In other
words, why not take advantage of the fact that the form of the
statement (&#8220;the function&#8221;) stays the same throughout, and only the
values (&#8220;the parameters&#8221;) vary? Prepared statements deliver that
performance benefit and other advantages as well.</p>
<p>The following code is semantically equivalent to the series of insert
operations discussed previously, except that it uses a single SQL
statement that contains Firebird&#8217;s parameter marker ( <cite>?</cite>) in the
slots where values are expected, then supplies those values as Python
tuples instead of constructing a textual representation of each value
and passing it to the database engine for parsing:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">insertStatement</span> <span class="o">=</span> <span class="s">&quot;insert into the_table (a,b,c) values (?,?,?)&quot;</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">insertStatement</span><span class="p">,</span> <span class="p">(</span><span class="s">&#39;aardvark&#39;</span><span class="p">,</span> <span class="mf">1</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">))</span>
<span class="o">...</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">insertStatement</span><span class="p">,</span> <span class="p">(</span><span class="s">&#39;zymurgy&#39;</span><span class="p">,</span> <span class="mf">2147483647</span><span class="p">,</span> <span class="mf">99999.999</span><span class="p">))</span>
</pre></div>
</div>
<p>Only the values change as each row is inserted; the statement remains
the same. For many years, KInterbasDB has recognized situations
similar to this one and automatically reused the same prepared
statement in each <a title="Cursor.execute" class="reference external" href="Python-DB-API-2.0.html#Cursor.execute"><tt class="xref docutils literal"><span class="pre">Cursor.execute()</span></tt></a> call. In KInterbasDB 3.2, the
scheme for automatically reusing prepared statements has become more
sophisticated, and the API has been extended to offer the client
programmer manual control over prepared statement creation and use.</p>
<p>The entry point for manual statement preparation is the <cite>Cursor.prep</cite>
method.</p>
<dl class="method">
<dt id="kinterbasdb.Cursor.prep">
<!--[kinterbasdb.Cursor.prep]--><tt class="descclassname">Cursor.</tt><tt class="descname">prep</tt><big>(</big><em>sql</em><big>)</big><a class="headerlink" href="#kinterbasdb.Cursor.prep" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Sql:</th><td class="field-body">string parameter that contains the SQL statement to be prepared.
Returns a <a title="kinterbasdb.PreparedStatement" class="reference internal" href="#kinterbasdb.PreparedStatement"><tt class="xref docutils literal"><span class="pre">PreparedStatement</span></tt></a> instance.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="class">
<dt id="kinterbasdb.PreparedStatement">
<!--[kinterbasdb.PreparedStatement]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">PreparedStatement</tt><a class="headerlink" href="#kinterbasdb.PreparedStatement" title="Permalink to this definition">¶</a></dt>
<dd><p><cite>PreparedStatement</cite> has no public methods, but does have the following
public read-only properties:</p>
<dl class="attribute">
<dt id="kinterbasdb.PreparedStatement.sql">
<!--[kinterbasdb.PreparedStatement.sql]--><tt class="descname">sql</tt><a class="headerlink" href="#kinterbasdb.PreparedStatement.sql" title="Permalink to this definition">¶</a></dt>
<dd>A reference to the string that was passed to
<a title="kinterbasdb.Cursor.prep" class="reference internal" href="#kinterbasdb.Cursor.prep"><tt class="xref docutils literal"><span class="pre">prep()</span></tt></a> to create this <cite>PreparedStatement</cite>.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.PreparedStatement.statement_type">
<!--[kinterbasdb.PreparedStatement.statement_type]--><tt class="descname">statement_type</tt><a class="headerlink" href="#kinterbasdb.PreparedStatement.statement_type" title="Permalink to this definition">¶</a></dt>
<dd><p>An integer code that can be matched against the statement type
constants in the <cite>kinterbasdb.isc_info_sql_stmt_*</cite> series.
The following statement type codes are currently available:</p>
<blockquote>
<ul class="simple">
<li><cite>isc_info_sql_stmt_commit</cite></li>
<li><cite>isc_info_sql_stmt_ddl</cite></li>
<li><cite>isc_info_sql_stmt_delete</cite></li>
<li><cite>isc_info_sql_stmt_exec_procedure</cite></li>
<li><cite>isc_info_sql_stmt_get_segment</cite></li>
<li><cite>isc_info_sql_stmt_insert</cite></li>
<li><cite>isc_info_sql_stmt_put_segment</cite></li>
<li><cite>isc_info_sql_stmt_rollback</cite></li>
<li><cite>isc_info_sql_stmt_savepoint</cite></li>
<li><cite>isc_info_sql_stmt_select</cite></li>
<li><cite>isc_info_sql_stmt_select_for_upd</cite></li>
<li><cite>isc_info_sql_stmt_set_generator</cite></li>
<li><cite>isc_info_sql_stmt_start_trans</cite></li>
<li><cite>isc_info_sql_stmt_update</cite></li>
</ul>
</blockquote>
</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.PreparedStatement.n_input_params">
<!--[kinterbasdb.PreparedStatement.n_input_params]--><tt class="descname">n_input_params</tt><a class="headerlink" href="#kinterbasdb.PreparedStatement.n_input_params" title="Permalink to this definition">¶</a></dt>
<dd>The number of input parameters the statement requires.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.PreparedStatement.n_output_params">
<!--[kinterbasdb.PreparedStatement.n_output_params]--><tt class="descname">n_output_params</tt><a class="headerlink" href="#kinterbasdb.PreparedStatement.n_output_params" title="Permalink to this definition">¶</a></dt>
<dd>The number of output fields the statement produces.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.PreparedStatement.plan">
<!--[kinterbasdb.PreparedStatement.plan]--><tt class="descname">plan</tt><a class="headerlink" href="#kinterbasdb.PreparedStatement.plan" title="Permalink to this definition">¶</a></dt>
<dd>A string representation of the execution plan generated for this
statement by the database engine&#8217;s optimizer. This property can
be used, for example, to verify that a statement is using the
expected index.</dd></dl>

<dl class="attribute">
<dt id="kinterbasdb.PreparedStatement.description">
<!--[kinterbasdb.PreparedStatement.description]--><tt class="descname">description</tt><a class="headerlink" href="#kinterbasdb.PreparedStatement.description" title="Permalink to this definition">¶</a></dt>
<dd>A Python DB API 2.0 description sequence (of the same format as
<a title="Cursor.description" class="reference external" href="Python-DB-API-2.0.html#Cursor.description"><tt class="xref docutils literal"><span class="pre">Cursor.description</span></tt></a>) that describes the statement&#8217;s output
parameters. Statements without output parameters have a <cite>description</cite>
of <cite>None</cite>.</dd></dl>

</dd></dl>

<p>In addition to programmatically examining the characteristics of a SQL
statement via the properties of <cite>PreparedStatement</cite>, the client
programmer can submit a <cite>PreparedStatement</cite> to <a title="Cursor.execute" class="reference external" href="Python-DB-API-2.0.html#Cursor.execute"><tt class="xref docutils literal"><span class="pre">Cursor.execute()</span></tt></a> or
<a title="Cursor.executemany" class="reference external" href="Python-DB-API-2.0.html#Cursor.executemany"><tt class="xref docutils literal"><span class="pre">Cursor.executemany()</span></tt></a> for execution. The code snippet below is
semantically equivalent to both of the previous snippets in this
section, but it explicitly prepares the <cite>INSERT</cite> statement in advance,
then submits it to <a title="Cursor.executemany" class="reference external" href="Python-DB-API-2.0.html#Cursor.executemany"><tt class="xref docutils literal"><span class="pre">Cursor.executemany()</span></tt></a> for execution:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">insertStatement</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">prep</span><span class="p">(</span><span class="s">&quot;insert into the_table (a,b,c) values (?,?,?)&quot;</span><span class="p">)</span>
<span class="n">inputRows</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">(</span><span class="s">&#39;aardvark&#39;</span><span class="p">,</span> <span class="mf">1</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">),</span>
    <span class="o">...</span>
    <span class="p">(</span><span class="s">&#39;zymurgy&#39;</span><span class="p">,</span> <span class="mf">2147483647</span><span class="p">,</span> <span class="mf">99999.999</span><span class="p">)</span>
  <span class="p">]</span>
<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="n">insertStatement</span><span class="p">,</span> <span class="n">inputRows</span><span class="p">)</span>
</pre></div>
</div>
<p><strong>Example Program</strong></p>
<p>The following program demonstrates the explicit use of
PreparedStatements. It also benchmarks explicit <cite>PreparedStatement</cite>
reuse against KInterbasDB&#8217;s automatic <cite>PreparedStatement</cite> reuse, and
against an input strategy that prevents <cite>PreparedStatement</cite> reuse.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;localhost:D:\temp\test-20.firebird&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span>
  <span class="p">)</span>

<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="c"># Create supporting database entities:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table t (a int, b varchar(50))&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;create unique index unique_t_a on t(a)&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="c"># Explicitly prepare the insert statement:</span>
<span class="n">psIns</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">prep</span><span class="p">(</span><span class="s">&quot;insert into t (a,b) values (?,?)&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;psIns.sql: &quot;</span><span class="si">%s</span><span class="s">&quot;&#39;</span> <span class="o">%</span> <span class="n">psIns</span><span class="o">.</span><span class="n">sql</span>
<span class="k">print</span> <span class="s">&#39;psIns.statement_type == kinterbasdb.isc_info_sql_stmt_insert:&#39;</span><span class="p">,</span> <span class="p">(</span>
    <span class="n">psIns</span><span class="o">.</span><span class="n">statement_type</span> <span class="o">==</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_sql_stmt_insert</span>
  <span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;psIns.n_input_params: </span><span class="si">%d</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">psIns</span><span class="o">.</span><span class="n">n_input_params</span>
<span class="k">print</span> <span class="s">&#39;psIns.n_output_params: </span><span class="si">%d</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">psIns</span><span class="o">.</span><span class="n">n_output_params</span>
<span class="k">print</span> <span class="s">&#39;psIns.plan: </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">psIns</span><span class="o">.</span><span class="n">plan</span>

<span class="k">print</span>

<span class="n">N</span> <span class="o">=</span> <span class="mf">10000</span>
<span class="n">iStart</span> <span class="o">=</span> <span class="mf">0</span>

<span class="c"># The client programmer uses a PreparedStatement explicitly:</span>
<span class="n">startTime</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iStart</span><span class="p">,</span> <span class="n">iStart</span> <span class="o">+</span> <span class="n">N</span><span class="p">):</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">psIns</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">)))</span>
<span class="k">print</span> <span class="p">(</span>
    <span class="s">&#39;With explicit prepared statement, performed&#39;</span>
    <span class="s">&#39;</span><span class="se">\n</span><span class="s">  </span><span class="si">%0.2f</span><span class="s"> insertions per second.&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">N</span> <span class="o">/</span> <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">startTime</span><span class="p">))</span>
  <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">iStart</span> <span class="o">+=</span> <span class="n">N</span>

<span class="c"># KInterbasDB automatically uses a PreparedStatement &quot;under the hood&quot;:</span>
<span class="n">startTime</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iStart</span><span class="p">,</span> <span class="n">iStart</span> <span class="o">+</span> <span class="n">N</span><span class="p">):</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into t (a,b) values (?,?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">)))</span>
<span class="k">print</span> <span class="p">(</span>
    <span class="s">&#39;With implicit prepared statement, performed&#39;</span>
    <span class="s">&#39;</span><span class="se">\n</span><span class="s">  </span><span class="si">%0.2f</span><span class="s"> insertions per second.&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">N</span> <span class="o">/</span> <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">startTime</span><span class="p">))</span>
  <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">iStart</span> <span class="o">+=</span> <span class="n">N</span>

<span class="c"># A new SQL string containing the inputs is submitted every time, so</span>
<span class="c"># KInterbasDB is not able to implicitly reuse a PreparedStatement.  Also, in a</span>
<span class="c"># more complicated scenario where the end user supplied the string input</span>
<span class="c"># values, the program would risk SQL injection attacks:</span>
<span class="n">startTime</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iStart</span><span class="p">,</span> <span class="n">iStart</span> <span class="o">+</span> <span class="n">N</span><span class="p">):</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into t (a,b) values (</span><span class="si">%d</span><span class="s">,&#39;</span><span class="si">%s</span><span class="s">&#39;)&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">)))</span>
<span class="k">print</span> <span class="p">(</span>
    <span class="s">&#39;When unable to reuse prepared statement, performed&#39;</span>
    <span class="s">&#39;</span><span class="se">\n</span><span class="s">  </span><span class="si">%0.2f</span><span class="s"> insertions per second.&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">N</span> <span class="o">/</span> <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">startTime</span><span class="p">))</span>
  <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="c"># Prepare a SELECT statement and examine its properties.  The optimizer&#39;s plan</span>
<span class="c"># should use the unique index that we created at the beginning of this program.</span>
<span class="k">print</span>
<span class="n">psSel</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">prep</span><span class="p">(</span><span class="s">&quot;select * from t where a = ?&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;psSel.sql: &quot;</span><span class="si">%s</span><span class="s">&quot;&#39;</span> <span class="o">%</span> <span class="n">psSel</span><span class="o">.</span><span class="n">sql</span>
<span class="k">print</span> <span class="s">&#39;psSel.statement_type == kinterbasdb.isc_info_sql_stmt_select:&#39;</span><span class="p">,</span> <span class="p">(</span>
    <span class="n">psSel</span><span class="o">.</span><span class="n">statement_type</span> <span class="o">==</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_sql_stmt_select</span>
  <span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;psSel.n_input_params: </span><span class="si">%d</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">psSel</span><span class="o">.</span><span class="n">n_input_params</span>
<span class="k">print</span> <span class="s">&#39;psSel.n_output_params: </span><span class="si">%d</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">psSel</span><span class="o">.</span><span class="n">n_output_params</span>
<span class="k">print</span> <span class="s">&#39;psSel.plan: </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">psSel</span><span class="o">.</span><span class="n">plan</span>

<span class="c"># The current implementation does not allow PreparedStatements to be prepared</span>
<span class="c"># on one Cursor and executed on another:</span>
<span class="k">print</span>
<span class="k">print</span> <span class="s">&#39;Note that PreparedStatements are not transferrable from one cursor to another:&#39;</span>
<span class="n">cur2</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur2</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">psSel</span><span class="p">)</span>
</pre></div>
</div>
<p>Output:</p>
<div class="highlight-python"><pre>psIns.sql: "insert into t (a,b) values (?,?)"
psIns.statement_type == kinterbasdb.isc_info_sql_stmt_insert: True
psIns.n_input_params: 2
psIns.n_output_params: 0
psIns.plan: None

With explicit prepared statement, performed
  9551.10 insertions per second.
With implicit prepared statement, performed
  9407.34 insertions per second.
When unable to reuse prepared statement, performed
  1882.53 insertions per second.

psSel.sql: "select * from t where a = ?"
psSel.statement_type == kinterbasdb.isc_info_sql_stmt_select: True
psSel.n_input_params: 1
psSel.n_output_params: 2
psSel.plan: PLAN (T INDEX (UNIQUE_T_A))

Note that PreparedStatements are not transferrable from one cursor to another:
Traceback (most recent call last):
  File "adv_prepared_statements__overall_example.py", line 86, in ?
    cur2.execute(psSel)
kinterbasdb.ProgrammingError: (0, 'A PreparedStatement can only be used with the
 Cursor that originally prepared it.')</pre>
</div>
<p>As you can see, the version that prevents the reuse of prepared
statements is about five times slower &#8211; <em>for a trivial statement</em>. In
a real application, SQL statements are likely to be far more
complicated, so the speed advantage of using prepared statements would
only increase.</p>
<p>As the timings indicate, KInterbasDB does a good job of reusing
prepared statements even if the client program is written in a style
strictly compatible with the Python DB API 2.0 (which accepts only
strings &#8211; not <a title="kinterbasdb.PreparedStatement" class="reference internal" href="#kinterbasdb.PreparedStatement"><tt class="xref docutils literal"><span class="pre">PreparedStatement</span></tt></a> objects &#8211; to the <a title="Cursor.execute" class="reference external" href="Python-DB-API-2.0.html#Cursor.execute"><tt class="xref docutils literal"><span class="pre">Cursor.execute()</span></tt></a>
method). The performance loss in this case is less than one percent.</p>
</div>
<div class="section" id="named-cursors">
<h2>Named Cursors<a class="headerlink" href="#named-cursors" title="Permalink to this headline">¶</a></h2>
<p>To allow the Python programmer to perform scrolling <cite>UPDATE</cite> or
<cite>DELETE</cite> via the &#8220;<cite>SELECT ... FOR UPDATE</cite>&#8221; syntax, KInterbasDB
provides the read/write property <cite>Cursor.name</cite>.</p>
<dl class="attribute">
<dt id="kinterbasdb.Cursor.name">
<!--[kinterbasdb.Cursor.name]--><tt class="descclassname">Cursor.</tt><tt class="descname">name</tt><a class="headerlink" href="#kinterbasdb.Cursor.name" title="Permalink to this definition">¶</a></dt>
<dd>Name for the SQL cursor. This property can be ignored entirely
if you don&#8217;t need to use it.</dd></dl>

<p><strong>Example Program</strong></p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>
<span class="n">curScroll</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">curUpdate</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">curScroll</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select city from addresses for update&quot;</span><span class="p">)</span>
<span class="n">curScroll</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s">&#39;city_scroller&#39;</span>
<span class="n">update</span> <span class="o">=</span> <span class="s">&quot;update addresses set city=? where current of &quot;</span> <span class="o">+</span> <span class="n">curScroll</span><span class="o">.</span><span class="n">name</span>

<span class="k">for</span> <span class="p">(</span><span class="n">city</span><span class="p">,)</span> <span class="ow">in</span> <span class="n">curScroll</span><span class="p">:</span>
    <span class="n">city</span> <span class="o">=</span> <span class="o">...</span> <span class="c"># make some changes to city</span>
    <span class="n">curUpdate</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span> <span class="n">update</span><span class="p">,</span> <span class="p">(</span><span class="n">city</span><span class="p">,)</span> <span class="p">)</span>

<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="parameter-conversion">
<h2>Parameter Conversion<a class="headerlink" href="#parameter-conversion" title="Permalink to this headline">¶</a></h2>
<p>KInterbasDB converts bound parameters marked with a <cite>?</cite> in SQL code in
a standard way. However, the module also offers several extensions to
standard parameter binding, intended to make client code more readable
and more convenient to write.</p>
<div class="section" id="implicit-conversion-of-input-parameters-from-strings">
<h3>Implicit Conversion of Input Parameters from Strings<a class="headerlink" href="#implicit-conversion-of-input-parameters-from-strings" title="Permalink to this headline">¶</a></h3>
<p>The database engine treats most SQL data types in a weakly typed
fashion: the engine may attempt to convert the raw value to a
different type, as appropriate for the current context. For instance,
the SQL expressions <cite>123</cite> (integer) and <cite>&#8216;123&#8217;</cite> (string) are treated
equivalently when the value is to be inserted into an <cite>integer</cite> field;
the same applies when <cite>&#8216;123&#8217;</cite> and <cite>123</cite> are to be inserted into a
<cite>varchar</cite> field.</p>
<p>This weak typing model is quite unlike Python&#8217;s dynamic yet strong
typing. Although weak typing is regarded with suspicion by most
experienced Python programmers, the database engine is in certain
situations so aggressive about its typing model that KInterbasDB
must <a class="reference external" href="http://sourceforge.net/tracker/index.php?func=detail&amp;aid=531828&amp;group_id=9913&amp;atid=309913">compromise</a> in order to remain an elegant
means of programming the database engine.</p>
<p>An example is the handling of &#8220;magic values&#8221; for date and time fields.
The database engine interprets certain string values such as
<cite>&#8216;yesterday&#8217;</cite> and <cite>&#8216;now&#8217;</cite> as having special meaning in a date/time
context. If KInterbasDB did not accept strings as the values of
parameters destined for storage in date/time fields, the resulting
code would be awkward. Consider the difference between the two Python
snippets below, which insert a row containing an integer and a
timestamp into a table defined with the following DDL statement:</p>
<div class="highlight-python"><pre>create table test_table (i int, t timestamp)</pre>
</div>
<div class="highlight-python"><div class="highlight"><pre><span class="n">i</span> <span class="o">=</span> <span class="mf">1</span>
<span class="n">t</span> <span class="o">=</span> <span class="s">&#39;now&#39;</span>
<span class="n">sqlWithMagicValues</span> <span class="o">=</span> <span class="s">&quot;insert into test_table (i, t) values (?, &#39;</span><span class="si">%s</span><span class="s">&#39;)&quot;</span> <span class="o">%</span> <span class="n">t</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span> <span class="n">sqlWithMagicValues</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">,)</span> <span class="p">)</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre><span class="n">i</span> <span class="o">=</span> <span class="mf">1</span>
<span class="n">t</span> <span class="o">=</span> <span class="s">&#39;now&#39;</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span> <span class="s">&quot;insert into test_table (i, t) values (?, ?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span> <span class="p">)</span>
</pre></div>
</div>
<p>If KInterbasDB did not support weak parameter typing, string
parameters that the database engine is to interpret as &#8220;magic values&#8221;
would have to be rolled into the SQL statement in a separate operation
from the binding of the rest of the parameters, as in the first Python
snippet above. Implicit conversion of parameter values from strings
allows the consistency evident in the second snippet, which is both
more readable and more general.</p>
<p>It should be noted that KInterbasDB does not perform the conversion
from string itself. Instead, it passes that responsibility to the
database engine by changing the parameter metadata structure
dynamically at the last moment, then restoring the original state of
the metadata structure after the database engine has performed the
conversion.</p>
<p>A secondary benefit is that when one uses KInterbasDB to import large
amounts of data from flat files into the database, the incoming values
need not necessarily be converted to their proper Python types before
being passed to the database engine. Eliminating this intermediate
step may accelerate the import process considerably, although other
factors such as the chosen connection protocol and the deactivation of
indexes during the import are more consequential. For bulk import
tasks, the database engine&#8217;s external tables also deserve
consideration. External tables can be used to suck semi-structured
data from flat files directly into the relational database without the
intervention of an ad hoc conversion program.</p>
</div>
<div class="section" id="dynamic-type-translation">
<h3>Dynamic Type Translation<a class="headerlink" href="#dynamic-type-translation" title="Permalink to this headline">¶</a></h3>
<p>Dynamic type translators are conversion functions registered by the
Python programmer to transparently convert database field values to
and from their internal representation.</p>
<p>The client programmer can choose to ignore translators altogether, in
which case KInterbasDB will manage them behind the scenes. Otherwise,
the client programmer can use any of several <a class="reference internal" href="#included-translators"><em>standard type translators</em></a> included with KInterbasDB, register custom
translators, or set the translators to <cite>None</cite> to deal directly with
the KInterbasDB-internal representation of the data type. When
translators have been registered for a specific SQL data type, Python
objects on their way into a database field of that type will be passed
through the input translator before they are presented to the database
engine; values on their way out of the database into Python will be
passed through the corresponding output translator. Output and input
translation for a given type is usually implemented by two different
functions.</p>
</div>
<div class="section" id="specifics-of-the-dynamic-type-translation-api">
<h3>Specifics of the Dynamic Type Translation API<a class="headerlink" href="#specifics-of-the-dynamic-type-translation-api" title="Permalink to this headline">¶</a></h3>
<p>Translators are managed with next methods of <a title="kinterbasdb.Connection" class="reference internal" href="#kinterbasdb.Connection"><tt class="xref docutils literal"><span class="pre">Connection</span></tt></a>
and <a title="kinterbasdb.Cursor" class="reference internal" href="#kinterbasdb.Cursor"><tt class="xref docutils literal"><span class="pre">Cursor</span></tt></a>.</p>
<dl class="method">
<dt id="kinterbasdb.Connection.get_type_trans_in">
<!--[kinterbasdb.Connection.get_type_trans_in]--><tt class="descclassname">Connection.</tt><tt class="descname">get_type_trans_in</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.get_type_trans_in" title="Permalink to this definition">¶</a></dt>
<dd>Retrieves the inbound type translation map.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Connection.set_type_trans_in">
<!--[kinterbasdb.Connection.set_type_trans_in]--><tt class="descclassname">Connection.</tt><tt class="descname">set_type_trans_in</tt><big>(</big><em>trans_dict</em><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.set_type_trans_in" title="Permalink to this definition">¶</a></dt>
<dd>Changes the inbound type translation map.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Cursor.get_type_trans_in">
<!--[kinterbasdb.Cursor.get_type_trans_in]--><tt class="descclassname">Cursor.</tt><tt class="descname">get_type_trans_in</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Cursor.get_type_trans_in" title="Permalink to this definition">¶</a></dt>
<dd>Retrieves the inbound type translation map.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Cursor.set_type_trans_in">
<!--[kinterbasdb.Cursor.set_type_trans_in]--><tt class="descclassname">Cursor.</tt><tt class="descname">set_type_trans_in</tt><big>(</big><em>trans_dict</em><big>)</big><a class="headerlink" href="#kinterbasdb.Cursor.set_type_trans_in" title="Permalink to this definition">¶</a></dt>
<dd>Changes the inbound type translation map.</dd></dl>

<p>The <cite>set_type_trans_[in|out]</cite> methods accept a single argument: a mapping
of type name to translator. The <cite>get_type_trans[in|out]</cite> methods return
a copy of the translation table.</p>
<p><cite>Cursor`s inherit their `Connection</cite>&#8216;s translation settings, but can
override them without affecting the connection or other cursors
(much as subclasses can override the methods of their base classes).</p>
<p>The following code snippet installs an input translator for fixed
point types ( <cite>NUMERIC</cite>/ <cite>DECIMAL</cite> SQL types) into a connection:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">con</span><span class="o">.</span><span class="n">set_type_trans_in</span><span class="p">(</span> <span class="p">{</span><span class="s">&#39;FIXED&#39;</span><span class="p">:</span> <span class="n">fixed_input_translator_function</span><span class="p">}</span> <span class="p">)</span>
</pre></div>
</div>
<p>The following method call retrieves the type translation table for
<cite>con</cite>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">con</span><span class="o">.</span><span class="n">get_type_trans_in</span><span class="p">()</span>
</pre></div>
</div>
<p>The method call above would return a translation table (dictionary)
such as this:</p>
<div class="highlight-python"><pre>{
  'DATE': &lt;function date_conv_in at 0x00920648&gt;,
  'TIMESTAMP': &lt;function timestamp_conv_in at 0x0093E090&gt;,
  'FIXED': &lt;function &lt;lambda&gt; at 0x00962DB0&gt;,
  'TIME': &lt;function time_conv_in at 0x009201B0&gt;
}</pre>
</div>
<p>Notice that although the sample code registered only one type
translator, there are four listed in the mapping returned by the
<cite>get_type_trans_in</cite> method. By default, KInterbasDB uses dynamic type
translation to implement the conversion of <cite>DATE</cite>, <cite>TIME</cite>,
<cite>TIMESTAMP</cite>, <cite>NUMERIC</cite>, and <cite>DECIMAL</cite> values. For the source code
locations of KInterbasDB&#8217;s reference translators, see the <a class="reference internal" href="#included-translators"><em>table</em></a> in the next section.</p>
<p>In the sample above, a translator is registered under the key
<cite>&#8216;FIXED&#8217;</cite>, but Firebird has no SQL data type named <cite>FIXED</cite>. The
following table lists the names of the database engine&#8217;s SQL data
types in the left column, and the corresponding KInterbasDB-specific
key under which client programmers can register translators in the
right column.</p>
<p id="table-mapping-to-keys"><strong>Mapping of SQL Data Type Names to Translator Keys</strong></p>
<table border="1" class="docutils">
<colgroup>
<col width="37%" />
<col width="63%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">SQL Type(s)</th>
<th class="head">Translator Key</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>CHAR / VARCHAR</td>
<td><p class="first">&#8216;TEXT&#8217; for fields with charsets
<cite>NONE</cite>, <cite>OCTETS</cite>, or <cite>ASCII</cite></p>
<p class="last">&#8216;TEXT_UNICODE&#8217; for all other charsets</p>
</td>
</tr>
<tr><td>BLOB</td>
<td>&#8216;BLOB&#8217;</td>
</tr>
<tr><td>SMALLINT/INTEGER/BIGINT</td>
<td>&#8216;INTEGER&#8217;</td>
</tr>
<tr><td>FLOAT/ DOUBLE PRECISION</td>
<td>&#8216;FLOATING&#8217;</td>
</tr>
<tr><td>NUMERIC / DECIMAL</td>
<td>&#8216;FIXED&#8217;</td>
</tr>
<tr><td>DATE</td>
<td>&#8216;DATE&#8217;</td>
</tr>
<tr><td>TIME</td>
<td>&#8216;TIME&#8217;</td>
</tr>
<tr><td>TIMESTAMP</td>
<td>&#8216;TIMESTAMP&#8217;</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="module-kinterbasdb.typeconv_text_unicode">
<h3>Consequences of the Dynamic Type Translation in KInterbasDB<a class="headerlink" href="#module-kinterbasdb.typeconv_text_unicode" title="Permalink to this headline">¶</a></h3>
<p>Dynamic type translation haseliminated KInterbasDB&#8217;s dependency on
<tt class="xref docutils literal"><span class="pre">mx.DateTime</span></tt>. Although KInterbasDB will continue to use
<tt class="xref docutils literal"><span class="pre">mx.DateTime</span></tt> as its default date/time representation for the
sake of backward compatibility, dynamic type translation allows users
to conveniently deal with database date/time values in terms of the new
standard library module <cite>datetime</cite>, or any other representation they
care to write translators for.</p>
<p>Dynamic type translation also allows <cite>NUMERIC</cite>/ <cite>DECIMAL</cite> values to be
transparently represented as <tt class="xref docutils literal"><span class="pre">decimal.Decimal</span></tt> objects rather than
scaled integers, which is much more convenient. For backward
compatibility, <cite>NUMERIC</cite>/ <cite>DECIMAL</cite> values are still represented by
default as Python floats, and the older API based on the
<a title="kinterbasdb.Connection.precision_mode" class="reference external" href="python-db-api-compliance.html#kinterbasdb.Connection.precision_mode"><tt class="xref docutils literal"><span class="pre">precision_mode</span></tt></a> attribute is still present. However, all
of these representations are now implemented &#8220;under the hood&#8221; via
dynamic type translation.</p>
<p>Reference implementations of all of the translators discussed above
are provided with KInterbasDB, in these modules:</p>
<p id="included-translators"><strong>Reference Translators Included with KInterbasDB</strong></p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="38%" />
<col width="40%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">SQL Type(s)</th>
<th class="head">Python Type(s)</th>
<th class="head">Reference Implementation In Module</th>
</tr>
</thead>
<tbody valign="top">
<tr><td rowspan="4">NUMERIC/DECIMAL</td>
<td>float <em>(imprecise)</em> (default)</td>
<td>kinterbasdb.typeconv_fixed_stdlib</td>
</tr>
<tr><td>scaled <cite>int</cite> <em>(precise)</em></td>
<td>kinterbasdb.typeconv_fixed_stdlib</td>
</tr>
<tr><td><cite>fixedpoint.FixedPoint</cite> <em>(precise)</em></td>
<td>kinterbasdb.typeconv_fixed_fixedpoint</td>
</tr>
<tr><td><cite>decimal.Decimal</cite> <em>(precise)</em></td>
<td>kinterbasdb.typeconv_fixed_decimal</td>
</tr>
<tr><td rowspan="2">DATE/TIME/TIMESTAMP</td>
<td><cite>mx.DateTime</cite> (default)</td>
<td>kinterbasdb.typeconv_datetime_mx</td>
</tr>
<tr><td>Python 2.4+ <cite>datetime</cite></td>
<td>kinterbasdb.typeconv_datetime_stdlib</td>
</tr>
<tr><td>CHAR/VARCHAR (with
any character set
except NONE, OCTETS,
ASCII)</td>
<td><cite>unicode</cite></td>
<td>kinterbasdb.typeconv_text_unicode</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="writing-custom-translators">
<h3>Writing Custom Translators<a class="headerlink" href="#writing-custom-translators" title="Permalink to this headline">¶</a></h3>
<p>Below is a table that specifies the required argument and return value
signatures of input and output converters for the various translator
keys. Python&#8217;s native types map perfectly to <cite>&#8216;TEXT&#8217;</cite>,
<cite>&#8216;TEXT_UNICODE&#8217;</cite>, <cite>&#8216;BLOB&#8217;</cite>, <cite>&#8216;INTEGER&#8217;</cite>, and <cite>&#8216;FLOATING&#8217;</cite> types, so in
those cases the translator signatures are very simple. The signatures
for <cite>&#8216;FIXED&#8217;</cite>, <cite>&#8216;DATE&#8217;</cite>, <cite>&#8216;TIME&#8217;</cite>, and <cite>&#8216;TIMESTAMP&#8217;</cite> are not as simple
because Python (before 2.4) lacks native types to represent these
values with both precision <em>and</em> convenience. KInterbasDB handles
<cite>&#8216;FIXED&#8217;</cite> values internally as scaled integers; the date and time
types as tuples.</p>
<p>KInterbasDB itself uses translators implemented according to the rules
in the table below; the code for these reference translators can be
found in the Python modules named <cite>kinterbasdb.typeconv_*</cite> (see
the table in the previous section for details).</p>
<div class="section" id="signature-specifications-for-translators">
<h4>Signature Specifications for Translators<a class="headerlink" href="#signature-specifications-for-translators" title="Permalink to this headline">¶</a></h4>
<dl class="docutils">
<dt><strong>Translator Key &#8216;TEXT&#8217;</strong></dt>
<dd>For <cite>CHAR</cite> / <cite>VARCHAR</cite> fields with character sets <cite>NONE</cite>, <cite>OCTETS</cite>, or <cite>ASCII</cite></dd>
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd><p class="first">Args: a single Python <cite>str`ing argument (or `None</cite>)</p>
<p class="last">Returns: a single Python string</p>
</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd>Same signature as input translator, except that return value is not constrained.</dd>
<dt><strong>Translator Key &#8216;TEXT_UNICODE&#8217;</strong></dt>
<dd>For <cite>CHAR</cite> / <cite>VARCHAR</cite> fields with charsets  <strong>other</strong> than <cite>NONE</cite>, <cite>OCTETS</cite>, or <cite>ASCII</cite></dd>
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd><p class="first">Args: a single Python 2-tuple argument containing a Python <cite>unicode</cite> or <cite>str</cite> object
(or <cite>None</cite>) in the first element;  the database character set code in the second
element (the  tuple is of the form <cite>(val, dbCharacterSetCode)</cite>).</p>
<p>The database character set codes (which are integers) are  defined in
RDB$CHARACTER_SETS system table. The module <cite>kinterbasdb.typeconv_text_unicode</cite>
contains a dictionary named  <cite>DB_TO_PYTHON_ENCODING_MAP</cite> that maps database
character set codes to Python codec names.</p>
<p>For example, the database character set <cite>UNICODE_FSS</cite> has code <cite>3</cite>;
<cite>typeconv_text_unicode.DB_TO_PYTHON_ENCODING_MAP[3]</cite> is <cite>&#8216;utf_8&#8217;</cite>,
the name of a Python codec that can be passed to the <cite>encode</cite> / <cite>decode</cite> methods
of <cite>unicode</cite> / <cite>str</cite>.</p>
<p class="last">Returns: a Python <cite>str</cite> object containing the encoded representation of the incoming
value (typically computed via <cite>val.encode</cite>).</p>
</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd><p class="first">Args: a single Python 2-tuple argument containing a Python <cite>str</cite> object (or <cite>None</cite>)
in the first element; the database character set code in the second element
(the tuple is of the form <cite>(val, dbCharacterSetCode)</cite>). <cite>val</cite> contains the encoded
representation of the Unicode string.</p>
<p class="last">Returns: a Python <cite>unicode</cite> object containing the decoded representation
of the outgoing value (typically computed via <cite>val.decode</cite>).</p>
</dd>
</dl>
<p><strong>Translator Key &#8216;BLOB&#8217;</strong></p>
<dl class="docutils">
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd>By default, same signature as that of &#8216;TEXT&#8217;. A special case was introduced in
KInterbasDB 3.2 to allow for <a class="reference internal" href="#blob-conversion"><em>streaming blob handling</em></a>.</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd>Same signature as input translator, except that return value is not constrained.</dd>
</dl>
<p><strong>Translator Key &#8216;INTEGER&#8217;</strong></p>
<dl class="docutils">
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd><p class="first">Args: a single Python <cite>int</cite> argument (or <cite>None</cite>)</p>
<p class="last">Returns: a single Python <cite>int</cite> (or <cite>long</cite>, if the number too large to fit in
an <cite>int</cite>)</p>
</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd>Same signature as input translator, except that return value is not constrained.</dd>
</dl>
<p><strong>Translator Key &#8216;FLOATING&#8217;</strong></p>
<dl class="docutils">
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd><p class="first">Args: a single Python <cite>float</cite> argument (or <cite>None</cite>)</p>
<p class="last">Returns: a single Python <cite>float</cite></p>
</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd>Same signature as input translator, except that return value is not constrained.</dd>
</dl>
<p><strong>Translator Key &#8216;FIXED&#8217;</strong></p>
<dl class="docutils">
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd><p class="first">Args: a single Python 2-tuple argument containing a scaled Python
integer in the first element and the scale factor in the second
element (the tuple is of the form <cite>(val, scale)</cite>).</p>
<p class="last">Returns: a single Python integer, scaled appropriately</p>
</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd>Same signature as input translator, except that return value is not constrained.</dd>
</dl>
<p><strong>Translator Key &#8216;DATE&#8217;</strong></p>
<dl class="docutils">
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd><p class="first">Args: an instance of the chosen date type (such as Python 2.4+&#8217;s <cite>datetime.date</cite>)
or <cite>None</cite></p>
<p class="last">Returns: a single Python 3-tuple of the form <cite>(year, month, day)</cite></p>
</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd><p class="first">Args: a single Python 3-tuple of the form <cite>(year, month, day)</cite> (or <cite>None</cite> if
the database field was <cite>NULL</cite>)</p>
<p class="last">Return value is not constrained.</p>
</dd>
</dl>
<p><strong>Translator Key &#8216;TIME&#8217;</strong></p>
<dl class="docutils">
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd><p class="first">Args: an instance of the chosen time type (such as Python 2.4+&#8217;s <cite>datetime.time</cite>)
or <cite>None</cite></p>
<p class="last">Returns: a single Python 4-tuple of the form <cite>(hour, minute, second, microseconds)</cite></p>
</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd><p class="first">Args: a single Python 4-tuple of the form <cite>(hour, minute, second, microseconds)</cite>
(or <cite>None</cite> if the database field was <cite>NULL</cite>).</p>
<p class="last">Return value is not constrained.</p>
</dd>
</dl>
<p><strong>Translator Key &#8216;TIMESTAMP&#8217;</strong></p>
<dl class="docutils">
<dt><em>Input Translator Argument / Return Value Signature:</em></dt>
<dd><p class="first">Args: an instance of the chosen time type (such as Python 2.4+&#8217;s <cite>datetime.datetime</cite>)
or <cite>None</cite></p>
<p class="last">Returns: a single Python 7-tuple of the form <cite>(year, month, day, hour, minute,
second, microseconds)</cite></p>
</dd>
<dt><em>Output Translator Signature:</em></dt>
<dd><p class="first">Args: a single Python 7-tuple of the form <cite>(year, month, day, hour, minute, second,
microseconds)</cite>. (or <cite>None</cite> if the database field was <cite>NULL</cite>).</p>
<p class="last">Return value is not constrained.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="example-programs">
<h3>Example Programs<a class="headerlink" href="#example-programs" title="Permalink to this headline">¶</a></h3>
<p>DATE/TIME/TIMESTAMP</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">datetime</span> <span class="c"># Python 2.3 standard library module</span>

<span class="kn">import</span> <span class="nn">kinterbasdb</span>
<span class="kn">import</span> <span class="nn">kinterbasdb.typeconv_datetime_stdlib</span> <span class="kn">as</span> <span class="nn">tc_dt</span>

<span class="k">def</span> <span class="nf">connect</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">      This wrapper around kinterbasdb.connect creates connections that use</span>
<span class="sd">    the datetime module (which entered the standard library in Python 2.3)</span>
<span class="sd">    for both input and output of DATE, TIME, and TIMESTAMP database fields.</span>
<span class="sd">      This wrapper simply registers kinterbasdb&#39;s official date/time</span>
<span class="sd">    translators for the datetime module, which reside in the</span>
<span class="sd">    kinterbasdb.typeconv_datetime_stdlib module.</span>
<span class="sd">      An equivalent set of translators for mx.DateTime (which kinterbasdb</span>
<span class="sd">    uses by default for backward compatibility) resides in the</span>
<span class="sd">    kinterbasdb.typeconv_datetime_mx module.</span>
<span class="sd">      Note that because cursors inherit their connection&#39;s dynamic type</span>
<span class="sd">    translation settings, cursors created upon connections returned by this</span>
<span class="sd">    function will also use the datetime module.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="n">con</span><span class="o">.</span><span class="n">set_type_trans_in</span><span class="p">({</span>
        <span class="s">&#39;DATE&#39;</span><span class="p">:</span>             <span class="n">tc_dt</span><span class="o">.</span><span class="n">date_conv_in</span><span class="p">,</span>
        <span class="s">&#39;TIME&#39;</span><span class="p">:</span>             <span class="n">tc_dt</span><span class="o">.</span><span class="n">time_conv_in</span><span class="p">,</span>
        <span class="s">&#39;TIMESTAMP&#39;</span><span class="p">:</span>        <span class="n">tc_dt</span><span class="o">.</span><span class="n">timestamp_conv_in</span><span class="p">,</span>
        <span class="p">})</span>

    <span class="n">con</span><span class="o">.</span><span class="n">set_type_trans_out</span><span class="p">({</span>
        <span class="s">&#39;DATE&#39;</span><span class="p">:</span>             <span class="n">tc_dt</span><span class="o">.</span><span class="n">date_conv_out</span><span class="p">,</span>
        <span class="s">&#39;TIME&#39;</span><span class="p">:</span>             <span class="n">tc_dt</span><span class="o">.</span><span class="n">time_conv_out</span><span class="p">,</span>
        <span class="s">&#39;TIMESTAMP&#39;</span><span class="p">:</span>        <span class="n">tc_dt</span><span class="o">.</span><span class="n">timestamp_conv_out</span><span class="p">,</span>
        <span class="p">})</span>

    <span class="k">return</span> <span class="n">con</span>


<span class="k">def</span> <span class="nf">_test</span><span class="p">():</span>
    <span class="n">con</span> <span class="o">=</span> <span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>
    <span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

    <span class="c"># Retrieve the current timestamp of the database server.</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select current_timestamp from rdb$database&quot;</span><span class="p">)</span>
    <span class="n">curStamp</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mf">0</span><span class="p">]</span>
    <span class="k">print</span> <span class="s">&#39;The type of curStamp is&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="p">(</span><span class="n">curStamp</span><span class="p">)</span>
    <span class="k">print</span> <span class="s">&#39;curStamp is&#39;</span><span class="p">,</span> <span class="n">curStamp</span>

    <span class="c"># Create a test table with a single TIMESTAMP column.</span>
    <span class="n">con</span><span class="o">.</span><span class="n">execute_immediate</span><span class="p">(</span><span class="s">&quot;recreate table test_stamp (a timestamp)&quot;</span><span class="p">)</span>
    <span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

    <span class="c"># Insert a timestamp into the database, then retrieve it.</span>
    <span class="n">py23StandardLibTimestamp</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into test_stamp values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">py23StandardLibTimestamp</span><span class="p">,))</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test_stamp&quot;</span><span class="p">)</span>
    <span class="n">curStamp</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mf">0</span><span class="p">]</span>
    <span class="k">print</span> <span class="s">&#39;The type of curStamp is&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="p">(</span><span class="n">curStamp</span><span class="p">)</span>
    <span class="k">print</span> <span class="s">&#39;curStamp is&#39;</span><span class="p">,</span> <span class="n">curStamp</span>


<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">_test</span><span class="p">()</span>
</pre></div>
</div>
<p>Sample output:</p>
<div class="highlight-python"><pre>The type of curStamp is
curStamp is 2003-05-20 03:55:42
The type of stamp is
stamp is 2003-05-20 03:55:42</pre>
</div>
</div>
<div class="section" id="module-kinterbasdb.typeconv_24plus">
<h3>Deferred Loading of Dynamic Type Translators<a class="headerlink" href="#module-kinterbasdb.typeconv_24plus" title="Permalink to this headline">¶</a></h3>
<p>KInterbasDB has existed since 1998, five years before the <cite>datetime</cite> module was
available in the Python standard library. Therefore, KInterbasDB&#8217;s default
representation for date and time values is the <cite>mx.DateTime</cite> module. This representation
is recommended by the Python DB API 2.0 Specification, and was an entirely sensible
choice during the many years before the advent of the standard library <cite>datetime</cite> module.</p>
<p>Now that the <cite>datetime</cite> module is available in the standard library, many KInterbasDB
users prefer it to <cite>mx.DateTime</cite>. For the sake of backward-compatibility, it is
necessary to continue to use <cite>mx.DateTime</cite> by default, but it&#8217;s both burdensome and
wasteful to import <cite>mx.DateTime</cite> in programs that don&#8217;t use it. To address this
situation, KInterbasDB&#8217;s type translation initialization code defers the choice of
a default set of translators until the <a title="kinterbasdb.init" class="reference internal" href="#kinterbasdb.init"><tt class="xref docutils literal"><span class="pre">kinterbasdb.init()</span></tt></a> function is called. A client
program can explicitly call <cite>kinterbasdb.init</cite> to forestall the import of <cite>mx.DateTime</cite>.</p>
<dl class="function">
<dt id="kinterbasdb.init">
<!--[kinterbasdb.init]--><tt class="descclassname">kinterbasdb.</tt><tt class="descname">init</tt><big>(</big><em>type_conv=200</em><big>)</big><a class="headerlink" href="#kinterbasdb.init" title="Permalink to this definition">¶</a></dt>
<dd><p>
<span class="versionmodified">Changed in version 3.3.</span></p>
<p>Takes a keyword argument <cite>type_conv</cite>, which controls KInterbasDB&#8217;s initial choice
of type translators. <cite>type_conv</cite> can be either an integer or an object that has all
of the attributes named in <tt class="xref docutils literal"><span class="pre">kinterbasdb.BASELINE_TYPE_TRANSLATION_FACILITIES</span></tt>
(an example of such an object is the module <tt class="xref docutils literal"><span class="pre">kinterbasdb.typeconv_backcompat</span></tt>).
If <cite>type_conv</cite> is an integer, it will cause KInterbasDB to use one of the following
predefined type translator configurations:</p>
<table border="1" class="docutils" id="typeconv-values">
<colgroup>
<col width="24%" />
<col width="76%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head"><cite>type_conv</cite> code</th>
<th class="head">Resulting translator configuration</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>0</td>
<td><p class="first">Minimal type translators that represent date/time values as
tuples and fixed point values as either floats or scaled
integers, depending on the value of the deprecated
<cite>Connection.precision_mode</cite> attribute.</p>
<p>Unicode values are <strong>not</strong> encoded or decoded automatically.</p>
<p class="last">Implemented by the <tt class="xref docutils literal"><span class="pre">kinterbasdb.typeconv_naked</span></tt> module.</p>
</td>
</tr>
<tr><td>1</td>
<td><p class="first">Backward-compatible type translators that represent date/time
values via the <cite>mx.DateTime</cite> module and fixed point values as
either floats or scaled integers, depending on the value of the
deprecated <cite>Connection.precision_mode</cite> attribute.</p>
<p>Unicode values are <strong>not</strong> encoded or decoded automatically.</p>
<p>Implemented by the <tt class="xref docutils literal"><span class="pre">kinterbasdb.typeconv_backcompat</span></tt></p>
<p class="last">This configuration, perfectly mimics the type translation
behavior of KInterbasDB 3.0.</p>
</td>
</tr>
<tr><td>100</td>
<td><p class="first">This translator configuration, which is intended for use with
Python 2.4 and later, represents date/time values via the
standard library module <cite>datetime</cite> and fixed point values via
the third-party <cite>fixedpoint</cite> module.</p>
<p>Unicode values <strong>are</strong> encoded and decoded automatically.</p>
<p class="last">Implemented by the <tt class="xref docutils literal"><span class="pre">kinterbasdb.typeconv_23plus</span></tt> module.</p>
</td>
</tr>
<tr><td>200 (the default)</td>
<td><p class="first">This translator configuration represents date/time values via
the standard library module <cite>datetime</cite> and fixed point values
via the <cite>decimal</cite> module. The <cite>decimal</cite> module entered the
standard library in Python 2.4, but can also be manually
installed in Python 2.3.</p>
<p>Unicode values <strong>are</strong> encoded and decoded automatically.</p>
<p class="last">Implemented by the <tt class="xref docutils literal"><span class="pre">kinterbasdb.typeconv_24plus</span></tt> module.</p>
</td>
</tr>
<tr><td>199</td>
<td><p class="first">This translator configuration is exactly like <cite>200</cite>, except
that it represents fixed point values as <cite>float</cite> objects in
order to avoid the substantial memory overhead of the <cite>decimal</cite>
module.</p>
<p><em>It is fundamentally imprecise to represent fixed point values
in floating point</em>, so this convenience code is intended
<em>solely</em> for users who wish to use <cite>datetime</cite> instead
of <cite>mx.DateTime</cite>, but don&#8217;t care about fixed point values and
don&#8217;t want to suffer the memory overhead of the <cite>decimal</cite>
module.</p>
<p class="last">Implemented by the <tt class="xref docutils literal"><span class="pre">kinterbasdb.typeconv_23plus_lowmem</span></tt></p>
</td>
</tr>
<tr><td><p class="first">300 (the ideal for
Firebird 2.1 and
later)</p>
<p class="last">New in v3.3</p>
</td>
<td>This translator configuration is identical to 200, but textual
blobs are handled in the same way as other textual types, so
unicode encoding/decoding is performed automagically. When
converting in the input direction, this doesn&#8217;t work with any
Firebird version prior to 2.1, because the Firebird API doesn&#8217;t
make the blob&#8217;s character set ID available.</td>
</tr>
</tbody>
</table>
<p>These integer type conversion codes are defined <em>solely</em> for convenience. The same
functionality is available via the object variant of <cite>type_conv</cite>, but setting it up
is more laborious for typical translator configurations.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The default <cite>type_conv</cite> value was changed from 1 to 200 in version 3.3 !</p>
</div>
</dd></dl>

</div>
<div class="section" id="deferred-loading-backward-compatibility-issues">
<h3>Deferred Loading: Backward Compatibility Issues<a class="headerlink" href="#deferred-loading-backward-compatibility-issues" title="Permalink to this headline">¶</a></h3>
<p>The deferred type translator loading scheme introduced in KInterbasDB
3.1 goes to great lengths to maintain backward compatibility. If the
client programmer does not call <a title="kinterbasdb.init" class="reference internal" href="#kinterbasdb.init"><tt class="xref docutils literal"><span class="pre">kinterbasdb.init()</span></tt></a>, KInterbasDB will
implicitly initialize itself in a backward-compatible manner (
<cite>type_conv=1</cite>) the first time one of its public functions is called or
one of its public classes is instantiated.</p>
<p>The only known backward incompatibility is this: the DB API type
comparison singleton <a title="kinterbasdb.DATETIME" class="reference external" href="python-db-api-compliance.html#kinterbasdb.DATETIME"><tt class="xref docutils literal"><span class="pre">DATETIME</span></tt></a> will not compare equal
to any type until the <cite>kinterbasdb.init()</cite> function has been called (whether
explicitly or implicitly). After <cite>kinterbasdb.init()</cite> has been called,
<cite>DATETIME</cite> will compare equal to the date, time, and timestamp types
that were loaded.</p>
<p>This issue should affect hardly any existing KInterbasDB-based programs.</p>
</div>
<div class="section" id="deferred-loading-example">
<h3>Deferred Loading Example<a class="headerlink" href="#deferred-loading-example" title="Permalink to this headline">¶</a></h3>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">datetime</span><span class="o">,</span> <span class="nn">decimal</span><span class="o">,</span> <span class="nn">os.path</span><span class="o">,</span> <span class="nn">string</span><span class="o">,</span> <span class="nn">sys</span>

<span class="kn">import</span> <span class="nn">kinterbasdb</span>
<span class="n">kinterbasdb</span><span class="o">.</span><span class="n">init</span><span class="p">(</span><span class="n">type_conv</span><span class="o">=</span><span class="mf">200</span><span class="p">)</span>
<span class="c"># This program never imports mx.DateTime:</span>
<span class="k">assert</span> <span class="s">&#39;mx&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span>

<span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="n">dbFilename</span> <span class="o">=</span> <span class="s">r&#39;D:\temp\test-deferred.firebird&#39;</span>
    <span class="n">prepareTestDatabase</span><span class="p">(</span><span class="n">dbFilename</span><span class="p">)</span>

    <span class="c"># Connect with character set UNICODE_FSS, to match the default character</span>
    <span class="c"># set of the test database.</span>
    <span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="n">dbFilename</span><span class="p">,</span>
        <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">,</span> <span class="n">charset</span><span class="o">=</span><span class="s">&#39;UNICODE_FSS&#39;</span>
      <span class="p">)</span>
    <span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

    <span class="c"># Create a test table.</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">        create table test (</span>
<span class="s">          a numeric(18,2),</span>
<span class="s">          b date,</span>
<span class="s">          c time,</span>
<span class="s">          d timestamp,</span>
<span class="s">          e varchar(50), /* Defaults to character set UNICODE_FSS. */</span>
<span class="s">          f varchar(50), /* Defaults to character set UNICODE_FSS. */</span>
<span class="s">          g varchar(50) character set ASCII</span>
<span class="s">        )</span>
<span class="s">      &quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

    <span class="c"># Create an input value for each field in the test table.</span>
    <span class="n">aIn</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s">&#39;4.53&#39;</span><span class="p">)</span>

    <span class="c"># Notice that the DB API date/time constructors in kinterbasdb generate</span>
    <span class="c"># datetime-based objects instead of mx-based objects because of our earlier</span>
    <span class="c"># call to kinterbasdb.init(type_conv=200).</span>
    <span class="n">bIn</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">Date</span><span class="p">(</span><span class="mf">2004</span><span class="p">,</span><span class="mf">1</span><span class="p">,</span><span class="mf">4</span><span class="p">)</span>
    <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">bIn</span><span class="p">,</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">)</span>
    <span class="n">cIn</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">Time</span><span class="p">(</span><span class="mf">16</span><span class="p">,</span><span class="mf">27</span><span class="p">,</span><span class="mf">59</span><span class="p">)</span>
    <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">cIn</span><span class="p">,</span> <span class="n">datetime</span><span class="o">.</span><span class="n">time</span><span class="p">)</span>
    <span class="n">dIn</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">Timestamp</span><span class="p">(</span><span class="mf">2004</span><span class="p">,</span><span class="mf">1</span><span class="p">,</span><span class="mf">4</span><span class="p">,</span> <span class="mf">16</span><span class="p">,</span><span class="mf">27</span><span class="p">,</span><span class="mf">59</span><span class="p">)</span>
    <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">dIn</span><span class="p">,</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">)</span>

    <span class="n">eIn</span> <span class="o">=</span> <span class="s">u&#39;A unicod</span><span class="se">\u2211</span><span class="s"> object stored in a Unicode field.&#39;</span>
    <span class="n">fIn</span> <span class="o">=</span> <span class="s">&#39;A str object stored in a Unicode field.&#39;</span>
    <span class="n">gIn</span> <span class="o">=</span> <span class="s">&#39;A str object stored in an ASCII field.&#39;</span>

    <span class="k">print</span> <span class="s">&#39;-&#39;</span> <span class="o">*</span> <span class="mf">70</span>
    <span class="n">inputValues</span> <span class="o">=</span> <span class="p">(</span><span class="n">aIn</span><span class="p">,</span> <span class="n">bIn</span><span class="p">,</span> <span class="n">cIn</span><span class="p">,</span> <span class="n">dIn</span><span class="p">,</span> <span class="n">eIn</span><span class="p">,</span> <span class="n">fIn</span><span class="p">,</span> <span class="n">gIn</span><span class="p">)</span>
    <span class="n">reportValues</span><span class="p">(</span><span class="s">&#39;In&#39;</span><span class="p">,</span> <span class="n">inputValues</span><span class="p">)</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into test values (?,?,?,?,?,?,?)&quot;</span><span class="p">,</span> <span class="n">inputValues</span><span class="p">)</span>
    <span class="k">print</span> <span class="s">&#39;-&#39;</span> <span class="o">*</span> <span class="mf">70</span>
    <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select a,b,c,d,e,f,g from test&quot;</span><span class="p">)</span>
    <span class="p">(</span><span class="n">aOut</span><span class="p">,</span> <span class="n">bOut</span><span class="p">,</span> <span class="n">cOut</span><span class="p">,</span> <span class="n">dOut</span><span class="p">,</span> <span class="n">eOut</span><span class="p">,</span> <span class="n">fOut</span><span class="p">,</span> <span class="n">gOut</span><span class="p">)</span> <span class="o">=</span> <span class="n">outputValues</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
    <span class="n">reportValues</span><span class="p">(</span><span class="s">&#39;Out&#39;</span><span class="p">,</span> <span class="n">outputValues</span><span class="p">)</span>
    <span class="k">print</span> <span class="s">&#39;-&#39;</span> <span class="o">*</span> <span class="mf">70</span>

    <span class="c"># Notice that all values made the journey to and from the database intact.</span>
    <span class="k">assert</span> <span class="n">inputValues</span> <span class="o">==</span> <span class="n">outputValues</span>

<span class="k">def</span> <span class="nf">reportValues</span><span class="p">(</span><span class="n">direction</span><span class="p">,</span> <span class="n">values</span><span class="p">):</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">val</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">values</span><span class="p">,</span> <span class="n">string</span><span class="o">.</span><span class="n">ascii_lowercase</span><span class="p">[:</span><span class="nb">len</span><span class="p">(</span><span class="n">values</span><span class="p">)]):</span>
        <span class="n">varName</span> <span class="o">=</span> <span class="n">c</span> <span class="o">+</span> <span class="n">direction</span>
        <span class="k">print</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s"> has type </span><span class="si">%s</span><span class="s">, value</span><span class="se">\n</span><span class="s">  </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">varName</span><span class="p">,</span> <span class="nb">type</span><span class="p">(</span><span class="n">val</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">val</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">prepareTestDatabase</span><span class="p">(</span><span class="n">dbFilename</span><span class="p">):</span>
    <span class="c"># Delete the test database if an old copy is already present.</span>
    <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">dbFilename</span><span class="p">):</span>
        <span class="n">conOld</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="n">dbFilename</span><span class="p">,</span>
            <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span>
          <span class="p">)</span>
        <span class="n">conOld</span><span class="o">.</span><span class="n">drop_database</span><span class="p">()</span>
    <span class="c"># Create the test database afresh.</span>
    <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">create_database</span><span class="p">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">          create database &#39;</span><span class="si">%s</span><span class="s">&#39;</span>
<span class="s">          user &#39;sysdba&#39; password &#39;masterkey&#39;</span>
<span class="s">          default character set UNICODE_FSS</span>
<span class="s">        &quot;&quot;&quot;</span> <span class="o">%</span> <span class="n">dbFilename</span>
      <span class="p">)</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">test</span><span class="p">()</span>
</pre></div>
</div>
<p>Program output:</p>
<div class="highlight-python"><pre>----------------------------------------------------------------------
aIn has type , value
  Decimal("4.53")
bIn has type , value
  datetime.date(2004, 1, 4)
cIn has type , value
  datetime.time(16, 27, 59)
dIn has type , value
  datetime.datetime(2004, 1, 4, 16, 27, 59)
eIn has type , value
  u'A unicod\u2211 object stored in a Unicode field.'
fIn has type , value
  'A str object stored in a Unicode field.'
gIn has type , value
  'A str object stored in an ASCII field.'
----------------------------------------------------------------------
aOut has type , value
  Decimal("4.53")
bOut has type , value
  datetime.date(2004, 1, 4)
cOut has type , value
  datetime.time(16, 27, 59)
dOut has type , value
  datetime.datetime(2004, 1, 4, 16, 27, 59)
eOut has type , value
  u'A unicod\u2211 object stored in a Unicode field.'
fOut has type , value
  u'A str object stored in a Unicode field.'
gOut has type , value
  u'A str object stored in an ASCII field.'
----------------------------------------------------------------------</pre>
</div>
<p><em>Notes about Unicode handling in the example above:</em></p>
<p>Upon input, the Python <cite>unicode</cite> object <cite>eIn</cite> was transparently
encoded for storage in database field <cite>TEST.E</cite> (a <cite>VARCHAR</cite> field with
character set <cite>UNICODE_FSS</cite> (that is, UTF-8)). Upon output, the
<cite>UNICODE_FSS</cite> value in <cite>TEST.E</cite> was decoded transparently into the
Python <cite>unicode</cite> object <cite>eOut</cite>.</p>
<p><cite>TEST.F</cite> accepted a Python <cite>str</cite> object even though it&#8217;s a Unicode
field. The output value <cite>fOut</cite> is a Python <cite>unicode</cite> object rather
than a <cite>str</cite>.</p>
<p>Although <cite>TEST.G</cite> is an <cite>ASCII</cite> field, and the input value <cite>gIn</cite> is a
<cite>str</cite>, the output value <cite>gOut</cite> is a <cite>unicode</cite> object. This is because
the connection&#8217;s charset is <cite>UNICODE_FSS</cite>, and Firebird tries to
convert every retrieved value to match that character set.</p>
</div>
<div class="section" id="positional-dymanic-type-translation">
<h3>Positional Dymanic Type Translation<a class="headerlink" href="#positional-dymanic-type-translation" title="Permalink to this headline">¶</a></h3>
<p>All forms of dynamic type translation discussed so far have used the
<em>type</em> of the database field as the basis for selecting a translator.
KInterbasDB 3.2 also allows the client programmer to control
translator selection on the basis of a field&#8217;s <em>position</em> within a
<cite>Cursor</cite>. Translator selection based on database field type is called
&#8221; <em>typal</em> translation&#8221;, while selection based on position is called &#8221;
<em>positional</em> translation&#8221;.</p>
<p>Positional translation can be enabled at the <cite>Cursor</cite> level by
including zero-based integer keys in the dictionary passed to
<cite>Cursor.set_type_trans[in|out]</cite>. Consider the following example
program:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;D:\temp\test-20.firebird&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span>
  <span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table test(a int, b int, c int, d int, e float)&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into test values (?,?,?,?,?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="mf">1</span><span class="p">,</span> <span class="mf">2</span><span class="p">,</span> <span class="mf">3</span><span class="p">,</span> <span class="mf">4</span><span class="p">,</span> <span class="mf">5.0</span><span class="p">))</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select a,b,c,d,e from test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Before translator modifications, output row is:&#39;</span>
<span class="k">print</span> <span class="s">&#39; &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">set_type_trans_out</span><span class="p">({</span>
    <span class="s">&#39;INTEGER&#39;</span><span class="p">:</span>  <span class="k">lambda</span> <span class="n">i</span><span class="p">:</span> <span class="n">i</span> <span class="o">*</span> <span class="mf">10</span><span class="p">,</span>
    <span class="mf">1</span><span class="p">:</span>          <span class="k">lambda</span> <span class="n">i</span><span class="p">:</span> <span class="n">i</span> <span class="o">*</span> <span class="mf">100</span><span class="p">,</span>
    <span class="mf">3</span><span class="p">:</span>          <span class="k">lambda</span> <span class="n">i</span><span class="p">:</span> <span class="n">i</span> <span class="o">*</span> <span class="mf">1000</span>
  <span class="p">})</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select a,b,c,d,e from test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;After translator modifications, output row is:&#39;</span>
<span class="k">print</span> <span class="s">&#39; &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
</pre></div>
</div>
<p>Program output:</p>
<div class="highlight-python"><pre>Before translator modifications, output row is:
  (1, 2, 3, 4, 5.0)
After translator modifications, output row is:
  (10, 200, 30, 4000, 5.0)</pre>
</div>
<p>The <cite>cur.set_type_trans_out</cite> call in the example program specifies
that integer values retrieved by <cite>cur</cite> should be multiplied by <cite>10</cite>,
then overrides that setting for specific columns: the value in the
second column (position <cite>1</cite>) is multiplied by <cite>100</cite>, while the value
in the fourth column (position <cite>3</cite>) is multiplied by <cite>1000</cite>.</p>
<p>KInterbasDB uses a cascading method of translator selection, listed
below in order from highest to lowest precedence:</p>
<ul class="simple">
<li><em>Positional</em> translation settings, which can only be activated at
the <cite>Cursor</cite> level, take precedence over <em>typal</em> translation settings.</li>
<li><cite>Cursor</cite>-level translation settings take precedence over
<cite>Connection</cite>-level settings.</li>
<li><cite>Connection</cite>-level translation settings take precedence over the
module-level defaults.</li>
<li>The module-level defaults are established by the call to
<a title="kinterbasdb.init" class="reference internal" href="#kinterbasdb.init"><tt class="xref docutils literal"><span class="pre">kinterbasdb.init()</span></tt></a>. If the client programmer does not call
<a title="kinterbasdb.init" class="reference internal" href="#kinterbasdb.init"><tt class="xref docutils literal"><span class="pre">kinterbasdb.init()</span></tt></a> explicitly, KInterbasDB&#8217;s internals will do so
implicitly.</li>
</ul>
</div>
<div class="section" id="database-arrays">
<h3>Database Arrays<a class="headerlink" href="#database-arrays" title="Permalink to this headline">¶</a></h3>
<p>KInterbasDB converts database arrays <em>from</em> Python sequences (except
strings) on input; <em>to</em> Python lists on output. On input, the Python
sequence must be nested appropriately if the array field is multi-
dimensional, and the incoming sequence must not fall short of its
maximum possible length (it will not be &#8220;padded&#8221; implicitly&#8211;see
below). On output, the lists will be nested if the database array has
multiple dimensions.</p>
<p>Database arrays have no place in a purely relational data model, which
requires that data values be <em>atomized</em> (that is, every value stored
in the database must be reduced to elementary, non-decomposable
parts). The Firebird implementation of database arrays, like that
of most relational database engines that support this data type,
is fraught with limitations.</p>
<p>Database arrays are of fixed size, with a predeclared number of
dimensions (max. 16) and number of elements per dimension. Individual array
elements cannot be set to <cite>NULL</cite> / <cite>None</cite>, so the mapping between
Python lists (which have dynamic length and are therefore <em>not</em>
normally &#8220;padded&#8221; with dummy values) and non-trivial database arrays
is clumsy.</p>
<p>Stored procedures cannot have array parameters.</p>
<p>Finally, many interface libraries, GUIs, and even the isql command
line utility do not support database arrays.</p>
<p>In general, it is preferable to avoid using database arrays unless you
have a compelling reason.</p>
<p><strong>Example Program</strong></p>
<p>The following program inserts an array (nested Python list) into a
single database field, then retrieves it.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">execute_immediate</span><span class="p">(</span><span class="s">&quot;recreate table array_table (a int[3,4])&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">arrayIn</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">[</span><span class="mf">1</span><span class="p">,</span> <span class="mf">2</span><span class="p">,</span> <span class="mf">3</span><span class="p">,</span> <span class="mf">4</span><span class="p">],</span>
    <span class="p">[</span><span class="mf">5</span><span class="p">,</span> <span class="mf">6</span><span class="p">,</span> <span class="mf">7</span><span class="p">,</span> <span class="mf">8</span><span class="p">],</span>
    <span class="p">[</span><span class="mf">9</span><span class="p">,</span><span class="mf">10</span><span class="p">,</span><span class="mf">11</span><span class="p">,</span><span class="mf">12</span><span class="p">]</span>
  <span class="p">]</span>

<span class="k">print</span> <span class="s">&#39;arrayIn:  </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">arrayIn</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into array_table values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">arrayIn</span><span class="p">,))</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select a from array_table&quot;</span><span class="p">)</span>
<span class="n">arrayOut</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mf">0</span><span class="p">]</span>
<span class="k">print</span> <span class="s">&#39;arrayOut: </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">arrayOut</span>

<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
</pre></div>
</div>
<p>Output:</p>
<div class="highlight-python"><pre>arrayIn:  [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
arrayOut: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]</pre>
</div>
</div>
<div class="section" id="blobs">
<span id="blob-conversion"></span><h3>Blobs<a class="headerlink" href="#blobs" title="Permalink to this headline">¶</a></h3>
<p>KInterbasDB supports the insertion and retrieval of blobs either
wholly in memory (&#8220;materialized mode&#8221;) or in chunks (&#8220;streaming mode&#8221;)
to reduce memory usage when handling large blobs. The default handling
mode is &#8220;materialized&#8221;; the &#8220;streaming&#8221; method is selectable via a
special case of Dynamic Type Translation.</p>
<p>In <strong>materialized</strong> mode, input and output blobs are represented as
Python <cite>str</cite> objects, with the result that the entirety of each blob&#8217;s
contents is loaded into memory. Unfortunately, flaws in the database
engine&#8217;s C API <a class="reference external" href="http://sourceforge.net/forum/forum.php?thread_id=1299756&amp;forum_id=30917">prevent</a> automatic Unicode conversion from
applying to textual blobs in the way it applies to Unicode <cite>CHAR</cite> and
<cite>VARCHAR</cite> fields in any Firebird version prior to version 2.1.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">KInterbasDB 3.3 introduces new <a class="reference internal" href="#typeconv-values"><em>type_conv mode 300</em></a> that enables automatic type conversion for textual
blobs when you&#8217;re working with Firebird 2.1 and newer.</p>
</div>
<p>In <strong>streaming</strong> mode, any Python &#8220;file-like&#8221; object is acceptable as
input for a blob parameter. Obvious examples of such objects are
instances of <tt class="xref docutils literal"><span class="pre">file</span></tt> or <tt class="xref docutils literal"><span class="pre">StringIO</span></tt>. Each output blob is represented by
a <a title="kinterbasdb.BlobReader" class="reference internal" href="#kinterbasdb.BlobReader"><tt class="xref docutils literal"><span class="pre">kinterbasdb.BlobReader</span></tt></a> object.</p>
<dl class="class">
<dt id="kinterbasdb.BlobReader">
<!--[kinterbasdb.BlobReader]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">BlobReader</tt><a class="headerlink" href="#kinterbasdb.BlobReader" title="Permalink to this definition">¶</a></dt>
<dd><p>BlobReader is a &#8220;file-like&#8221; class, so it acts much like a <cite>file</cite>
instance opened in <cite>rb</cite> mode.</p>
<p><cite>BlobReader</cite> adds one method not found in the &#8220;file-like&#8221; interface:</p>
<dl class="method">
<dt id="kinterbasdb.BlobReader.chunks">
<!--[kinterbasdb.BlobReader.chunks]--><tt class="descname">chunks</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.BlobReader.chunks" title="Permalink to this definition">¶</a></dt>
<dd><p>Takes a single integer parameter that specifies the number of bytes
to retrieve in each chunk (the final chunk may be smaller).</p>
<p>For example, if the size of the blob is <cite>50000000</cite> bytes,
<cite>BlobReader.chunks(2**20)</cite> will return <cite>47</cite> one-megabyte chunks, and
a smaller final chunk of <cite>716928</cite> bytes.</p>
</dd></dl>

</dd></dl>

<p>Due to the combination of CPython&#8217;s deterministic finalization with
careful programming in KInterbasDB&#8217;s internals, it is not strictly
necessary to close <cite>BlobReader</cite> instances explicitly. A <cite>BlobReader</cite>
object will be automatically closed by its <cite>__del__</cite> method when it
goes out of scope, or when its <cite>Connection</cite> closes, whichever comes
first. However, it is always a better idea to close resources
explicitly (via <cite>try...finally</cite>) than to rely on artifacts of the
CPython implementation. (For the sake of clarity, the example program
does not follow this practice.)</p>
<p><strong>Example Program</strong></p>
<p>The following program demonstrates blob storage and retrieval in both
<em>materialized</em> and <em>streaming</em> modes.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os.path</span>
<span class="kn">from</span> <span class="nn">cStringIO</span> <span class="kn">import</span> <span class="n">StringIO</span>

<span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;localhost:D:\temp\test-20.firebird&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span>
  <span class="p">)</span>

<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table blob_test (a blob)&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="c"># --- Materialized mode (str objects for both input and output) ---</span>
<span class="c"># Insertion:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into blob_test values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s">&#39;abcdef&#39;</span><span class="p">,))</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into blob_test values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s">&#39;ghijklmnop&#39;</span><span class="p">,))</span>
<span class="c"># Retrieval:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from blob_test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Materialized retrieval (as str):&#39;</span>
<span class="k">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;delete from blob_test&quot;</span><span class="p">)</span>

<span class="c"># --- Streaming mode (file-like objects for input; kinterbasdb.BlobReader</span>
<span class="c">#     objects for output) ---</span>
<span class="n">cur</span><span class="o">.</span><span class="n">set_type_trans_in</span> <span class="p">({</span><span class="s">&#39;BLOB&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s">&#39;mode&#39;</span><span class="p">:</span> <span class="s">&#39;stream&#39;</span><span class="p">}})</span>
<span class="n">cur</span><span class="o">.</span><span class="n">set_type_trans_out</span><span class="p">({</span><span class="s">&#39;BLOB&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s">&#39;mode&#39;</span><span class="p">:</span> <span class="s">&#39;stream&#39;</span><span class="p">}})</span>

<span class="c"># Insertion:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into blob_test values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">StringIO</span><span class="p">(</span><span class="s">&#39;abcdef&#39;</span><span class="p">),))</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into blob_test values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">StringIO</span><span class="p">(</span><span class="s">&#39;ghijklmnop&#39;</span><span class="p">),))</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">file</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">abspath</span><span class="p">(</span><span class="n">__file__</span><span class="p">),</span> <span class="s">&#39;rb&#39;</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into blob_test values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">f</span><span class="p">,))</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="c"># Retrieval using the &quot;file-like&quot; methods of BlobReader:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from blob_test&quot;</span><span class="p">)</span>

<span class="n">readerA</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mf">0</span><span class="p">]</span>

<span class="k">print</span> <span class="s">&#39;</span><span class="se">\n</span><span class="s">Streaming retrieval (via kinterbasdb.BlobReader):&#39;</span>

<span class="c"># Python &quot;file-like&quot; interface:</span>
<span class="k">print</span> <span class="s">&#39;readerA.mode:    &quot;</span><span class="si">%s</span><span class="s">&quot;&#39;</span> <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">mode</span>
<span class="k">print</span> <span class="s">&#39;readerA.closed:   </span><span class="si">%s</span><span class="s">&#39;</span>  <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">closed</span>
<span class="k">print</span> <span class="s">&#39;readerA.tell():   </span><span class="si">%d</span><span class="s">&#39;</span>  <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">tell</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;readerA.read(2): &quot;</span><span class="si">%s</span><span class="s">&quot;&#39;</span> <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mf">2</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;readerA.tell():   </span><span class="si">%d</span><span class="s">&#39;</span>  <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">tell</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;readerA.read():  &quot;</span><span class="si">%s</span><span class="s">&quot;&#39;</span> <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;readerA.tell():   </span><span class="si">%d</span><span class="s">&#39;</span>  <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">tell</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;readerA.read():  &quot;</span><span class="si">%s</span><span class="s">&quot;&#39;</span> <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="n">readerA</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;readerA.closed:   </span><span class="si">%s</span><span class="s">&#39;</span>  <span class="o">%</span> <span class="n">readerA</span><span class="o">.</span><span class="n">closed</span>

<span class="c"># The chunks method (not part of the Python &quot;file-like&quot; interface, but handy):</span>
<span class="k">print</span> <span class="s">&#39;</span><span class="se">\n</span><span class="s">For a blob with contents &quot;ghijklmnop&quot;, iterating over&#39;</span>
<span class="k">print</span> <span class="s">&#39;BlobReader.chunks(3) produces:&#39;</span>
<span class="n">readerB</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mf">0</span><span class="p">]</span>
<span class="k">for</span> <span class="n">chunkNo</span><span class="p">,</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">readerB</span><span class="o">.</span><span class="n">chunks</span><span class="p">(</span><span class="mf">3</span><span class="p">)):</span>
    <span class="k">print</span> <span class="s">&#39;Chunk </span><span class="si">%d</span><span class="s"> is: &quot;</span><span class="si">%s</span><span class="s">&quot;&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">chunkNo</span><span class="p">,</span> <span class="n">chunk</span><span class="p">)</span>
</pre></div>
</div>
<p>Output:</p>
<div class="highlight-python"><pre>Materialized retrieval (as str):
[('abcdef',), ('ghijklmnop',)]

Streaming retrieval (via kinterbasdb.BlobReader):
readerA.mode:    "rb"
readerA.closed:   False
readerA.tell():   0
readerA.read(2): "ab"
readerA.tell():   2
readerA.read():  "cdef"
readerA.tell():   6
readerA.read():  ""
readerA.closed:   True

For a blob with contents "ghijklmnop", iterating over
BlobReader.chunks(3) produces:
Chunk 0 is: "ghi"
Chunk 1 is: "jkl"
Chunk 2 is: "mno"
Chunk 3 is: "p"</pre>
</div>
</div>
</div>
<div class="section" id="connection-timeouts">
<span id="connection-timeout"></span><h2>Connection Timeouts<a class="headerlink" href="#connection-timeouts" title="Permalink to this headline">¶</a></h2>
<p>Connection timeouts allow the programmer to request that a connection
be automatically closed after a specified period of inactivity. The
simplest uses of connection timeouts are trivial, as demonstrated by
the following snippet:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;localhost:D:\temp\test.db&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">,</span>
    <span class="n">timeout</span><span class="o">=</span><span class="p">{</span><span class="s">&#39;period&#39;</span><span class="p">:</span> <span class="mf">120.0</span><span class="p">}</span> <span class="c"># time out after 120.0 seconds of inactivity</span>
  <span class="p">)</span>

<span class="o">...</span>
</pre></div>
</div>
<p>The connection created in the example above is <em>eligible</em> to be
automatically closed by KInterbasDB if it remains idle for at least
120.0 consecutive seconds. KInterbasDB does not guarantee that the
connection will be closed immediately when the specified period has
elapsed. On a busy system, there might be a considerable delay between
the moment a connection becomes eligible for timeout and the moment
KInterbasDB actually closes it. However, the thread that performs
connection timeouts is programmed in such a way that on a lightly
loaded system, it acts almost instantaneously to take advantage of a
connection&#8217;s eligibility for timeout.</p>
<p>After a connection has timed out, KInterbasDB reacts to attempts to
reactivate the severed connection in a manner dependent on the state
of the connection when it timed out. Consider the following example
program:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;localhost:D:\temp\test.db&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">,</span>
    <span class="n">timeout</span><span class="o">=</span><span class="p">{</span><span class="s">&#39;period&#39;</span><span class="p">:</span> <span class="mf">3.0</span><span class="p">}</span>
  <span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table test (a int, b char(1))&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s">&quot;insert into test (a, b) values (?, ?)&quot;</span><span class="p">,</span>
    <span class="p">[(</span><span class="mf">1</span><span class="p">,</span> <span class="s">&#39;A&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">2</span><span class="p">,</span> <span class="s">&#39;B&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">3</span><span class="p">,</span> <span class="s">&#39;C&#39;</span><span class="p">)]</span>
  <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;BEFORE:&#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;update test set b = &#39;X&#39; where a = 2&quot;</span><span class="p">)</span>

<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">6.0</span><span class="p">)</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;AFTER: &#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>
</div>
<p>So, should the example program print</p>
<div class="highlight-python"><pre>BEFORE: [(1, 'A'), (2, 'B'), (3, 'C')]
AFTER:  [(1, 'A'), (2, 'X'), (3, 'C')]</pre>
</div>
<p>or</p>
<div class="highlight-python"><pre>BEFORE: [(1, 'A'), (2, 'B'), (3, 'C')]
AFTER:  [(1, 'A'), (2, 'B'), (3, 'C')]</pre>
</div>
<p>or should it raise an exception? The answer is more complex than one
might think.</p>
<p>First of all, we cannot guarantee much about the example program&#8217;s
behavior because there is a race condition between the obvious thread
that&#8217;s executing the example code (which we&#8217;ll call &#8220;UserThread&#8221; for
the rest of this section) and the KInterbasDB-internal background
thread that actually closes connections that have timed out
(&#8220;TimeoutThread&#8221;). If the operating system were to suspend UserThread
just after the <a title="kinterbasdb.connect" class="reference external" href="python-db-api-compliance.html#kinterbasdb.connect"><tt class="xref docutils literal"><span class="pre">kinterbasdb.connect()</span></tt></a> call for more than
the specified timeout period of 3.0 seconds, the TimeoutThread might
close the connection before UserThread had performed any preparatory
operations on the database. Although such a scenario is extremely
unlikely when more &#8220;realistic&#8221; timeout periods such as 1800.0 seconds
(30 minutes) are used, it is important to consider. We&#8217;ll explore
solutions to this race condition later.</p>
<p>The <em>likely</em> (but not guaranteed) behavior of the example program is
that UserThread will complete all preparatory database operations
including the <cite>cur. execute ( &#8220;update test set b = &#8216;X&#8217; where a = 2&#8221; )</cite>
statement in the example program, then go to sleep for not less than
6.0 seconds. Not less than 3.0 seconds after UserThread executes the
<cite>cur. execute ( &#8220;update test set b = &#8216;X&#8217; where a = 2&#8221; )</cite> statement,
TimeoutThread is likely to close the connection because it has become
eligible for timeout.</p>
<p>The crucial issue is how TimeoutThread should resolve the transaction
that UserThread left open on <cite>con</cite>, and what should happen when
UserThread reawakens and tries to execute the <cite>cur. execute ( &#8220;select
* from test&#8221; )</cite> statement, since the transaction that UserThread left
open will no longer be active.</p>
<div class="section" id="user-supplied-connection-timeout-callbacks">
<h3>User-Supplied Connection Timeout Callbacks<a class="headerlink" href="#user-supplied-connection-timeout-callbacks" title="Permalink to this headline">¶</a></h3>
<p>In the context of a particular client program, it is not possible for
KInterbasDB to know the best way for TimeoutThread to react when it
encounters a connection that is eligible for timeout, but has an
unresolved transaction. For this reason, KInterbasDB&#8217;s connection
timeout system offers callbacks that the client programmer can use to
guide the TimeoutThread&#8217;s actions, or to log information about
connection timeout patterns.</p>
</div>
<div class="section" id="the-before-timeout-callback">
<h3>The &#8220;Before Timeout&#8221; Callback<a class="headerlink" href="#the-before-timeout-callback" title="Permalink to this headline">¶</a></h3>
<p>The client programmer can supply a &#8220;before timeout&#8221; callback that
accepts a single dictionary parameter and returns an integer code to
indicate how the TimeoutThread should proceed when it finds a
connection eligible for timeout. Within the dictionary, KInterbasDB
provides the following entries:</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">dsn:</th><td class="field-body">The <cite>dsn</cite> parameter that was passed to <cite>kinterbasdb.connect</cite>
when the connection was created.</td>
</tr>
<tr class="field"><th class="field-name" colspan="2">has_transaction:</th></tr>
<tr><td>&nbsp;</td><td class="field-body">A boolean that indicates whether the connection has an unresolved
transaction.</td>
</tr>
<tr class="field"><th class="field-name">active_secs:</th><td class="field-body">A <cite>float</cite> that indicates how many seconds elapsed between the point
when the connection attached to the server and the last client
program activity on the connection.</td>
</tr>
<tr class="field"><th class="field-name">idle_secs:</th><td class="field-body">A <cite>float</cite> that indicates how many seconds have elapsed since
the last client program activity on the connection. This
value will not be less than the specified timeout period, and is
likely to only a fraction of a second longer.</td>
</tr>
</tbody>
</table>
<p>Based on those data, the user-supplied callback should return one of
the following codes:</p>
<dl class="data">
<dt id="kinterbasdb.CT_VETO">
<!--[kinterbasdb.CT_VETO]--><tt class="descclassname">kinterbasdb.</tt><tt class="descname">CT_VETO</tt><a class="headerlink" href="#kinterbasdb.CT_VETO" title="Permalink to this definition">¶</a></dt>
<dd>Directs the TimeoutThread not to close the
connection at the current time, and not to reconsider timing the
connection out until at least another timeout period has passed. For
example, if a connection was created with a timeout period of 120.0
seconds, and the user-supplied &#8220;before callback&#8221; returns
<cite>CT_VETO</cite>, the TimeoutThread will not reconsider timing
out that particular connection until at least another 120.0 seconds
have elapsed.</dd></dl>

<dl class="data">
<dt id="kinterbasdb.CT_NONTRANSPARENT">
<!--[kinterbasdb.CT_NONTRANSPARENT]--><tt class="descclassname">kinterbasdb.</tt><tt class="descname">CT_NONTRANSPARENT</tt><a class="headerlink" href="#kinterbasdb.CT_NONTRANSPARENT" title="Permalink to this definition">¶</a></dt>
<dd><p>(&#8220;Nontransparent rollback&#8221;)</p>
<p>Directs the TimeoutThread to roll back the connection&#8217;s unresolved
transaction (if any), then close the connection. Any future attempt
to use the connection will raise a <tt class="xref docutils literal"><span class="pre">kinterbasdb.ConnectionTimedOut</span></tt>
exception.</p>
</dd></dl>

<dl class="data">
<dt id="kinterbasdb.CT_ROLLBACK">
<!--[kinterbasdb.CT_ROLLBACK]--><tt class="descclassname">kinterbasdb.</tt><tt class="descname">CT_ROLLBACK</tt><a class="headerlink" href="#kinterbasdb.CT_ROLLBACK" title="Permalink to this definition">¶</a></dt>
<dd><p>(&#8220;Transparent rollback&#8221;)</p>
<p>Directs the TimeoutThread to roll back the connection&#8217;s unresolved transaction
(if any), then close the connection. Upon any future attempt to use the
connection, KInterbasDB will <em>attempt</em> to transparently reconnect to
the database and &#8220;resume where it left off&#8221; insofar as possible. Of
course, network problems and the like could prevent KInterbasDB&#8217;s
<em>attempt</em> at transparent resumption from succeeding. Also, highly
state-dependent objects such as open result sets,
<a title="kinterbasdb.BlobReader" class="reference internal" href="#kinterbasdb.BlobReader"><tt class="xref docutils literal"><span class="pre">BlobReader</span></tt></a>, and <a title="kinterbasdb.PreparedStatement" class="reference internal" href="#kinterbasdb.PreparedStatement"><tt class="xref docutils literal"><span class="pre">PreparedStatement</span></tt></a>
cannot be used transparently across a connection timeout.</p>
</dd></dl>

<dl class="data">
<dt id="kinterbasdb.CT_COMMIT">
<!--[kinterbasdb.CT_COMMIT]--><tt class="descclassname">kinterbasdb.</tt><tt class="descname">CT_COMMIT</tt><a class="headerlink" href="#kinterbasdb.CT_COMMIT" title="Permalink to this definition">¶</a></dt>
<dd><p>(&#8220;Transparent commit&#8221;)</p>
<p>Directs the TimeoutThread to commit the connection&#8217;s unresolved transaction
(if any), then close the connection. Upon any future attempt to use the
connection, KInterbasDB will <em>attempt</em> to transparently reconnect to
the database and &#8220;resume where it left off&#8221; insofar as possible.</p>
</dd></dl>

<p>If the user does not supply a &#8220;before timeout&#8221; callback, KInterbasDB
considers the timeout transparent only if the connection does not have
an unresolved transaction.</p>
<p>If the user-supplied &#8220;before timeout&#8221; callback returns anything other
than one of the codes listed above, or if it raises an exception, the
TimeoutThread will act as though <a title="kinterbasdb.CT_NONTRANSPARENT" class="reference internal" href="#kinterbasdb.CT_NONTRANSPARENT"><tt class="xref docutils literal"><span class="pre">CT_NONTRANSPARENT</span></tt></a> had
been returned.</p>
<p>You might have noticed that the input dictionary to the &#8220;before
timeout&#8221; callback does <em>not</em> include a reference to the
<a title="kinterbasdb.Connection" class="reference internal" href="#kinterbasdb.Connection"><tt class="xref docutils literal"><span class="pre">Connection</span></tt></a> object itself. This is a deliberate design
decision intended to steer the client programmer away from writing
callbacks that take a long time to complete, or that manipulate the
<a title="kinterbasdb.Connection" class="reference internal" href="#kinterbasdb.Connection"><tt class="xref docutils literal"><span class="pre">Connection</span></tt></a> instance directly. See the caveats section for
more information.</p>
</div>
<div class="section" id="the-after-timeout-callback">
<h3>The &#8220;After Timeout&#8221; Callback<a class="headerlink" href="#the-after-timeout-callback" title="Permalink to this headline">¶</a></h3>
<p>The client programmer can supply an &#8220;after timeout&#8221; callback that
accepts a single dictionary parameter. Within that dictionary,
KInterbasDB currently provides the following entries:</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">dsn:</th><td class="field-body">The <cite>dsn</cite> parameter that was passed to <a title="kinterbasdb.connect" class="reference external" href="python-db-api-compliance.html#kinterbasdb.connect"><tt class="xref docutils literal"><span class="pre">kinterbasdb.connect()</span></tt></a>
when the connection was created.</td>
</tr>
<tr class="field"><th class="field-name">active_secs:</th><td class="field-body">A <cite>float</cite> that indicates how many seconds elapsed between
the point when the connection attached to the server and
the last client program activity on the connection.</td>
</tr>
<tr class="field"><th class="field-name">idle_secs:</th><td class="field-body">A <cite>float</cite> that indicates how many seconds elapsed between
the last client program activity on the connection and the moment
the TimeoutThread closed the connection.</td>
</tr>
</tbody>
</table>
<p>KInterbasDB only calls the &#8220;after timeout&#8221; callback after the
connection has actually been closed by the TimeoutThread. If the
&#8220;before timeout&#8221; callback returns <a title="kinterbasdb.CT_VETO" class="reference internal" href="#kinterbasdb.CT_VETO"><tt class="xref docutils literal"><span class="pre">CT_VETO</span></tt></a> to cancel the
timeout attempt, the &#8220;after timeout&#8221; callback will not be called.</p>
<p>KInterbasDB discards the return value of the &#8220;after timeout&#8221; callback,
and ignores any exceptions.</p>
<p>The same caveats that apply to the &#8220;before timeout&#8221; callback also
apply to the &#8220;after timeout&#8221; callback.</p>
</div>
<div class="section" id="user-supplied-connection-timeout-callback-caveats">
<h3>User-Supplied Connection Timeout Callback Caveats<a class="headerlink" href="#user-supplied-connection-timeout-callback-caveats" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>The user-supplied callbacks are executed by the TimeoutThread. They
should be designed to avoid blocking the TimeoutThread any longer than
absolutely necessary.</li>
<li>Manipulating the <a title="Connection" class="reference external" href="Python-DB-API-2.0.html#Connection"><tt class="xref docutils literal"><span class="pre">Connection</span></tt></a> object that is being timed out (or any
of that connection&#8217;s subordinate objects such as <a title="Cursor" class="reference external" href="Python-DB-API-2.0.html#Cursor"><tt class="xref docutils literal"><span class="pre">Cursor</span></tt></a>,
<a title="kinterbasdb.BlobReader" class="reference internal" href="#kinterbasdb.BlobReader"><tt class="xref docutils literal"><span class="pre">BlobReader</span></tt></a>, or <a title="kinterbasdb.PreparedStatement" class="reference internal" href="#kinterbasdb.PreparedStatement"><tt class="xref docutils literal"><span class="pre">PreparedStatement</span></tt></a>)
from the timeout callbacks is strictly forbidden.</li>
</ul>
</div>
<div class="section" id="examples">
<h3>Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h3>
<p><strong>Example: `CT_VETO`</strong></p>
<p>The following program registers a &#8220;before timeout&#8221; callback that
unconditionally returns <a title="kinterbasdb.CT_VETO" class="reference internal" href="#kinterbasdb.CT_VETO"><tt class="xref docutils literal"><span class="pre">CT_VETO</span></tt></a>, which means that the
TimeoutThread never times the connection out. Although an &#8220;after
timeout&#8221; callback is also registered, it will never be called.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="k">def</span> <span class="nf">callback_before</span><span class="p">(</span><span class="n">info</span><span class="p">):</span>
    <span class="k">print</span>
    <span class="k">print</span> <span class="s">&#39;callback_before called; input parameter contained:&#39;</span>
    <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">info</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
        <span class="k">print</span> <span class="s">&#39;  </span><span class="si">%s</span><span class="s">: </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">key</span><span class="p">)</span><span class="o">.</span><span class="n">ljust</span><span class="p">(</span><span class="mf">20</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">value</span><span class="p">))</span>
    <span class="k">print</span>
    <span class="c"># Unconditionally veto any timeout attempts:</span>
    <span class="k">return</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">CT_VETO</span>

<span class="k">def</span> <span class="nf">callback_after</span><span class="p">(</span><span class="n">info</span><span class="p">):</span>
    <span class="k">assert</span> <span class="bp">False</span><span class="p">,</span> <span class="s">&#39;This will never be called.&#39;</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;localhost:D:\temp\test.db&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">,</span>
    <span class="n">timeout</span><span class="o">=</span><span class="p">{</span>
        <span class="s">&#39;period&#39;</span><span class="p">:</span> <span class="mf">3.0</span><span class="p">,</span>
        <span class="s">&#39;callback_before&#39;</span><span class="p">:</span> <span class="n">callback_before</span><span class="p">,</span>
        <span class="s">&#39;callback_after&#39;</span><span class="p">:</span>  <span class="n">callback_after</span><span class="p">,</span>
      <span class="p">}</span>
  <span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table test (a int, b char(1))&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s">&quot;insert into test (a, b) values (?, ?)&quot;</span><span class="p">,</span>
    <span class="p">[(</span><span class="mf">1</span><span class="p">,</span> <span class="s">&#39;A&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">2</span><span class="p">,</span> <span class="s">&#39;B&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">3</span><span class="p">,</span> <span class="s">&#39;C&#39;</span><span class="p">)]</span>
  <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;BEFORE:&#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;update test set b = &#39;X&#39; where a = 2&quot;</span><span class="p">)</span>

<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">6.0</span><span class="p">)</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="n">rows</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="c"># The value of the second column of the second row of the table is still &#39;X&#39;,</span>
<span class="c"># because the transaction that changed it from &#39;B&#39; to &#39;X&#39; remains active.</span>
<span class="k">assert</span> <span class="n">rows</span><span class="p">[</span><span class="mf">1</span><span class="p">][</span><span class="mf">1</span><span class="p">]</span> <span class="o">==</span> <span class="s">&#39;X&#39;</span>
<span class="k">print</span> <span class="s">&#39;AFTER: &#39;</span><span class="p">,</span> <span class="n">rows</span>
</pre></div>
</div>
<p>Sample output:</p>
<div class="highlight-python"><pre>BEFORE: [(1, 'A'), (2, 'B'), (3, 'C')]

callback_before called; input parameter contained:
  'dsn'               : 'localhost:D:\\temp\\test.db'
  'idle_secs'         : 3.0
  'has_transaction'   : True

AFTER:  [(1, 'A'), (2, 'X'), (3, 'C')]</pre>
</div>
<p><strong>Example: Supporting Module `timeout_authorizer`</strong></p>
<p>The example programs for <a title="kinterbasdb.CT_NONTRANSPARENT" class="reference internal" href="#kinterbasdb.CT_NONTRANSPARENT"><tt class="xref docutils literal"><span class="pre">CT_NONTRANSPARENT</span></tt></a>, <a title="kinterbasdb.CT_ROLLBACK" class="reference internal" href="#kinterbasdb.CT_ROLLBACK"><tt class="xref docutils literal"><span class="pre">CT_ROLLBACK</span></tt></a>,
and <a title="kinterbasdb.CT_COMMIT" class="reference internal" href="#kinterbasdb.CT_COMMIT"><tt class="xref docutils literal"><span class="pre">CT_COMMIT</span></tt></a> rely on the <cite>TimeoutAuthorizer</cite> class from
the module below to guarantee that the TimeoutThread will not time
the connection out before the preparatory code has executed.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">threading</span>
<span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="k">class</span> <span class="nc">TimeoutAuthorizer</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">opCodeWhenAuthorized</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">currentOpCode</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">CT_VETO</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">opCodeWhenAuthorized</span> <span class="o">=</span> <span class="n">opCodeWhenAuthorized</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">authorize</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">lock</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">currentOpCode</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">opCodeWhenAuthorized</span>
        <span class="k">finally</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">lock</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">info</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">lock</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">currentOpCode</span>
        <span class="k">finally</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">lock</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
</pre></div>
</div>
<p><strong>Example: `CT_NONTRANSPARENT`</strong></p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">kinterbasdb</span>
<span class="kn">import</span> <span class="nn">timeout_authorizer</span>

<span class="n">authorizer</span> <span class="o">=</span> <span class="n">timeout_authorizer</span><span class="o">.</span><span class="n">TimeoutAuthorizer</span><span class="p">(</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">CT_NONTRANSPARENT</span><span class="p">)</span>
<span class="n">connectionTimedOut</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Event</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">callback_after</span><span class="p">(</span><span class="n">info</span><span class="p">):</span>
    <span class="k">print</span>
    <span class="k">print</span> <span class="s">&#39;The connection was closed nontransparently.&#39;</span>
    <span class="k">print</span>
    <span class="n">connectionTimedOut</span><span class="o">.</span><span class="n">set</span><span class="p">()</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;localhost:D:\temp\test.db&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">,</span>
    <span class="n">timeout</span><span class="o">=</span><span class="p">{</span>
        <span class="s">&#39;period&#39;</span><span class="p">:</span> <span class="mf">3.0</span><span class="p">,</span>
        <span class="s">&#39;callback_before&#39;</span><span class="p">:</span> <span class="n">authorizer</span><span class="p">,</span>
        <span class="s">&#39;callback_after&#39;</span><span class="p">:</span>  <span class="n">callback_after</span><span class="p">,</span>
      <span class="p">}</span>
  <span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table test (a int, b char(1))&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s">&quot;insert into test (a, b) values (?, ?)&quot;</span><span class="p">,</span>
    <span class="p">[(</span><span class="mf">1</span><span class="p">,</span> <span class="s">&#39;A&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">2</span><span class="p">,</span> <span class="s">&#39;B&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">3</span><span class="p">,</span> <span class="s">&#39;C&#39;</span><span class="p">)]</span>
  <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;BEFORE:&#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;update test set b = &#39;X&#39; where a = 2&quot;</span><span class="p">)</span>

<span class="n">authorizer</span><span class="o">.</span><span class="n">authorize</span><span class="p">()</span>
<span class="n">connectionTimedOut</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>

<span class="c"># This will raise a kinterbasdb.ConnectionTimedOut exception because the</span>
<span class="c"># before callback returned kinterbasdb.CT_NONTRANSPARENT:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Sample output:</p>
<div class="highlight-python"><pre>BEFORE: [(1, 'A'), (2, 'B'), (3, 'C')]

The connection was closed nontransparently.

Traceback (most recent call last):
  File "connection_timeouts_ct_nontransparent.py", line 42, in ?
    cur.execute("select * from test")
kinterbasdb.ConnectionTimedOut: (0, 'A transaction was still unresolved when
this connection timed out, so it cannot be transparently reactivated.')</pre>
</div>
<p><strong>Example: `CT_ROLLBACK`</strong></p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">kinterbasdb</span>
<span class="kn">import</span> <span class="nn">timeout_authorizer</span>

<span class="n">authorizer</span> <span class="o">=</span> <span class="n">timeout_authorizer</span><span class="o">.</span><span class="n">TimeoutAuthorizer</span><span class="p">(</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">CT_ROLLBACK</span><span class="p">)</span>
<span class="n">connectionTimedOut</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Event</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">callback_after</span><span class="p">(</span><span class="n">info</span><span class="p">):</span>
    <span class="k">print</span>
    <span class="k">print</span> <span class="s">&#39;The unresolved transaction was rolled back; the connection has been&#39;</span>
    <span class="k">print</span> <span class="s">&#39; closed transparently.&#39;</span>
    <span class="k">print</span>
    <span class="n">connectionTimedOut</span><span class="o">.</span><span class="n">set</span><span class="p">()</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;localhost:D:\temp\test.db&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">,</span>
    <span class="n">timeout</span><span class="o">=</span><span class="p">{</span>
        <span class="s">&#39;period&#39;</span><span class="p">:</span> <span class="mf">3.0</span><span class="p">,</span>
        <span class="s">&#39;callback_before&#39;</span><span class="p">:</span> <span class="n">authorizer</span><span class="p">,</span>
        <span class="s">&#39;callback_after&#39;</span><span class="p">:</span>  <span class="n">callback_after</span><span class="p">,</span>
      <span class="p">}</span>
  <span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table test (a int, b char(1))&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s">&quot;insert into test (a, b) values (?, ?)&quot;</span><span class="p">,</span>
    <span class="p">[(</span><span class="mf">1</span><span class="p">,</span> <span class="s">&#39;A&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">2</span><span class="p">,</span> <span class="s">&#39;B&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">3</span><span class="p">,</span> <span class="s">&#39;C&#39;</span><span class="p">)]</span>
  <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;BEFORE:&#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;update test set b = &#39;X&#39; where a = 2&quot;</span><span class="p">)</span>

<span class="n">authorizer</span><span class="o">.</span><span class="n">authorize</span><span class="p">()</span>
<span class="n">connectionTimedOut</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>

<span class="c"># The value of the second column of the second row of the table will have</span>
<span class="c"># reverted to &#39;B&#39; when the transaction that changed it to &#39;X&#39; was rolled back.</span>
<span class="c"># The cur.execute call on the next line will transparently reactivate the</span>
<span class="c"># connection, which was timed out transparently.</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="n">rows</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="k">assert</span> <span class="n">rows</span><span class="p">[</span><span class="mf">1</span><span class="p">][</span><span class="mf">1</span><span class="p">]</span> <span class="o">==</span> <span class="s">&#39;B&#39;</span>
<span class="k">print</span> <span class="s">&#39;AFTER: &#39;</span><span class="p">,</span> <span class="n">rows</span>
</pre></div>
</div>
<p>Sample output:</p>
<div class="highlight-python"><pre>BEFORE: [(1, 'A'), (2, 'B'), (3, 'C')]

The unresolved transaction was rolled back; the connection has been
 closed transparently.

AFTER:  [(1, 'A'), (2, 'B'), (3, 'C')]</pre>
</div>
<p><strong>Example: `CT_COMMIT`</strong></p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">kinterbasdb</span>
<span class="kn">import</span> <span class="nn">timeout_authorizer</span>

<span class="n">authorizer</span> <span class="o">=</span> <span class="n">timeout_authorizer</span><span class="o">.</span><span class="n">TimeoutAuthorizer</span><span class="p">(</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">CT_COMMIT</span><span class="p">)</span>
<span class="n">connectionTimedOut</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Event</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">callback_after</span><span class="p">(</span><span class="n">info</span><span class="p">):</span>
    <span class="k">print</span>
    <span class="k">print</span> <span class="s">&#39;The unresolved transaction was committed; the connection has been&#39;</span>
    <span class="k">print</span> <span class="s">&#39; closed transparently.&#39;</span>
    <span class="k">print</span>
    <span class="n">connectionTimedOut</span><span class="o">.</span><span class="n">set</span><span class="p">()</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">r&#39;localhost:D:\temp\test.db&#39;</span><span class="p">,</span>
    <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">,</span>
    <span class="n">timeout</span><span class="o">=</span><span class="p">{</span>
        <span class="s">&#39;period&#39;</span><span class="p">:</span> <span class="mf">3.0</span><span class="p">,</span>
        <span class="s">&#39;callback_before&#39;</span><span class="p">:</span> <span class="n">authorizer</span><span class="p">,</span>
        <span class="s">&#39;callback_after&#39;</span><span class="p">:</span>  <span class="n">callback_after</span><span class="p">,</span>
      <span class="p">}</span>
  <span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;recreate table test (a int, b char(1))&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s">&quot;insert into test (a, b) values (?, ?)&quot;</span><span class="p">,</span>
    <span class="p">[(</span><span class="mf">1</span><span class="p">,</span> <span class="s">&#39;A&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">2</span><span class="p">,</span> <span class="s">&#39;B&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mf">3</span><span class="p">,</span> <span class="s">&#39;C&#39;</span><span class="p">)]</span>
  <span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;BEFORE:&#39;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;update test set b = &#39;X&#39; where a = 2&quot;</span><span class="p">)</span>

<span class="n">authorizer</span><span class="o">.</span><span class="n">authorize</span><span class="p">()</span>
<span class="n">connectionTimedOut</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>

<span class="c"># The modification of the value of the second column of the second row of the</span>
<span class="c"># table from &#39;B&#39; to &#39;X&#39; will have persisted, because the TimeoutThread</span>
<span class="c"># committed the transaction before it timed the connection out.</span>
<span class="c"># The cur.execute call on the next line will transparently reactivate the</span>
<span class="c"># connection, which was timed out transparently.</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;select * from test&quot;</span><span class="p">)</span>
<span class="n">rows</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="k">assert</span> <span class="n">rows</span><span class="p">[</span><span class="mf">1</span><span class="p">][</span><span class="mf">1</span><span class="p">]</span> <span class="o">==</span> <span class="s">&#39;X&#39;</span>
<span class="k">print</span> <span class="s">&#39;AFTER: &#39;</span><span class="p">,</span> <span class="n">rows</span>
</pre></div>
</div>
<p>Sample output:</p>
<div class="highlight-python"><pre>BEFORE: [(1, 'A'), (2, 'B'), (3, 'C')]

The unresolved transaction was committed; the connection has been
 closed transparently.

AFTER:  [(1, 'A'), (2, 'X'), (3, 'C')]</pre>
</div>
</div>
</div>
<div class="section" id="database-event-notification">
<h2>Database Event Notification<a class="headerlink" href="#database-event-notification" title="Permalink to this headline">¶</a></h2>
<div class="section" id="what-are-database-events">
<h3>What are database events?<a class="headerlink" href="#what-are-database-events" title="Permalink to this headline">¶</a></h3>
<p>The database engine features a distributed, interprocess communication
mechanism based on messages called <em>database events</em>.
A database event is a message passed from a trigger or stored
procedure to an application to announce the occurrence of a specified
condition or action, usually a database change such as an insertion,
modification, or deletion of a record. The Firebird event mechanism
enables applications to respond to actions and database changes made
by other, concurrently running applications without the need for those
applications to communicate directly with one another, and without
incurring the expense of CPU time required for periodic polling to
determine if an event has occurred.</p>
</div>
<div class="section" id="why-use-database-events">
<h3>Why use database events?<a class="headerlink" href="#why-use-database-events" title="Permalink to this headline">¶</a></h3>
<p>Anything that can be accomplished with database events can also be
implemented using other techniques, so why bother with events? Since
you&#8217;ve chosen to write database-centric programs in Python rather than
assembly language, you probably already know the answer to this
question, but let&#8217;s illustrate.</p>
<p>A typical application for database events is the handling of
administrative messages. Suppose you have an administrative message
database with a <cite>messages</cite> table, into which various applications
insert timestamped status reports. It may be desirable to react to
these messages in diverse ways, depending on the status they indicate:
to ignore them, to initiate the update of dependent databases upon
their arrival, to forward them by e-mail to a remote administrator, or
even to set off an alarm so that on-site administrators will know a
problem has occurred.</p>
<p>It is undesirable to tightly couple the program whose status is being
reported (the <em>message producer</em>) to the program that handles the
status reports (the <em>message handler</em>). There are obvious losses of
flexibility in doing so. For example, the message producer may run on
a separate machine from the administrative message database and may
lack access rights to the downstream reporting facilities (e.g.,
network access to the SMTP server, in the case of forwarded e-mail
notifications). Additionally, the actions required to handle status
reports may themselves be time-consuming and error-prone, as in
accessing a remote network to transmit e-mail.</p>
<p>In the absence of database event support, the message handler would
probably be implemented via <em>polling</em>. Polling is simply the
repetition of a check for a condition at a specified interval. In this
case, the message handler would check in an infinite loop to see
whether the most recent record in the <cite>messages</cite> table was more recent
than the last message it had handled. If so, it would handle the fresh
message(s); if not, it would go to sleep for a specified interval,
then loop.</p>
<p>The <em>polling-based</em> implementation of the message handler is
fundamentally flawed. Polling is a form of <a class="reference external" href="http://www.catb.org/jargon/html/B/busy-wait.html">busy-wait</a>; the check for
new messages is performed at the specified interval, regardless of the
actual activity level of the message producers. If the polling
interval is lengthy, messages might not be handled within a reasonable
time period after their arrival; if the polling interval is brief, the
message handler program (and there may be many such programs) will
waste a large amount of CPU time on unnecessary checks.</p>
<p>The database server is necessarily aware of the exact moment when a
new message arrives. Why not let the message handler program request
that the database server send it a notification when a new message
arrives? The message handler can then efficiently sleep until the
moment its services are needed. Under this <em>event-based</em> scheme, the
message handler becomes aware of new messages at the instant they
arrive, yet it does not waste CPU time checking in vain for new
messages when there are none available.</p>
</div>
<div class="section" id="how-events-are-exposed-to-the-server-and-the-client-process">
<h3>How events are exposed to the server and the client process?<a class="headerlink" href="#how-events-are-exposed-to-the-server-and-the-client-process" title="Permalink to this headline">¶</a></h3>
<ol class="arabic">
<li><p class="first">Server Process (&#8220;An event just occurred!&#8221;)</p>
<p>To notify any interested listeners that a specific event has
occurred, issue the <cite>POST_EVENT</cite> statement from Stored Procedure
or Trigger. The <cite>POST_EVENT</cite> statement has one parameter: the name
of the event to post. In the preceding example of the administrative
message database, <cite>POST_EVENT</cite> might be used from an <cite>after insert</cite>
trigger on the <cite>messages</cite> table, like this:</p>
<div class="highlight-python"><pre>create trigger trig_messages_handle_insert
  for messages
    after insert
as
begin
  POST_EVENT 'new_message';
end</pre>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The physical notification of the client process does not
occur until the transaction in which the <cite>POST_EVENT</cite> took place is
actually committed. Therefore, multiple events may <em>conceptually</em>
occur before the client process is <em>physically</em> informed of even one
occurrence. Furthermore, the database engine makes no guarantee that
clients will be informed of events in the same groupings in which they
conceptually occurred. If, within a single transaction, an event named
<cite>event_a</cite> is posted once and an event named <cite>event_b</cite> is posted once,
the client may receive those posts in separate &#8220;batches&#8221;, despite the
fact that they occurred in the same conceptual unit (a single
transaction). This also applies to multiple occurrences of <em>the same</em>
event within a single conceptual unit: the physical notifications may
arrive at the client separately.</p>
</div>
</li>
<li><p class="first">Client Process (&#8220;Send me a message when an event occurs.&#8221;)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you don&#8217;t care about the gory details of event notification,
skip to the section that describes KInterbasDB&#8217;s Python-level
event handling API.</p>
</div>
<p>The Firebird C client library offers two forms of event notification.
The first form is <em>synchronous</em> notification, by way of the function
<tt class="xref docutils literal"><span class="pre">isc_wait_for_event()</span></tt>. This form is admirably simple for a C programmer
to use, but is inappropriate as a basis for KInterbasDB&#8217;s event support,
chiefly because it&#8217;s not sophisticated enough to serve as the basis for
a comfortable Python-level API. The other form of event notification
offered by the database client library is <em>asynchronous</em>, by way of the
functions <tt class="xref docutils literal"><span class="pre">isc_que_events()</span></tt> (note that the name of that function
is misspelled), <tt class="xref docutils literal"><span class="pre">isc_cancel_events()</span></tt>, and others. The details are
as nasty as they are numerous, but the essence of using asynchronous
notification from C is as follows:</p>
<blockquote>
<ol class="arabic simple">
<li>Call <tt class="xref docutils literal"><span class="pre">isc_event_block()</span></tt> to create a formatted binary buffer that
will tell the server which events the client wants to listen for.</li>
<li>Call <tt class="xref docutils literal"><span class="pre">isc_que_events()</span></tt> (passing the buffer created in the previous
step) to inform the server that the client is ready to receive event
notifications, and provide a callback that will be asynchronously
invoked when one or more of the registered events occurs.</li>
<li>[The thread that called <tt class="xref docutils literal"><span class="pre">isc_que_events()</span></tt> to initiate event
listening must now do something else.]</li>
<li>When the callback is invoked (the database client library starts a
thread dedicated to this purpose), it can use the <tt class="xref docutils literal"><span class="pre">isc_event_counts()</span></tt>
function to determine how many times each of the registered events has
occurred since the last call to <tt class="xref docutils literal"><span class="pre">isc_event_counts()</span></tt> (if any).</li>
<li>[The callback thread should now &#8220;do its thing&#8221;, which may include
communicating with the thread that called <tt class="xref docutils literal"><span class="pre">isc_que_events()</span></tt>.]</li>
<li>When the callback thread is finished handling an event
notification, it must call <tt class="xref docutils literal"><span class="pre">isc_que_events()</span></tt> again in order to receive
future notifications. Future notifications will invoke the callback
again, effectively &#8220;looping&#8221; the callback thread back to Step 4.</li>
</ol>
</blockquote>
</li>
</ol>
</div>
<div class="section" id="how-events-are-exposed-to-the-python-programmer">
<h3>How events are exposed to the Python programmer?<a class="headerlink" href="#how-events-are-exposed-to-the-python-programmer" title="Permalink to this headline">¶</a></h3>
<p>The KInterbasDB database event API is comprised of the following: the
method <cite>Connection.event_conduit</cite> and the class <a title="kinterbasdb.EventConduit" class="reference internal" href="#kinterbasdb.EventConduit"><tt class="xref docutils literal"><span class="pre">EventConduit</span></tt></a>.</p>
<dl class="method">
<dt id="kinterbasdb.Connection.event_conduit">
<!--[kinterbasdb.Connection.event_conduit]--><tt class="descclassname">Connection.</tt><tt class="descname">event_conduit</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.event_conduit" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a conduit (an instance of <a title="kinterbasdb.EventConduit" class="reference internal" href="#kinterbasdb.EventConduit"><tt class="xref docutils literal"><span class="pre">EventConduit</span></tt></a>)
through which database event notifications will flow into the Python program.</p>
<p><cite>event_conduit</cite> is a method of <cite>Connection</cite> rather than a module-level
function or a class constructor because the database engine deals with
events in the context of a particular database (after all,
<cite>POST_EVENT</cite> must be issued by a stored procedure or a trigger).</p>
<p>Arguments:</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Event_names:</th><td class="field-body">A sequence of string event names The <a title="kinterbasdb.EventConduit.wait" class="reference internal" href="#kinterbasdb.EventConduit.wait"><tt class="xref docutils literal"><span class="pre">EventConduit.wait()</span></tt></a>
method will block until the occurrence of at least one of the
events named by the strings in <cite>event_names</cite>. KInterbasDB&#8217;s
own event-related code is capable of operating with up to 2147483647
events per conduit. However, it has been observed that the Firebird
client library experiences catastrophic problems (including memory
corruption) on some platforms with anything beyond about 100 events
per conduit. These limitations are dependent on both the Firebird
version and the platform.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="class">
<dt id="kinterbasdb.EventConduit">
<!--[kinterbasdb.EventConduit]-->class <tt class="descclassname">kinterbasdb.</tt><tt class="descname">EventConduit</tt><a class="headerlink" href="#kinterbasdb.EventConduit" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="kinterbasdb.EventConduit.__init__">
<!--[kinterbasdb.EventConduit.__init__]--><tt class="descname">__init__</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.EventConduit.__init__" title="Permalink to this definition">¶</a></dt>
<dd>The <cite>EventConduit</cite> class is not designed to be instantiated directly
by the Python programmer. Instead, use the <cite>Connection.event_conduit</cite>
method to create <cite>EventConduit</cite> instances.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.EventConduit.wait">
<!--[kinterbasdb.EventConduit.wait]--><tt class="descname">wait</tt><big>(</big><em>timeout=None</em><big>)</big><a class="headerlink" href="#kinterbasdb.EventConduit.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Blocks the calling thread until at least one of the events occurs, or
the specified <cite>timeout</cite> (if any) expires.</p>
<p>If one or more event notifications has arrived since the last call to
<cite>wait</cite>, this method will retrieve a notification from the head of the
<cite>EventConduit</cite>&#8216;s internal queue and return immediately.</p>
<p>The names of the relevant events were supplied to the
<cite>Connection.event_conduit</cite> method during the creation of this
<cite>EventConduit</cite>. In the code snippet below, the relevant events are
named <cite>event_a</cite> and <cite>event_b</cite>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">conduit</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">event_conduit</span><span class="p">(</span> <span class="p">(</span><span class="s">&#39;event_a&#39;</span><span class="p">,</span> <span class="s">&#39;event_b&#39;</span><span class="p">)</span> <span class="p">)</span>
<span class="n">conduit</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
</pre></div>
</div>
<p>Arguments:</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Timeout:</th><td class="field-body"><em>optional</em> number of seconds (use a <cite>float</cite> to
indicate fractions of seconds) If not even one of the relevant
events has occurred after <cite>timeout</cite> seconds, this method will
unblock and return <cite>None</cite>. The default <cite>timeout</cite> is infinite.</td>
</tr>
</tbody>
</table>
<dl class="docutils">
<dt>Returns:</dt>
<dd><cite>None</cite> if the wait timed out, otherwise a dictionary that maps
<cite>event_name -&gt; event_occurrence_count</cite>.</dd>
</dl>
<p>In the code snippet above, if <cite>event_a</cite> occurred once and <cite>event_b</cite>
did not occur at all, the return value from <cite>conduit.wait()</cite> would be
the following dictionary:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">{</span>
 <span class="s">&#39;event_a&#39;</span><span class="p">:</span> <span class="mf">1</span><span class="p">,</span>
 <span class="s">&#39;event_b&#39;</span><span class="p">:</span> <span class="mf">0</span>
<span class="p">}</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.EventConduit.close">
<!--[kinterbasdb.EventConduit.close]--><tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.EventConduit.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Cancels the standing request for this conduit to be notified of events.</p>
<p>After this method has been called, this <cite>EventConduit</cite> object is
useless, and should be discarded. (The boolean property <cite>closed</cite> is
<cite>True</cite> after an <cite>EventConduit</cite> has been closed.)</p>
<p>This method has no arguments.</p>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.EventConduit.flush">
<!--[kinterbasdb.EventConduit.flush]--><tt class="descname">flush</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.EventConduit.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>This method allows the Python programmer to manually clear any event
notifications that have accumulated in the conduit&#8217;s internal queue.</p>
<p>From the moment the conduit is created by the
<a title="kinterbasdb.Connection.event_conduit" class="reference internal" href="#kinterbasdb.Connection.event_conduit"><tt class="xref docutils literal"><span class="pre">Connection.event_conduit()</span></tt></a> method, notifications of any events that
occur will accumulate asynchronously within the conduit&#8217;s internal
queue until the conduit is closed either explicitly (via the <cite>close</cite>
method) or implicitly (via garbage collection). There are two ways to
dispose of the accumulated notifications: call <cite>wait()</cite> to receive them
one at a time ( <cite>wait()</cite> will block when the conduit&#8217;s internal queue is
empty), or call this method to get rid of all accumulated
notifications.</p>
<p>This method has no arguments.</p>
<dl class="docutils">
<dt>Returns:</dt>
<dd>The number of event notifications that were flushed from the queue.
The &#8220;number of event <em>notifications</em>&#8221; is not necessarily the same as
the &#8220;number of event <em>occurrences</em>&#8220;, since a single notification can
indicate multiple occurrences of a given event (see the return value
of the <cite>wait</cite> method).</dd>
</dl>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="example-program">
<h3>Example Program<a class="headerlink" href="#example-program" title="Permalink to this headline">¶</a></h3>
<p>The following code (a SQL table definition, a SQL trigger definition,
and two Python programs) demonstrates KInterbasDB-based event
notification.</p>
<p>The example is based on a database at <cite>&#8216;localhost:/temp/test.db&#8217;</cite>,
which contains a simple table named <cite>test_table</cite>.&nbsp; <cite>test_table</cite> has
an <cite>after insert</cite> trigger that posts several events. Note that the
trigger posts <cite>test_event_a</cite> twice, <cite>test_event_b</cite> once, and
<cite>test_event_c</cite> once.</p>
<p>The Python event <em>handler</em> program connects to the database and
establishes an <cite>EventConduit</cite> in the context of that connection. As
specified by the list of <cite>RELEVANT_EVENTS</cite> passed to <cite>event_conduit</cite>,
the event conduit will concern itself only with events named
<cite>test_event_a</cite> and <cite>test_event_b</cite>. Next, the program calls the
conduit&#8217;s <cite>wait</cite> method without a timeout; it will wait infinitely
until <em>at least one</em> of the relevant events is posted in a transaction
that is subsequently committed.</p>
<p>The Python event <em>producer</em> program simply connects to the database,
inserts a row into <cite>test_table</cite>, and commits the transaction. Notice
that except for the printed comment, no code in the producer makes any
mention of events &#8211; the events are posted as an implicit consequence of
the row&#8217;s insertion into <cite>test_table</cite>.</p>
<p>The insertion into <cite>test_table</cite> causes the trigger to <em>conceptually</em>
post events, but those events are not <em>physically</em> sent to interested
listeners until the transaction is committed. When the commit occurs,
the handler program returns from the <cite>wait</cite> call and prints the
notification that it received.</p>
<p>SQL table definition:</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">create</span> <span class="k">table</span> <span class="n">test_table</span> <span class="p">(</span><span class="n">a</span> <span class="nb">integer</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL trigger definition:</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">create</span> <span class="k">trigger</span> <span class="n">trig_test_insert_event</span>
  <span class="k">for</span> <span class="n">test_table</span>
    <span class="k">after</span> <span class="k">insert</span>
<span class="k">as</span>
<span class="k">begin</span>
  <span class="n">post_event</span> <span class="s1">&#39;test_event_a&#39;</span><span class="p">;</span>
  <span class="n">post_event</span> <span class="s1">&#39;test_event_b&#39;</span><span class="p">;</span>
  <span class="n">post_event</span> <span class="s1">&#39;test_event_c&#39;</span><span class="p">;</span>

  <span class="n">post_event</span> <span class="s1">&#39;test_event_a&#39;</span><span class="p">;</span>
<span class="k">end</span>
</pre></div>
</div>
<p>Python event <em>handler</em> program:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">RELEVANT_EVENTS</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;test_event_a&#39;</span><span class="p">,</span> <span class="s">&#39;test_event_b&#39;</span><span class="p">]</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>
<span class="n">conduit</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">event_conduit</span><span class="p">(</span><span class="n">RELEVANT_EVENTS</span><span class="p">)</span>

<span class="k">print</span> <span class="s">&#39;HANDLER: About to wait for the occurrence of one of </span><span class="si">%s</span><span class="s">...</span><span class="se">\n</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">RELEVANT_EVENTS</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">conduit</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;HANDLER: An event notification has arrived:&#39;</span>
<span class="k">print</span> <span class="n">result</span>
<span class="n">conduit</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Python event <em>producer</em> program:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;insert into test_table values (1)&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;PRODUCER: Committing transaction that will cause event notification to be sent.&#39;</span>
<span class="n">con</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
</pre></div>
</div>
<p>Event producer output:</p>
<div class="highlight-python"><pre>PRODUCER: Committing transaction that will cause event notification to be sent.</pre>
</div>
<p>Event handler output (assuming that the handler was already started
and waiting when the event producer program was executed):</p>
<div class="highlight-python"><pre>HANDLER: About to wait for the occurrence of one of ['test_event_a', 'test_event_b']...

HANDLER: An event notification has arrived:
{'test_event_a': 2, 'test_event_b': 1}</pre>
</div>
<p>Notice that there is no mention of <cite>test_event_c</cite> in the result
dictionary received by the event handler program. Although
<cite>test_event_c</cite> was posted by the <cite>after insert</cite> trigger, the event
conduit in the handler program was created to listen only for
<cite>test_event_a</cite> and <cite>test_event_b</cite> events.</p>
</div>
<div class="section" id="pitfalls-and-limitations">
<h3>Pitfalls and Limitations<a class="headerlink" href="#pitfalls-and-limitations" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>Remember that if an <cite>EventConduit</cite> is left active (not yet closed
or garbage collected), notifications for any registered events that
actually occur will continue to accumulate in the EventConduit&#8217;s
internal queue even if the Python programmer doesn&#8217;t call
<a title="kinterbasdb.EventConduit.wait" class="reference internal" href="#kinterbasdb.EventConduit.wait"><tt class="xref docutils literal"><span class="pre">EventConduit.wait()</span></tt></a> to receive the notifications or
<a title="kinterbasdb.EventConduit.flush" class="reference internal" href="#kinterbasdb.EventConduit.flush"><tt class="xref docutils literal"><span class="pre">EventConduit.flush()</span></tt></a> to clear the queue. The ill-informed may
misinterpret this behavior as a memory leak in KInterbasDB; it is not.</li>
<li>NEVER use LOCAL-protocol connections in a multithreaded program that
also uses event handling! The database client library implements the
local protocol on some platforms in such a way that deadlocks may
arise in bizarre places if you do this. <em>This no-LOCAL prohibition is
not limited to connections that are used as the basis for event
conduits; it applies to all connections throughout the process.</em> So
why doesn&#8217;t KInterbasDB protect the Python programmer from this
mistake? Because the event handling thread is started by the database
client library, and it operates beyond the synchronization domain of
KInterbasDB at times.</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The restrictions on the number of active <cite>EventConduit`s in a
process, and on the number of event names that a single `EventConduit</cite>
can listen for, have been removed in KInterbasDB 3.2.</p>
</div>
</div>
</div>
<div class="section" id="the-database-info-api">
<h2>The <cite>database_info</cite> API<a class="headerlink" href="#the-database-info-api" title="Permalink to this headline">¶</a></h2>
<p>Firebird provides various informations about server and connected database
via <cite>database_info</cite> API call. KInterbasDB surfaces this API through next
methods on Connection object:</p>
<dl class="method">
<dt id="kinterbasdb.Connection.database_info">
<!--[kinterbasdb.Connection.database_info]--><tt class="descclassname">Connection.</tt><tt class="descname">database_info</tt><big>(</big><em>request</em>, <em>result_type</em><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.database_info" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is a <em>very thin</em> wrapper around function <tt class="xref docutils literal"><span class="pre">isc_database_info()</span></tt>.
This method does <em>not</em> attempt to interpret its results except with regard to
whether they are a string or an integer.</p>
<p>For example, requesting <tt class="xref docutils literal"><span class="pre">isc_info_user_names</span></tt> with the call</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">con</span><span class="o">.</span><span class="n">database_info</span><span class="p">(</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_user_names</span><span class="p">,</span> <span class="s">&#39;s&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>will return a binary string containing a <em>raw</em> succession of length-
name pairs. A more convenient way to access the same functionality is
via the <a title="kinterbasdb.Connection.db_info" class="reference internal" href="#kinterbasdb.Connection.db_info"><tt class="xref docutils literal"><span class="pre">db_info()</span></tt></a> method.</p>
<p>Arguments:</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Request:</th><td class="field-body">One of the <cite>kinterbasdb.isc_info_*</cite> constants.</td>
</tr>
<tr class="field"><th class="field-name">Result_type:</th><td class="field-body">Must be either <cite>&#8216;s&#8217;</cite> if you expect a string result,
or <cite>&#8216;i&#8217;</cite> if you expect an integer result.</td>
</tr>
</tbody>
</table>
<p><strong>Example Program</strong></p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>

<span class="c"># Retrieving an integer info item is quite simple.</span>
<span class="n">bytesInUse</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">database_info</span><span class="p">(</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_current_memory</span><span class="p">,</span> <span class="s">&#39;i&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="s">&#39;The server is currently using </span><span class="si">%d</span><span class="s"> bytes of memory.&#39;</span> <span class="o">%</span> <span class="n">bytesInUse</span>

<span class="c"># Retrieving a string info item is somewhat more involved, because the</span>
<span class="c"># information is returned in a raw binary buffer that must be parsed</span>
<span class="c"># according to the rules defined in the Interbase® 6 API Guide section</span>
<span class="c"># entitled &quot;Requesting buffer items and result buffer values&quot; (page 51).</span>
<span class="c">#</span>
<span class="c"># Often, the buffer contains a succession of length-string pairs</span>
<span class="c"># (one byte telling the length of s, followed by s itself).</span>
<span class="c"># Function kinterbasdb.raw_byte_to_int is provided to convert a raw</span>
<span class="c"># byte to a Python integer (see examples below).</span>
<span class="n">buf</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">database_info</span><span class="p">(</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_db_id</span><span class="p">,</span> <span class="s">&#39;s&#39;</span><span class="p">)</span>

<span class="c"># Parse the filename from the buffer.</span>
<span class="n">beginningOfFilename</span> <span class="o">=</span> <span class="mf">2</span>
<span class="c"># The second byte in the buffer contains the size of the database filename</span>
<span class="c"># in bytes.</span>
<span class="n">lengthOfFilename</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">raw_byte_to_int</span><span class="p">(</span><span class="n">buf</span><span class="p">[</span><span class="mf">1</span><span class="p">])</span>
<span class="n">filename</span> <span class="o">=</span> <span class="n">buf</span><span class="p">[</span><span class="n">beginningOfFilename</span><span class="p">:</span><span class="n">beginningOfFilename</span> <span class="o">+</span> <span class="n">lengthOfFilename</span><span class="p">]</span>

<span class="c"># Parse the host name from the buffer.</span>
<span class="n">beginningOfHostName</span> <span class="o">=</span> <span class="p">(</span><span class="n">beginningOfFilename</span> <span class="o">+</span> <span class="n">lengthOfFilename</span><span class="p">)</span> <span class="o">+</span> <span class="mf">1</span>
<span class="c"># The first byte after the end of the database filename contains the size</span>
<span class="c"># of the host name in bytes.</span>
<span class="n">lengthOfHostName</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">raw_byte_to_int</span><span class="p">(</span><span class="n">buf</span><span class="p">[</span><span class="n">beginningOfHostName</span> <span class="o">-</span> <span class="mf">1</span><span class="p">])</span>
<span class="n">host</span> <span class="o">=</span> <span class="n">buf</span><span class="p">[</span><span class="n">beginningOfHostName</span><span class="p">:</span><span class="n">beginningOfHostName</span> <span class="o">+</span> <span class="n">lengthOfHostName</span><span class="p">]</span>

<span class="k">print</span> <span class="s">&#39;We are connected to the database at </span><span class="si">%s</span><span class="s"> on host </span><span class="si">%s</span><span class="s">.&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">host</span><span class="p">)</span>
</pre></div>
</div>
<p>Sample output:</p>
<div class="highlight-python"><pre>The server is currently using 8931328 bytes of memory.
We are connected to the database at C:\TEMP\TEST.DB on host WEASEL.</pre>
</div>
<p>As you can see, extracting data with the <cite>database_info</cite> function is
rather clumsy. In KInterbasDB 3.2, a higher-level means of accessing
the same information is available: the <a title="kinterbasdb.Connection.db_info" class="reference internal" href="#kinterbasdb.Connection.db_info"><tt class="xref docutils literal"><span class="pre">db_info()</span></tt></a>
method. Also, the Services API (accessible to Python programmers via the
<tt class="xref docutils literal"><span class="pre">kinterbasdb.services</span></tt> module) provides high-level support for
querying database statistics and performing maintenance.</p>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.Connection.db_info">
<!--[kinterbasdb.Connection.db_info]--><tt class="descclassname">Connection.</tt><tt class="descname">db_info</tt><big>(</big><em>request</em><big>)</big><a class="headerlink" href="#kinterbasdb.Connection.db_info" title="Permalink to this definition">¶</a></dt>
<dd><p>High-level convenience wrapper around the
<a title="kinterbasdb.Connection.database_info" class="reference internal" href="#kinterbasdb.Connection.database_info"><tt class="xref docutils literal"><span class="pre">database_info()</span></tt></a> method that parses the output
of <cite>database_info</cite> into Python-friendly objects instead of returning raw binary
uffers in the case of complex result types. If an unrecognized <cite>isc_info_*</cite> code
is requested, this method raises <cite>ValueError</cite>.</p>
<p>For example, requesting <tt class="xref docutils literal"><span class="pre">isc_info_user_names</span></tt> with the call</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">con</span><span class="o">.</span><span class="n">db_info</span><span class="p">(</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_user_names</span><span class="p">)</span>
</pre></div>
</div>
<p>returns a dictionary that maps (username -&gt; number of open
connections). If <cite>SYSDBA</cite> has one open connection to the database to
which <cite>con</cite> is connected, and <cite>TEST_USER_1</cite> has three open connections
to that same database, the return value would be <cite>{&#8216;SYSDBA&#8217;: 1,
&#8216;TEST_USER_1&#8217;: 3}</cite></p>
<p>Arguments:</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Request:</th><td class="field-body"><p class="first">must be either:</p>
<ul class="last simple">
<li>A single <cite>kinterbasdb.isc_info_*</cite> info request code.
In this case, a single result is returned.</li>
<li>A sequence of such codes. In this case, a mapping of
(info request code -&gt; result) is returned.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p><strong>Example Program</strong></p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os.path</span>

<span class="kn">import</span> <span class="nn">kinterbasdb</span>

<span class="n">DB_FILENAME</span> <span class="o">=</span> <span class="s">r&#39;D:\temp\test-20.firebird&#39;</span>
<span class="n">DSN</span> <span class="o">=</span> <span class="s">&#39;localhost:&#39;</span> <span class="o">+</span> <span class="n">DB_FILENAME</span>

<span class="c">###############################################################################</span>
<span class="c"># Querying an isc_info_* item that has a complex result:</span>
<span class="c">###############################################################################</span>
<span class="c"># Establish three connections to the test database as TEST_USER_1, and one</span>
<span class="c"># connection as SYSDBA.  Then use the Connection.db_info method to query the</span>
<span class="c"># number of attachments by each user to the test database.</span>
<span class="n">testUserCons</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mf">3</span><span class="p">):</span>
    <span class="n">tCon</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="n">DSN</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;test_user_1&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;pass&#39;</span><span class="p">)</span>
    <span class="n">testUserCons</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">tCon</span><span class="p">)</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="n">DSN</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="s">&#39;Open connections to this database:&#39;</span>
<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">db_info</span><span class="p">(</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_user_names</span><span class="p">)</span>

<span class="c">###############################################################################</span>
<span class="c"># Querying multiple isc_info_* items at once:</span>
<span class="c">###############################################################################</span>
<span class="c"># Request multiple db_info items at once, specifically the page size of the</span>
<span class="c"># database and the number of pages currently allocated.  Compare the size</span>
<span class="c"># computed by that method with the size reported by the file system.</span>
<span class="c"># The advantages of using db_info instead of the file system to compute</span>
<span class="c"># database size are:</span>
<span class="c">#   - db_info works seamlessly on connections to remote databases that reside</span>
<span class="c">#     in file systems to which the client program lacks access.</span>
<span class="c">#   - If the database is split across multiple files, db_info includes all of</span>
<span class="c">#     them.</span>
<span class="n">res</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">db_info</span><span class="p">(</span>
    <span class="p">[</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_page_size</span><span class="p">,</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_allocation</span><span class="p">]</span>
  <span class="p">)</span>
<span class="n">pagesAllocated</span> <span class="o">=</span> <span class="n">res</span><span class="p">[</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_allocation</span><span class="p">]</span>
<span class="n">pageSize</span> <span class="o">=</span> <span class="n">res</span><span class="p">[</span><span class="n">kinterbasdb</span><span class="o">.</span><span class="n">isc_info_page_size</span><span class="p">]</span>
<span class="k">print</span> <span class="s">&#39;</span><span class="se">\n</span><span class="s">db_info indicates database size is&#39;</span><span class="p">,</span> <span class="n">pageSize</span> <span class="o">*</span> <span class="n">pagesAllocated</span><span class="p">,</span> <span class="s">&#39;bytes&#39;</span>
<span class="k">print</span>   <span class="s">&#39;os.path.getsize indicates size is &#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">getsize</span><span class="p">(</span><span class="n">DB_FILENAME</span><span class="p">),</span> <span class="s">&#39;bytes&#39;</span>
</pre></div>
</div>
<p>Sample output:</p>
<div class="highlight-python"><pre>  Open connections to this database:
  {'SYSDBA': 1, 'TEST_USER_1': 3}

db_info indicates database size is 20684800 bytes
os.path.getsize indicates size is  20684800 bytes</pre>
</div>
</dd></dl>

</div>
<div class="section" id="module-kinterbasdb.services">
<h2>Using Firebird Services API<a class="headerlink" href="#module-kinterbasdb.services" title="Permalink to this headline">¶</a></h2>
<p>Database server maintenance tasks such as user management, load
monitoring, and database backup have traditionally been automated by
scripting the command-line tools <strong>gbak</strong>, <strong>gfix</strong>,
<strong>gsec</strong>, and <strong>gstat</strong>.</p>
<p>The API presented to the client programmer by these utilities is
inelegant because they are, after all, command-line tools rather than
native components of the client language. To address this problem,
Firebird has a facility called the Services API, which exposes a uniform
interface to the administrative functionality of the traditional
command-line tools.</p>
<p>The native Services API, though consistent, is much lower-level than a
Pythonic API. If the native version were exposed directly,
accomplishing a given task would probably require more Python code
than scripting the traditional command-line tools. For this reason,
KInterbasDB presents its own abstraction over the native API via the
<tt class="xref docutils literal"><span class="pre">kinterbasdb.services</span></tt> module.</p>
<div class="section" id="establishing-services-api-connections">
<h3>Establishing Services API Connections<a class="headerlink" href="#establishing-services-api-connections" title="Permalink to this headline">¶</a></h3>
<p>All Services API operations are performed in the context of a
connection to a specific database server, represented by the
<a title="kinterbasdb.services.Connection" class="reference internal" href="#kinterbasdb.services.Connection"><tt class="xref docutils literal"><span class="pre">kinterbasdb.services.Connection</span></tt></a> class.</p>
<dl class="function">
<dt id="kinterbasdb.services.connect">
<!--[kinterbasdb.services.connect]--><tt class="descclassname">kinterbasdb.services.</tt><tt class="descname">connect</tt><big>(</big><em>host='service_mgr'</em>, <em>user='sysdba'</em>, <em>password=None</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.connect" title="Permalink to this definition">¶</a></dt>
<dd><p>Establish a connection to database server Services and returns
<a title="kinterbasdb.services.Connection" class="reference internal" href="#kinterbasdb.services.Connection"><tt class="xref docutils literal"><span class="pre">kinterbasdb.services.Connection</span></tt></a> object.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Host:</th><td class="field-body">The network name of the computer on which the database
server is running.</td>
</tr>
<tr class="field"><th class="field-name">User:</th><td class="field-body">The name of the database user under whose authority the
maintenance tasks are to be performed.</td>
</tr>
<tr class="field"><th class="field-name">Password:</th><td class="field-body">User&#8217;s password.</td>
</tr>
</tbody>
</table>
<p>Since maintenance operations are most often initiated by an
administrative user on the same computer as the database server,
<cite>host</cite> defaults to the local computer, and <cite>user</cite> defaults to
<cite>SYSDBA</cite>.</p>
<p>The three calls to <cite>kinterbasdb.services.connect()</cite> in the following
program are equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="class">
<dt id="kinterbasdb.services.Connection">
<!--[kinterbasdb.services.Connection]-->class <tt class="descclassname">kinterbasdb.services.</tt><tt class="descname">Connection</tt><a class="headerlink" href="#kinterbasdb.services.Connection" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="kinterbasdb.services.Connection.close">
<!--[kinterbasdb.services.Connection.close]--><tt class="descname">close</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.close" title="Permalink to this definition">¶</a></dt>
<dd>Explicitly terminates a <a title="kinterbasdb.services.Connection" class="reference internal" href="#kinterbasdb.services.Connection"><tt class="xref docutils literal"><span class="pre">Connection</span></tt></a>;
if this is not invoked, the underlying connection will be closed implicitly
when the <cite>Connection</cite> object is garbage collected.</dd></dl>

</dd></dl>

</div>
<div class="section" id="server-configuration-and-activity-levels">
<h3>Server Configuration and Activity Levels<a class="headerlink" href="#server-configuration-and-activity-levels" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="kinterbasdb.services.Connection.getServiceManagerVersion">
<!--[kinterbasdb.services.Connection.getServiceManagerVersion]--><tt class="descclassname">Connection.</tt><tt class="descname">getServiceManagerVersion</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getServiceManagerVersion" title="Permalink to this definition">¶</a></dt>
<dd><p>To help client programs adapt to version changes, the service manager
exposes its version number as an integer.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getServiceManagerVersion</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on Firebird 1.5.0):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="mf">2</span>
</pre></div>
</div>
<p><cite>kinterbasdb.services</cite> is a thick wrapper of the Services API that can
shield its users from changes in the underlying C API, so this method
is unlikely to be useful to the typical Python client programmer.</p>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getServerVersion">
<!--[kinterbasdb.services.Connection.getServerVersion]--><tt class="descclassname">Connection.</tt><tt class="descname">getServerVersion</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getServerVersion" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the server&#8217;s version string:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getServerVersion</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on Firebird 1.5.0/Win32):</p>
<div class="highlight-python"><pre>WI-V1.5.0.4290 Firebird 1.5</pre>
</div>
<p>At first glance, thhis method appears to duplicate the functionality of the
<a title="kinterbasdb.Connection.server_version" class="reference external" href="python-db-api-compliance.html#kinterbasdb.Connection.server_version"><tt class="xref docutils literal"><span class="pre">kinterbasdb.Connection.server_version</span></tt></a> property, but when working
with Firebird, there is a difference. <a title="kinterbasdb.Connection.server_version" class="reference external" href="python-db-api-compliance.html#kinterbasdb.Connection.server_version"><tt class="xref docutils literal"><span class="pre">kinterbasdb.Connection.server_version</span></tt></a>
is based on a C API call (<tt class="xref docutils literal"><span class="pre">isc_database_info()</span></tt>) that existed long before
the introduction of the Services API. Some programs written before the advent
of Firebird test the version number in the return value of <tt class="xref docutils literal"><span class="pre">isc_database_info()</span></tt>,
and refuse to work if it indicates that the server is too old. Since the first
stable version of Firebird was labeled <cite>1.0</cite>, this pre-Firebird version testing
scheme incorrectly concludes that (e.g.) Firebird 1.0 is older than Interbase 5.0.</p>
<p>Firebird addresses this problem by making <tt class="xref docutils literal"><span class="pre">isc_database_info()</span></tt> return a
&#8220;pseudo-InterBase&#8221; version number, whereas the Services API returns
the true Firebird version, as shown:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:C:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Interbase-compatible version string:&#39;</span><span class="p">,</span> <span class="n">con</span><span class="o">.</span><span class="n">server_version</span>

<span class="kn">import</span> <span class="nn">kinterbasdb.services</span>
<span class="n">svcCon</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Actual Firebird version string:     &#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getServerVersion</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on Firebird 1.5.0/Win32):</p>
<div class="highlight-python"><pre>Interbase-compatible version string: WI-V6.3.0.4290 Firebird 1.5
Actual Firebird version string:      WI-V1.5.0.4290 Firebird 1.5</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getArchitecture">
<!--[kinterbasdb.services.Connection.getArchitecture]--><tt class="descclassname">Connection.</tt><tt class="descname">getArchitecture</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getArchitecture" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns platform information for the server, including hardware architecture
and operating system family.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getArchitecture</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on Firebird 1.5.0/Windows 2000):</p>
<div class="highlight-python"><pre>Firebird/x86/Windows NT</pre>
</div>
<p>Unfortunately, the architecture string is almost useless because its
format is irregular and sometimes outright idiotic, as with Firebird
1.5.0 running on x86 Linux:</p>
<div class="highlight-python"><pre>Firebird/linux Intel</pre>
</div>
<p>Magically, Linux becomes a hardware architecture, the ASCII store
decides to hold a 31.92% off sale, and Intel grabs an unfilled niche
in the operating system market.</p>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getHomeDir">
<!--[kinterbasdb.services.Connection.getHomeDir]--><tt class="descclassname">Connection.</tt><tt class="descname">getHomeDir</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getHomeDir" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the equivalent of the <cite>RootDirectory</cite> setting from <tt class="docutils literal"><span class="pre">firebird.conf</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getHomeDir</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on a particular Firebird 1.5.0/Windows 2000 installation):</p>
<div class="highlight-python"><pre>C:\dev\db\firebird150\</pre>
</div>
<p>Output (on a particular Firebird 1.5.0/Linux installation):</p>
<div class="highlight-python"><pre>/opt/firebird/</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getSecurityDatabasePath">
<!--[kinterbasdb.services.Connection.getSecurityDatabasePath]--><tt class="descclassname">Connection.</tt><tt class="descname">getSecurityDatabasePath</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getSecurityDatabasePath" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the location of the server&#8217;s core security database, which contains
user definitions and such. Interbase® and Firebird 1.0 named this database
<tt class="docutils literal"><span class="pre">isc4.gdb</span></tt>, while in Firebird 1.5 it&#8217;s renamed to <tt class="docutils literal"><span class="pre">security.fdb</span></tt>
and to <tt class="docutils literal"><span class="pre">security2.fdb</span></tt> in Firebird 2.0 and later.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getSecurityDatabasePath</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on a particular Firebird 1.5.0/Windows 2000 installation):</p>
<div class="highlight-python"><pre>C:\dev\db\firebird150\security.fdb</pre>
</div>
<p>Output (on a particular Firebird 1.5.0/Linux installation):</p>
<div class="highlight-python"><pre>/opt/firebird/security.fdb</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getLockFileDir">
<!--[kinterbasdb.services.Connection.getLockFileDir]--><tt class="descclassname">Connection.</tt><tt class="descname">getLockFileDir</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getLockFileDir" title="Permalink to this definition">¶</a></dt>
<dd><p>The database engine <a class="reference external" href="http://www.ibphoenix.com/main.nfs?a=ibphoenix&amp;page=ibp_locking">uses a lock file</a> to
coordinate interprocess communication; <cite>getLockFileDir()</cite> returns the
directory in which that file resides:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getLockFileDir</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on a particular Firebird 1.5.0/Windows 2000 installation):</p>
<div class="highlight-python"><pre>C:\dev\db\firebird150\</pre>
</div>
<p>Output (on a particular Firebird 1.5.0/Linux installation):</p>
<div class="highlight-python"><pre>/opt/firebird/</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getCapabilityMask">
<!--[kinterbasdb.services.Connection.getCapabilityMask]--><tt class="descclassname">Connection.</tt><tt class="descname">getCapabilityMask</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getCapabilityMask" title="Permalink to this definition">¶</a></dt>
<dd>The Services API offers &#8220;a bitmask representing the capabilities
currently enabled on the server&#8221;, but the only availabledocumentation
for this bitmask suggests that it is &#8220;reserved for future implementation&#8221;.
kinterbasdb exposes this bitmask as a Python <cite>int</cite> returned from the
<cite>getCapabilityMask()</cite> method.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getMessageFileDir">
<!--[kinterbasdb.services.Connection.getMessageFileDir]--><tt class="descclassname">Connection.</tt><tt class="descname">getMessageFileDir</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getMessageFileDir" title="Permalink to this definition">¶</a></dt>
<dd><p>To support internationalized error messages/prompts, the database
engine stores its messages in a file named <tt class="docutils literal"><span class="pre">interbase.msg</span></tt>
(Interbase® and Firebird 1.0) or <tt class="docutils literal"><span class="pre">firebird.msg</span></tt> (Firebird 1.5 and
later). The directory in which this file resides can be determined
with the <cite>getMessageFileDir()</cite> method.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getMessageFileDir</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on a particular Firebird 1.5.0/Windows 2000 installation):</p>
<div class="highlight-python"><pre>C:\dev\db\firebird150\</pre>
</div>
<p>Output (on a particular Firebird 1.5.0/Linux installation):</p>
<div class="highlight-python"><pre>/opt/firebird/</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getConnectionCount">
<!--[kinterbasdb.services.Connection.getConnectionCount]--><tt class="descclassname">Connection.</tt><tt class="descname">getConnectionCount</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getConnectionCount" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of active connections to databases managed by the server.
This count only includes <em>database</em> connections (such as open instances of
<a title="kinterbasdb.Connection" class="reference internal" href="#kinterbasdb.Connection"><tt class="xref docutils literal"><span class="pre">kinterbasdb.Connection</span></tt></a>), not <em>services manager</em> connections (such
as open instances of <a title="kinterbasdb.services.Connection" class="reference internal" href="#kinterbasdb.services.Connection"><tt class="xref docutils literal"><span class="pre">kinterbasdb.services.Connection</span></tt></a>).</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span><span class="o">,</span> <span class="nn">kinterbasdb.services</span>
<span class="n">svcCon</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="s">&#39;A:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getConnectionCount</span><span class="p">()</span>

<span class="n">con1</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:C:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;B:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getConnectionCount</span><span class="p">()</span>

<span class="n">con2</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:C:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;C:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getConnectionCount</span><span class="p">()</span>

<span class="n">con1</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;D:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getConnectionCount</span><span class="p">()</span>

<span class="n">con2</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;E:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getConnectionCount</span><span class="p">()</span>
</pre></div>
</div>
<p>On an otherwise inactive server, the example program generates the
following output:</p>
<div class="highlight-python"><pre>A: 0
B: 1
C: 2
D: 1
E: 0</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getAttachedDatabaseNames">
<!--[kinterbasdb.services.Connection.getAttachedDatabaseNames]--><tt class="descclassname">Connection.</tt><tt class="descname">getAttachedDatabaseNames</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getAttachedDatabaseNames" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a list of the names of all databases to which the server is
maintaining at least one connection. The database names are not guaranteed
to be in any particular order.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">kinterbasdb</span><span class="o">,</span> <span class="nn">kinterbasdb.services</span>
<span class="n">svcCon</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="s">&#39;A:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getAttachedDatabaseNames</span><span class="p">()</span>

<span class="n">con1</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:C:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;B:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getAttachedDatabaseNames</span><span class="p">()</span>

<span class="n">con2</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:C:/temp/test2.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;C:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getAttachedDatabaseNames</span><span class="p">()</span>

<span class="n">con3</span> <span class="o">=</span> <span class="n">kinterbasdb</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">dsn</span><span class="o">=</span><span class="s">&#39;localhost:C:/temp/test2.db&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;D:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getAttachedDatabaseNames</span><span class="p">()</span>

<span class="n">con1</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;E:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getAttachedDatabaseNames</span><span class="p">()</span>

<span class="n">con2</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;F:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getAttachedDatabaseNames</span><span class="p">()</span>

<span class="n">con3</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;G:&#39;</span><span class="p">,</span> <span class="n">svcCon</span><span class="o">.</span><span class="n">getAttachedDatabaseNames</span><span class="p">()</span>
</pre></div>
</div>
<p>On an otherwise inactive server, the example program generates the
following output:</p>
<div class="highlight-python"><pre>A: []
B: ['C:\\TEMP\\TEST.DB']
C: ['C:\\TEMP\\TEST2.DB', 'C:\\TEMP\\TEST.DB']
D: ['C:\\TEMP\\TEST2.DB', 'C:\\TEMP\\TEST.DB']
E: ['C:\\TEMP\\TEST2.DB']
F: ['C:\\TEMP\\TEST2.DB']
G: []</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.getLog">
<!--[kinterbasdb.services.Connection.getLog]--><tt class="descclassname">Connection.</tt><tt class="descname">getLog</tt><big>(</big><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getLog" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the contents of the server&#8217;s log file (named <tt class="docutils literal"><span class="pre">interbase.log</span></tt>
by Interbase® and Firebird 1.0; <tt class="docutils literal"><span class="pre">firebird.log</span></tt> by Firebird 1.5 and later):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getLog</span><span class="p">()</span>
</pre></div>
</div>
<p>Output (on a particular Firebird 1.5.0/Windows 2000 installation):</p>
<div class="highlight-python"><pre>WEASEL (Client) Thu Jun 03 12:01:35 2004
  INET/inet_error: send errno = 10054

WEASEL (Client) Sun Jun 06 19:21:17 2004
  INET/inet_error: connect errno = 10061</pre>
</div>
</dd></dl>

</div>
<div class="section" id="database-statistics">
<h3>Database Statistics<a class="headerlink" href="#database-statistics" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="kinterbasdb.services.Connection.getStatistics">
<!--[kinterbasdb.services.Connection.getStatistics]--><tt class="descclassname">Connection.</tt><tt class="descname">getStatistics</tt><big>(</big><em>database</em>, <em>showOnlyDatabaseLogPages=0...</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.getStatistics" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string containing a printout in the same format as the output
of the <strong>gstat</strong> command-line utility. This method has one required
parameter, the location of the database on which to compute statistics,
and five optional boolean parameters for controlling the domain of the
statistics.</p>
<p><strong>Map of gstat paremeters to getStatistics options</strong></p>
<table border="1" class="docutils">
<colgroup>
<col width="43%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head"><cite>gstat</cite> command-line option</th>
<th class="head"><cite>getStatistics</cite> boolean parameter</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>-header</td>
<td>showOnlyDatabaseHeaderPages</td>
</tr>
<tr><td>-log</td>
<td>showOnlyDatabaseLogPages</td>
</tr>
<tr><td>-data</td>
<td>showUserDataPages</td>
</tr>
<tr><td>-index</td>
<td>showUserIndexPages</td>
</tr>
<tr><td>-system</td>
<td>showSystemTablesAndIndexes</td>
</tr>
</tbody>
</table>
<p>The following program presents several <cite>getStatistics</cite> calls and their
<cite>gstat</cite>-command-line equivalents. In this context, output is
considered &#8220;equivalent&#8221; even if their are some whitespace differences.
When collecting textual output from the Services API, kinterbasdb
terminates lines with <cite>n</cite> regardless of the platform&#8217;s convention;
<cite>gstat</cite> is platform-sensitive.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="c"># Equivalent to &#39;gstat -u sysdba -p masterkey C:/temp/test.db&#39;:</span>
<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getStatistics</span><span class="p">(</span><span class="s">&#39;C:/temp/test.db&#39;</span><span class="p">)</span>

<span class="c"># Equivalent to &#39;gstat -u sysdba -p masterkey -header C:/temp/test.db&#39;:</span>
<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getStatistics</span><span class="p">(</span><span class="s">&#39;C:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">showOnlyDatabaseHeaderPages</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

<span class="c"># Equivalent to &#39;gstat -u sysdba -p masterkey -log C:/temp/test.db&#39;:</span>
<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getStatistics</span><span class="p">(</span><span class="s">&#39;C:/temp/test.db&#39;</span><span class="p">,</span> <span class="n">showOnlyDatabaseLogPages</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

<span class="c"># Equivalent to &#39;gstat -u sysdba -p masterkey -data -index -system C:/temp/test.db&#39;:</span>
<span class="k">print</span> <span class="n">con</span><span class="o">.</span><span class="n">getStatistics</span><span class="p">(</span><span class="s">&#39;C:/temp/test.db&#39;</span><span class="p">,</span>
    <span class="n">showUserDataPages</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">showUserIndexPages</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">showSystemTablesAndIndexes</span><span class="o">=</span><span class="bp">True</span>
  <span class="p">)</span>
</pre></div>
</div>
<p>The output of the example program is not shown here because it is
quite long.</p>
</dd></dl>

</div>
<div class="section" id="backup-and-restoration">
<h3>Backup and Restoration<a class="headerlink" href="#backup-and-restoration" title="Permalink to this headline">¶</a></h3>
<p>KInterbasDB offers convenient programmatic control over database
backup and restoration via the <cite>backup</cite> and <cite>restore</cite> methods.</p>
<p>At the time of this writing, released versions of Firebird/Interbase®
do not implement incremental backup, so we can simplistically define
<em>backup</em> as the process of generating and storing an archived replica
of a live database, and <em>restoration</em> as the inverse. The
backup/restoration process exposes numerous parameters, which are
properly documented in Firebird Documentation to <strong>gbak</strong>.
The KInterbasDB API to these parameters is presented with minimal
documentation in the sample code below.</p>
<dl class="method">
<dt id="kinterbasdb.services.Connection.backup">
<!--[kinterbasdb.services.Connection.backup]--><tt class="descclassname">Connection.</tt><tt class="descname">backup</tt><big>(</big><em>sourceDatabase</em>, <em>destFilenames</em>, <em>destFileSizes=()</em>, <em>&lt;options&gt;</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.backup" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a backup file from database content.</p>
<p><strong>Simple Form</strong></p>
<p>The simplest form of <cite>backup</cite> creates a single backup file that
contains everything in the database. Although the extension <cite>&#8216;.fbk&#8217;</cite>
is conventional, it is not required.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="n">backupLog</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">backup</span><span class="p">(</span><span class="s">&#39;C:/temp/test.db&#39;</span><span class="p">,</span> <span class="s">&#39;C:/temp/test_backup.fbk&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">backupLog</span>
</pre></div>
</div>
<p>In the example, <cite>backupLog</cite> is a string containing a <cite>gbak</cite>-style log
of the backup process. It is too long to reproduce here.</p>
<p>Although the return value of the <cite>backup</cite> method is a freeform log
string, <cite>backup</cite> will raise an exception if there is an error. For
example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="c"># Pass an invalid backup path to the engine:</span>
<span class="n">backupLog</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">backup</span><span class="p">(</span><span class="s">&#39;C:/temp/test.db&#39;</span><span class="p">,</span> <span class="s">&#39;BOGUS/PATH/test_backup.fbk&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">backupLog</span>
</pre></div>
</div>
<div class="highlight-python"><pre>Traceback (most recent call last):
  File "adv_services_backup_simplest_witherror.py", line 5, in ?
    backupLog = con.backup('C:/temp/test.db', 'BOGUS/PATH/test_backup.fbk')
  File "C:\code\projects\kinterbasdb\Kinterbasdb-3.0\build\lib.win32-2.3\kinterbasdb\services.py", line 269, in backup
    return self._actAndReturnTextualResults(request)
  File "C:\code\projects\kinterbasdb\Kinterbasdb-3.0\build\lib.win32-2.3\kinterbasdb\services.py", line 613, in _actAndReturnTextualResults
    self._act(requestBuffer)
  File "C:\code\projects\kinterbasdb\Kinterbasdb-3.0\build\lib.win32-2.3\kinterbasdb\services.py", line 610, in _act
    return _ksrv.action_thin(self._C_conn, requestBuffer.render())
kinterbasdb.OperationalError: (-902, '_kiservices could not perform the action: cannot open backup file BOGUS/PATH/test_backup.fbk. ')</pre>
</div>
<p><strong>Multifile Form</strong></p>
<p>The database engine has built-in support for splitting the backup into
multiple files, which is useful for circumventing operating system
file size limits or spreading the backup across multiple discs.</p>
<p>KInterbasDB exposes this facility via the <cite>Connection.backup</cite>
parameters <cite>destFilenames</cite> and <cite>destFileSizes</cite>. <cite>destFilenames</cite> (the
second positional parameter of <cite>Connection.backup</cite>) can be either a
string (as in the example above, when creating the backup as a single
file) or a sequence of strings naming each constituent file of the
backup. If <cite>destFilenames</cite> is a string-sequence with length <cite>N</cite>,
<cite>destFileSizes</cite> must be a sequence of integer file sizes (in bytes)
with length <cite>N-1</cite>. The database engine will constrain the size of each
backup constituent file named in <cite>destFilenames[:-1]</cite> to the
corresponding size specified in <cite>destFileSizes</cite>; any remaining backup
data will be placed in the file name by <cite>destFilenames[-1]</cite>.</p>
<p>Unfortunately, the database engine does not appear to expose any
convenient means of calculating the total size of a database backup
before its creation. The page size of the database and the number of
pages in the database are available via
<a title="kinterbasdb.Connection.database_info" class="reference internal" href="#kinterbasdb.Connection.database_info"><tt class="xref docutils literal"><span class="pre">database_info()</span></tt></a> calls:
<cite>database_info(kinterbasdb.isc_info_page_size, &#8216;i&#8217;)</cite> and
<cite>database_info(kinterbasdb.isc_info_db_size_in_pages, &#8216;i&#8217;)</cite>,
respectively, but the size of the backup file is usually smaller than
the size of the database.</p>
<p>There <em>should</em> be no harm in submitting too many constituent
specifications; the engine will write an empty header record into the
excess constituents. However, at the time of this writing, released
versions of the database engine hang the backup task if more than 11
constituents are specified (that is, if <cite>len(destFilenames) &gt; 11</cite>).
KInterbasDB does not prevent the programmer from submitting more than
11 constituents, but it does issue a warning.</p>
<p>The following program directs the engine to split the backup of the
database at <tt class="docutils literal"><span class="pre">C:/temp/test.db</span></tt> into <tt class="docutils literal"><span class="pre">C:/temp/back01.fbk</span></tt>,
a file 4096 bytes in size, <tt class="docutils literal"><span class="pre">C:/temp/back02.fbk</span></tt>, a file 16384 bytes
in size, and <tt class="docutils literal"><span class="pre">C:/temp/back03.fbk</span></tt>, a file containing the remainder of
the backup data.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="n">con</span><span class="o">.</span><span class="n">backup</span><span class="p">(</span><span class="s">&#39;C:/temp/test.db&#39;</span><span class="p">,</span>
   <span class="p">(</span><span class="s">&#39;C:/temp/back01.fbk&#39;</span><span class="p">,</span> <span class="s">&#39;C:/temp/back02.fbk&#39;</span><span class="p">,</span> <span class="s">&#39;C:/temp/back03.fbk&#39;</span><span class="p">),</span>
    <span class="n">destFileSizes</span><span class="o">=</span><span class="p">(</span><span class="mf">4096</span><span class="p">,</span> <span class="mf">16384</span><span class="p">)</span>
  <span class="p">)</span>
</pre></div>
</div>
<p><strong>Extended Options</strong></p>
<p>In addition to the three parameters documented previously (positional
<cite>sourceDatabase</cite>, positional <cite>destFilenames</cite>, and keyword
<cite>destFileSizes</cite>), the <cite>Connection.backup</cite> method accepts six boolean
parameters that control aspects of the backup process and the backup
file output format. These options are well documented so in this
document we present only a table of equivalence between <strong>gbak</strong>
options and names of the boolean keyword parameters:</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="54%" />
<col width="25%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head"><cite>gbak</cite> option</th>
<th class="head">Parameter Name</th>
<th class="head">Default Value</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>-T</td>
<td>transportable</td>
<td>True</td>
</tr>
<tr><td>-M</td>
<td>metadataOnly</td>
<td>False</td>
</tr>
<tr><td>-G</td>
<td>garbageCollect</td>
<td>True</td>
</tr>
<tr><td>-L</td>
<td>ignoreLimboTransactions</td>
<td>False</td>
</tr>
<tr><td>-IG</td>
<td>ignoreChecksums</td>
<td>False</td>
</tr>
<tr><td>-CO</td>
<td>convertExternalTablesToInternalTables</td>
<td>True</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.restore">
<!--[kinterbasdb.services.Connection.restore]--><tt class="descclassname">Connection.</tt><tt class="descname">restore</tt><big>(</big><em>sourceFilenames</em>, <em>destFilenames</em>, <em>destFilePages=()</em>, <em>&lt;options&gt;</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.restore" title="Permalink to this definition">¶</a></dt>
<dd><p>Restores database from backup file.</p>
<p><strong>Simplest Form</strong></p>
<p>The simplest form of <cite>restore</cite> creates a single-file database,
regardless of whether the backup data were split across multiple
files.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="n">restoreLog</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">restore</span><span class="p">(</span><span class="s">&#39;C:/temp/test_backup.fbk&#39;</span><span class="p">,</span> <span class="s">&#39;C:/temp/test_restored.db&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">restoreLog</span>
</pre></div>
</div>
<p>In the example, <cite>restoreLog</cite> is a string containing a <cite>gbak</cite>-style log
of the restoration process. It is too long to reproduce here.</p>
<p><strong>Multifile Form</strong></p>
<p>The database engine has built-in support for splitting the restored
database into multiple files, which is useful for circumventing
operating system file size limits or spreading the database across
multiple discs.</p>
<p>KInterbasDB exposes this facility via the <cite>Connection.restore</cite>
parameters <cite>destFilenames</cite> and <cite>destFilePages</cite>. <cite>destFilenames</cite> (the
second positional argument of <cite>Connection.restore</cite>) can be either a
string (as in the example above, when restoring to a single database
file) or a sequence of strings naming each constituent file of the
restored database. If <cite>destFilenames</cite> is a string-sequence with length
<cite>N</cite>, <cite>destFilePages</cite> must be a sequence of integers with length <cite>N-1</cite>.
The database engine will constrain the size of each database
constituent file named in <cite>destFilenames[:-1]</cite> to the corresponding
page count specified in <cite>destFilePages</cite>; any remaining database pages
will be placed in the file name by <cite>destFilenames[-1]</cite>.</p>
<p>The following program directs the engine to restore the backup file at
<tt class="docutils literal"><span class="pre">C:/temp/test_backup.fbk</span></tt> into a database with three constituent
files: <tt class="docutils literal"><span class="pre">C:/temp/test_restored01.db</span></tt>, <tt class="docutils literal"><span class="pre">C:/temp/test_restored02.db</span></tt>,
and <tt class="docutils literal"><span class="pre">C:/temp/test_restored03.db</span></tt>. The engine is instructed to place
fifty user data pages in the first file, seventy in the second, and
the remainder in the third file. In practice, the first database
constituent file will be larger than <cite>pageSize*destFilePages[0]</cite>,
because metadata pages must also be stored in the first constituent of
a multifile database.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">kinterbasdb</span> <span class="kn">import</span> <span class="n">services</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">services</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">user</span><span class="o">=</span><span class="s">&#39;sysdba&#39;</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">&#39;masterkey&#39;</span><span class="p">)</span>

<span class="n">con</span><span class="o">.</span><span class="n">restore</span><span class="p">(</span><span class="s">&#39;C:/temp/test_backup.fbk&#39;</span><span class="p">,</span>
    <span class="p">(</span><span class="s">&#39;C:/temp/test_restored01.db&#39;</span><span class="p">,</span> <span class="s">&#39;C:/temp/test_restored02.db&#39;</span><span class="p">,</span> <span class="s">&#39;C:/temp/test_restored03.db&#39;</span><span class="p">),</span>
    <span class="n">destFilePages</span><span class="o">=</span><span class="p">(</span><span class="mf">50</span><span class="p">,</span> <span class="mf">70</span><span class="p">),</span>
    <span class="n">pageSize</span><span class="o">=</span><span class="mf">1024</span><span class="p">,</span>
    <span class="n">replace</span><span class="o">=</span><span class="bp">True</span>
  <span class="p">)</span>
</pre></div>
</div>
<p><strong>Extended Options</strong></p>
<p>These options are well documented so in this document we present only
a table of equivalence between the <strong>gbak</strong> options
and the names of the keyword parameters to <cite>Connection.restore</cite>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="52%" />
<col width="28%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head"><cite>gbak</cite> option</th>
<th class="head">Parameter Name</th>
<th class="head">Default Value</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>-P</td>
<td>pageSize</td>
<td>[use server default]</td>
</tr>
<tr><td>-REP</td>
<td>replace</td>
<td>False</td>
</tr>
<tr><td>-O</td>
<td>commitAfterEachTable</td>
<td>False</td>
</tr>
<tr><td>-K</td>
<td>doNotRestoreShadows</td>
<td>False</td>
</tr>
<tr><td>-I</td>
<td>deactivateIndexes</td>
<td>False</td>
</tr>
<tr><td>-N</td>
<td>doNotEnforceConstraints</td>
<td>False</td>
</tr>
<tr><td>-USE</td>
<td>useAllPageSpace</td>
<td>False</td>
</tr>
<tr><td>-MO</td>
<td>accessModeReadOnly</td>
<td>False</td>
</tr>
<tr><td>-BU</td>
<td>cacheBuffers</td>
<td>[use server default]</td>
</tr>
</tbody>
</table>
</dd></dl>

</div>
<div class="section" id="database-operating-modes-sweeps-and-repair">
<h3>Database Operating Modes, Sweeps, and Repair<a class="headerlink" href="#database-operating-modes-sweeps-and-repair" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="kinterbasdb.services.Connection.sweep">
<!--[kinterbasdb.services.Connection.sweep]--><tt class="descclassname">Connection.</tt><tt class="descname">sweep</tt><big>(</big><em>database</em>, <em>markOutdatedRecordsAsFreeSpace=1</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.sweep" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Connection.setSweepInterval">
<!--[kinterbasdb.services.Connection.setSweepInterval]--><tt class="descclassname">Connection.</tt><tt class="descname">setSweepInterval</tt><big>(</big><em>database</em>, <em>n</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Connection.setSweepInterval" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.setDefaultPageBuffers">
<!--[kinterbasdb.services.Conenction.setDefaultPageBuffers]--><tt class="descclassname">Conenction.</tt><tt class="descname">setDefaultPageBuffers</tt><big>(</big><em>database</em>, <em>n</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.setDefaultPageBuffers" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.setShouldReservePageSpace">
<!--[kinterbasdb.services.Conenction.setShouldReservePageSpace]--><tt class="descclassname">Conenction.</tt><tt class="descname">setShouldReservePageSpace</tt><big>(</big><em>database</em>, <em>shouldReserve</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.setShouldReservePageSpace" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.setWriteMode">
<!--[kinterbasdb.services.Conenction.setWriteMode]--><tt class="descclassname">Conenction.</tt><tt class="descname">setWriteMode</tt><big>(</big><em>database</em>, <em>mode</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.setWriteMode" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.setAccessMode">
<!--[kinterbasdb.services.Conenction.setAccessMode]--><tt class="descclassname">Conenction.</tt><tt class="descname">setAccessMode</tt><big>(</big><em>database</em>, <em>mode</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.setAccessMode" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.setSQLDialect">
<!--[kinterbasdb.services.Conenction.setSQLDialect]--><tt class="descclassname">Conenction.</tt><tt class="descname">setSQLDialect</tt><big>(</big><em>database</em>, <em>dialect</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.setSQLDialect" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.activateShadowFile">
<!--[kinterbasdb.services.Conenction.activateShadowFile]--><tt class="descclassname">Conenction.</tt><tt class="descname">activateShadowFile</tt><big>(</big><em>database</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.activateShadowFile" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.shutdown">
<!--[kinterbasdb.services.Conenction.shutdown]--><tt class="descclassname">Conenction.</tt><tt class="descname">shutdown</tt><big>(</big><em>database</em>, <em>shutdownMethod</em>, <em>timeout</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.shutdown" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.bringOnline">
<!--[kinterbasdb.services.Conenction.bringOnline]--><tt class="descclassname">Conenction.</tt><tt class="descname">bringOnline</tt><big>(</big><em>database</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.bringOnline" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.getLimboTransactionIDs">
<!--[kinterbasdb.services.Conenction.getLimboTransactionIDs]--><tt class="descclassname">Conenction.</tt><tt class="descname">getLimboTransactionIDs</tt><big>(</big><em>database</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.getLimboTransactionIDs" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.commitLimboTransaction">
<!--[kinterbasdb.services.Conenction.commitLimboTransaction]--><tt class="descclassname">Conenction.</tt><tt class="descname">commitLimboTransaction</tt><big>(</big><em>database</em>, <em>transactionID</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.commitLimboTransaction" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.rollbackLimboTransaction">
<!--[kinterbasdb.services.Conenction.rollbackLimboTransaction]--><tt class="descclassname">Conenction.</tt><tt class="descname">rollbackLimboTransaction</tt><big>(</big><em>database</em>, <em>transactionID</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.rollbackLimboTransaction" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.repair">
<!--[kinterbasdb.services.Conenction.repair]--><tt class="descclassname">Conenction.</tt><tt class="descname">repair</tt><big>(</big><em>database</em>, <em>&lt;options&gt;</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.repair" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

</div>
<div class="section" id="user-maintenance">
<h3>User Maintenance<a class="headerlink" href="#user-maintenance" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="kinterbasdb.services.Conenction.getUsers">
<!--[kinterbasdb.services.Conenction.getUsers]--><tt class="descclassname">Conenction.</tt><tt class="descname">getUsers</tt><big>(</big><em>username=None</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.getUsers" title="Permalink to this definition">¶</a></dt>
<dd>By default, lists all users.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.addUser">
<!--[kinterbasdb.services.Conenction.addUser]--><tt class="descclassname">Conenction.</tt><tt class="descname">addUser</tt><big>(</big><em>user</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.addUser" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">User:</th><td class="field-body">An instance of <a title="kinterbasdb.services.User" class="reference internal" href="#kinterbasdb.services.User"><tt class="xref docutils literal"><span class="pre">User</span></tt></a> with <em>at least</em> its username
and password attributes specified as non-empty values.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.modifyUser">
<!--[kinterbasdb.services.Conenction.modifyUser]--><tt class="descclassname">Conenction.</tt><tt class="descname">modifyUser</tt><big>(</big><em>user</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.modifyUser" title="Permalink to this definition">¶</a></dt>
<dd><p>Changes user data.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">User:</th><td class="field-body">An instance of <a title="kinterbasdb.services.User" class="reference internal" href="#kinterbasdb.services.User"><tt class="xref docutils literal"><span class="pre">User</span></tt></a> with <em>at least</em> its username
and password attributes specified as non-empty values.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.removeUser">
<!--[kinterbasdb.services.Conenction.removeUser]--><tt class="descclassname">Conenction.</tt><tt class="descname">removeUser</tt><big>(</big><em>user</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.removeUser" title="Permalink to this definition">¶</a></dt>
<dd>Accepts either an instance of services.User or a string username,
and deletes the specified user.</dd></dl>

<dl class="method">
<dt id="kinterbasdb.services.Conenction.userExists">
<!--[kinterbasdb.services.Conenction.userExists]--><tt class="descclassname">Conenction.</tt><tt class="descname">userExists</tt><big>(</big><em>user</em><big>)</big><a class="headerlink" href="#kinterbasdb.services.Conenction.userExists" title="Permalink to this definition">¶</a></dt>
<dd>Returns a boolean that indicates whether the specified user exists.</dd></dl>

<dl class="class">
<dt id="kinterbasdb.services.User">
<!--[kinterbasdb.services.User]-->class <tt class="descclassname">kinterbasdb.services.</tt><tt class="descname">User</tt><a class="headerlink" href="#kinterbasdb.services.User" title="Permalink to this definition">¶</a></dt>
<dd>Not yet documented.</dd></dl>

</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">Native Database Engine Features and Extensions Beyond the Python DB API</a><ul>
<li><a class="reference external" href="#programmatic-database-creation-and-deletion">Programmatic Database Creation and Deletion</a></li>
<li><a class="reference external" href="#advanced-transaction-control">Advanced Transaction Control</a><ul>
<li><a class="reference external" href="#explicit-transaction-start">Explicit transaction start</a></li>
<li><a class="reference external" href="#transaction-parameters">Transaction Parameters</a></li>
<li><a class="reference external" href="#retaining-operations">Retaining Operations</a></li>
<li><a class="reference external" href="#savepoints">Savepoints</a></li>
<li><a class="reference external" href="#using-multiple-transactions-with-the-same-connection">Using multiple transactions with the same connection</a></li>
<li><a class="reference external" href="#distributed-transactions">Distributed Transactions</a></li>
</ul>
</li>
<li><a class="reference external" href="#prepared-statements">Prepared Statements</a></li>
<li><a class="reference external" href="#named-cursors">Named Cursors</a></li>
<li><a class="reference external" href="#parameter-conversion">Parameter Conversion</a><ul>
<li><a class="reference external" href="#implicit-conversion-of-input-parameters-from-strings">Implicit Conversion of Input Parameters from Strings</a></li>
<li><a class="reference external" href="#dynamic-type-translation">Dynamic Type Translation</a></li>
<li><a class="reference external" href="#specifics-of-the-dynamic-type-translation-api">Specifics of the Dynamic Type Translation API</a></li>
<li><a class="reference external" href="#module-kinterbasdb.typeconv_text_unicode">Consequences of the Dynamic Type Translation in KInterbasDB</a></li>
<li><a class="reference external" href="#writing-custom-translators">Writing Custom Translators</a><ul>
<li><a class="reference external" href="#signature-specifications-for-translators">Signature Specifications for Translators</a></li>
</ul>
</li>
<li><a class="reference external" href="#example-programs">Example Programs</a></li>
<li><a class="reference external" href="#module-kinterbasdb.typeconv_24plus">Deferred Loading of Dynamic Type Translators</a></li>
<li><a class="reference external" href="#deferred-loading-backward-compatibility-issues">Deferred Loading: Backward Compatibility Issues</a></li>
<li><a class="reference external" href="#deferred-loading-example">Deferred Loading Example</a></li>
<li><a class="reference external" href="#positional-dymanic-type-translation">Positional Dymanic Type Translation</a></li>
<li><a class="reference external" href="#database-arrays">Database Arrays</a></li>
<li><a class="reference external" href="#blobs">Blobs</a></li>
</ul>
</li>
<li><a class="reference external" href="#connection-timeouts">Connection Timeouts</a><ul>
<li><a class="reference external" href="#user-supplied-connection-timeout-callbacks">User-Supplied Connection Timeout Callbacks</a></li>
<li><a class="reference external" href="#the-before-timeout-callback">The &#8220;Before Timeout&#8221; Callback</a></li>
<li><a class="reference external" href="#the-after-timeout-callback">The &#8220;After Timeout&#8221; Callback</a></li>
<li><a class="reference external" href="#user-supplied-connection-timeout-callback-caveats">User-Supplied Connection Timeout Callback Caveats</a></li>
<li><a class="reference external" href="#examples">Examples</a></li>
</ul>
</li>
<li><a class="reference external" href="#database-event-notification">Database Event Notification</a><ul>
<li><a class="reference external" href="#what-are-database-events">What are database events?</a></li>
<li><a class="reference external" href="#why-use-database-events">Why use database events?</a></li>
<li><a class="reference external" href="#how-events-are-exposed-to-the-server-and-the-client-process">How events are exposed to the server and the client process?</a></li>
<li><a class="reference external" href="#how-events-are-exposed-to-the-python-programmer">How events are exposed to the Python programmer?</a></li>
<li><a class="reference external" href="#example-program">Example Program</a></li>
<li><a class="reference external" href="#pitfalls-and-limitations">Pitfalls and Limitations</a></li>
</ul>
</li>
<li><a class="reference external" href="#the-database-info-api">The <cite>database_info</cite> API</a></li>
<li><a class="reference external" href="#module-kinterbasdb.services">Using Firebird Services API</a><ul>
<li><a class="reference external" href="#establishing-services-api-connections">Establishing Services API Connections</a></li>
<li><a class="reference external" href="#server-configuration-and-activity-levels">Server Configuration and Activity Levels</a></li>
<li><a class="reference external" href="#database-statistics">Database Statistics</a></li>
<li><a class="reference external" href="#backup-and-restoration">Backup and Restoration</a></li>
<li><a class="reference external" href="#database-operating-modes-sweeps-and-repair">Database Operating Modes, Sweeps, and Repair</a></li>
<li><a class="reference external" href="#user-maintenance">User Maintenance</a></li>
</ul>
</li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="python-db-api-compliance.html" title="previous chapter">Compliance to Python Database API 2.0</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="concurrency.html" title="next chapter">Concurrency</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/beyond-python-db-api.txt">Show Source</a></li>
            </ul>
          <h3>Quick search</h3>
            <form class="search" action="search.html" method="get">
              <input type="text" name="q" size="18" /> <input type="submit" value="Go" />
              <input type="hidden" name="check_keywords" value="yes" />
              <input type="hidden" name="area" value="default" />
            </form>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="concurrency.html" title="Concurrency"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="python-db-api-compliance.html" title="Compliance to Python Database API 2.0"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">KInterbasDB v3.3.0 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; Copyright 2009, David Rushby, Pavel Cisar.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.5.1.
    </div>
  </body>
</html>