/usr/share/doc/python-psycopg2-docs/html/advanced.html is in python-psycopg2-doc 2.4.5-1build5.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | <!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>More advanced topics — Psycopg 2.4.5 documentation</title>
<link rel="stylesheet" href="_static/psycopg.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '2.4.5',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="Psycopg 2.4.5 documentation" href="index.html" />
<link rel="next" title="psycopg2.extensions – Extensions to the DB API" href="extensions.html" />
<link rel="prev" title="The cursor class" href="cursor.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="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="extensions.html" title="psycopg2.extensions – Extensions to the DB API"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="cursor.html" title="The cursor class"
accesskey="P">previous</a> |</li>
<li><a href="index.html">Psycopg 2.4.5 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="more-advanced-topics">
<h1>More advanced topics<a class="headerlink" href="#more-advanced-topics" title="Permalink to this headline">¶</a></h1>
<div class="section" id="connection-and-cursor-factories">
<span id="subclassing-cursor"></span><span id="subclassing-connection"></span><span id="index-0"></span><h2>Connection and cursor factories<a class="headerlink" href="#connection-and-cursor-factories" title="Permalink to this headline">¶</a></h2>
<p>Psycopg exposes two new-style classes that can be sub-classed and expanded to
adapt them to the needs of the programmer: <a class="reference internal" href="extensions.html#psycopg2.extensions.cursor" title="psycopg2.extensions.cursor"><tt class="xref py py-obj docutils literal"><span class="pre">psycopg2.extensions.cursor</span></tt></a>
and <a class="reference internal" href="extensions.html#psycopg2.extensions.connection" title="psycopg2.extensions.connection"><tt class="xref py py-obj docutils literal"><span class="pre">psycopg2.extensions.connection</span></tt></a>. The <a class="reference internal" href="connection.html#connection" title="connection"><tt class="xref py py-obj docutils literal"><span class="pre">connection</span></tt></a> class is
usually sub-classed only to provide an easy way to create customized cursors
but other uses are possible. <a class="reference internal" href="cursor.html#cursor" title="cursor"><tt class="xref py py-obj docutils literal"><span class="pre">cursor</span></tt></a> is much more interesting, because
it is the class where query building, execution and result type-casting into
Python variables happens.</p>
<p id="index-1">An example of cursor subclass performing logging is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">psycopg2</span>
<span class="kn">import</span> <span class="nn">psycopg2.extensions</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="k">class</span> <span class="nc">LoggingCursor</span><span class="p">(</span><span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">cursor</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">execute</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sql</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">'sql_debug'</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">mogrify</span><span class="p">(</span><span class="n">sql</span><span class="p">,</span> <span class="n">args</span><span class="p">))</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sql</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">exc</span><span class="p">:</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">"</span><span class="si">%s</span><span class="s">: </span><span class="si">%s</span><span class="s">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">exc</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">,</span> <span class="n">exc</span><span class="p">))</span>
<span class="k">raise</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">DSN</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">(</span><span class="n">cursor_factory</span><span class="o">=</span><span class="n">LoggingCursor</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">"INSERT INTO mytable VALUES (</span><span class="si">%s</span><span class="s">, </span><span class="si">%s</span><span class="s">, </span><span class="si">%s</span><span class="s">);"</span><span class="p">,</span>
<span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="adapting-new-python-types-to-sql-syntax">
<span id="adapting-new-types"></span><span id="index-2"></span><h2>Adapting new Python types to SQL syntax<a class="headerlink" href="#adapting-new-python-types-to-sql-syntax" title="Permalink to this headline">¶</a></h2>
<p>Any Python class or type can be adapted to an SQL string. Adaptation mechanism
is similar to the Object Adaptation proposed in the <span class="target" id="index-3"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0246"><strong>PEP 246</strong></a> and is exposed
by the <a class="reference internal" href="extensions.html#psycopg2.extensions.adapt" title="psycopg2.extensions.adapt"><tt class="xref py py-obj docutils literal"><span class="pre">psycopg2.extensions.adapt()</span></tt></a> function.</p>
<p>The <a class="reference internal" href="cursor.html#cursor.execute" title="cursor.execute"><tt class="xref py py-obj docutils literal"><span class="pre">execute()</span></tt></a> method adapts its arguments to the
<a class="reference internal" href="extensions.html#psycopg2.extensions.ISQLQuote" title="psycopg2.extensions.ISQLQuote"><tt class="xref py py-obj docutils literal"><span class="pre">ISQLQuote</span></tt></a> protocol. Objects that conform to this
protocol expose a <tt class="xref py py-obj docutils literal"><span class="pre">getquoted()</span></tt> method returning the SQL representation
of the object as a string (the method must return <tt class="xref py py-obj docutils literal"><span class="pre">bytes</span></tt> in Python 3).
Optionally the conform object may expose a
<a class="reference internal" href="extensions.html#psycopg2.extensions.ISQLQuote.prepare" title="psycopg2.extensions.ISQLQuote.prepare"><tt class="xref py py-obj docutils literal"><span class="pre">prepare()</span></tt></a> method.</p>
<p>There are two basic ways to have a Python object adapted to SQL:</p>
<ul class="simple">
<li>the object itself is conform, or knows how to make itself conform. Such
object must expose a <tt class="xref py py-obj docutils literal"><span class="pre">__conform__()</span></tt> method that will be called with the
protocol object as argument. The object can check that the protocol is
<tt class="xref py py-obj docutils literal"><span class="pre">ISQLQuote</span></tt>, in which case it can return <tt class="xref py py-obj docutils literal"><span class="pre">self</span></tt> (if the object also
implements <tt class="xref py py-obj docutils literal"><span class="pre">getquoted()</span></tt>) or a suitable wrapper object. This option is
viable if you are the author of the object and if the object is specifically
designed for the database (i.e. having Psycopg as a dependency and polluting
its interface with the required methods doesn’t bother you). For a simple
example you can take a look at the source code for the
<a class="reference internal" href="extras.html#psycopg2.extras.Inet" title="psycopg2.extras.Inet"><tt class="xref py py-obj docutils literal"><span class="pre">psycopg2.extras.Inet</span></tt></a> object.</li>
<li>If implementing the <tt class="xref py py-obj docutils literal"><span class="pre">ISQLQuote</span></tt> interface directly in the object is not an
option (maybe because the object to adapt comes from a third party library),
you can use an <em>adaptation function</em>, taking the object to be adapted as
argument and returning a conforming object. The adapter must be
registered via the <a class="reference internal" href="extensions.html#psycopg2.extensions.register_adapter" title="psycopg2.extensions.register_adapter"><tt class="xref py py-obj docutils literal"><span class="pre">register_adapter()</span></tt></a> function. A
simple example wrapper is <tt class="xref py py-obj docutils literal"><span class="pre">psycopg2.extras.UUID_adapter</span></tt> used by the
<a class="reference internal" href="extras.html#psycopg2.extras.register_uuid" title="psycopg2.extras.register_uuid"><tt class="xref py py-obj docutils literal"><span class="pre">register_uuid()</span></tt></a> function.</li>
</ul>
<p>A convenient object to write adapters is the <a class="reference internal" href="extensions.html#psycopg2.extensions.AsIs" title="psycopg2.extensions.AsIs"><tt class="xref py py-obj docutils literal"><span class="pre">AsIs</span></tt></a>
wrapper, whose <tt class="xref py py-obj docutils literal"><span class="pre">getquoted()</span></tt> result is simply the <tt class="xref py py-obj docutils literal"><span class="pre">str()</span></tt>ing conversion of
the wrapped object.</p>
<p id="index-4">Example: mapping of a <tt class="xref py py-obj docutils literal"><span class="pre">Point</span></tt> class into the <a class="reference external" href="http://www.postgresql.org/docs/current/static/datatype-geometric.html#DATATYPE-GEOMETRIC"><tt class="sql docutils literal"><span class="pre">point</span></tt></a> PostgreSQL
geometric type:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">psycopg2.extensions</span> <span class="kn">import</span> <span class="n">adapt</span><span class="p">,</span> <span class="n">register_adapter</span><span class="p">,</span> <span class="n">AsIs</span>
<span class="gp">>>> </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </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">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="n">x</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">y</span>
<span class="gp">>>> </span><span class="k">def</span> <span class="nf">adapt_point</span><span class="p">(</span><span class="n">point</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">return</span> <span class="n">AsIs</span><span class="p">(</span><span class="s">"'(</span><span class="si">%s</span><span class="s">, </span><span class="si">%s</span><span class="s">)'"</span> <span class="o">%</span> <span class="p">(</span><span class="n">adapt</span><span class="p">(</span><span class="n">point</span><span class="o">.</span><span class="n">x</span><span class="p">),</span> <span class="n">adapt</span><span class="p">(</span><span class="n">point</span><span class="o">.</span><span class="n">y</span><span class="p">)))</span>
<span class="gp">>>> </span><span class="n">register_adapter</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">adapt_point</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"INSERT INTO atable (apoint) VALUES (</span><span class="si">%s</span><span class="s">)"</span><span class="p">,</span>
<span class="gp">... </span> <span class="p">(</span><span class="n">Point</span><span class="p">(</span><span class="mf">1.23</span><span class="p">,</span> <span class="mf">4.56</span><span class="p">),))</span>
</pre></div>
</div>
<p>The above function call results in the SQL command:</p>
<div class="highlight-python"><div class="highlight"><pre>INSERT INTO atable (apoint) VALUES ('(1.23, 4.56)');
</pre></div>
</div>
</div>
<div class="section" id="type-casting-of-sql-types-into-python-objects">
<span id="type-casting-from-sql-to-python"></span><span id="index-5"></span><h2>Type casting of SQL types into Python objects<a class="headerlink" href="#type-casting-of-sql-types-into-python-objects" title="Permalink to this headline">¶</a></h2>
<p>PostgreSQL objects read from the database can be adapted to Python objects
through an user-defined adapting function. An adapter function takes two
arguments: the object string representation as returned by PostgreSQL and the
cursor currently being read, and should return a new Python object. For
example, the following function parses the PostgreSQL <tt class="sql docutils literal"><span class="pre">point</span></tt>
representation into the previously defined <tt class="xref py py-obj docutils literal"><span class="pre">Point</span></tt> class:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">def</span> <span class="nf">cast_point</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">cur</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">if</span> <span class="n">value</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="bp">None</span>
<span class="gp">...</span>
<span class="gp">... </span> <span class="c"># Convert from (f1, f2) syntax using a regular expression.</span>
<span class="gp">... </span> <span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s">r"\(([^)]+),([^)]+)\)"</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">if</span> <span class="n">m</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="n">Point</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)),</span> <span class="nb">float</span><span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)))</span>
<span class="gp">... </span> <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="n">InterfaceError</span><span class="p">(</span><span class="s">"bad point representation: </span><span class="si">%r</span><span class="s">"</span> <span class="o">%</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>In order to create a mapping from a PostgreSQL type (either standard or
user-defined), its OID must be known. It can be retrieved either by the second
column of the <a class="reference internal" href="cursor.html#cursor.description" title="cursor.description"><tt class="xref py py-obj docutils literal"><span class="pre">cursor.description</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"SELECT NULL::point"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">point_oid</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">description</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">point_oid</span>
<span class="go">600</span>
</pre></div>
</div>
<p>or by querying the system catalog for the type name and namespace (the
namespace for system objects is <tt class="sql docutils literal"><span class="pre">pg_catalog</span></tt>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"""</span>
<span class="gp">... </span><span class="s"> SELECT pg_type.oid</span>
<span class="gp">... </span><span class="s"> FROM pg_type JOIN pg_namespace</span>
<span class="gp">... </span><span class="s"> ON typnamespace = pg_namespace.oid</span>
<span class="gp">... </span><span class="s"> WHERE typname = </span><span class="si">%(typename)s</span><span class="s"></span>
<span class="gp">... </span><span class="s"> AND nspname = </span><span class="si">%(namespace)s</span><span class="s">"""</span><span class="p">,</span>
<span class="gp">... </span> <span class="p">{</span><span class="s">'typename'</span><span class="p">:</span> <span class="s">'point'</span><span class="p">,</span> <span class="s">'namespace'</span><span class="p">:</span> <span class="s">'pg_catalog'</span><span class="p">})</span>
<span class="gp">>>> </span><span class="n">point_oid</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="mi">0</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">point_oid</span>
<span class="go">600</span>
</pre></div>
</div>
<p>After you know the object OID, you can create and register the new type:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">POINT</span> <span class="o">=</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">new_type</span><span class="p">((</span><span class="n">point_oid</span><span class="p">,),</span> <span class="s">"POINT"</span><span class="p">,</span> <span class="n">cast_point</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">register_type</span><span class="p">(</span><span class="n">POINT</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="extensions.html#psycopg2.extensions.new_type" title="psycopg2.extensions.new_type"><tt class="xref py py-obj docutils literal"><span class="pre">new_type()</span></tt></a> function binds the object OIDs
(more than one can be specified) to the adapter function.
<a class="reference internal" href="extensions.html#psycopg2.extensions.register_type" title="psycopg2.extensions.register_type"><tt class="xref py py-obj docutils literal"><span class="pre">register_type()</span></tt></a> completes the spell. Conversion
is automatically performed when a column whose type is a registered OID is
read:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"SELECT '(10.2,20.3)'::point"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">point</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="mi">0</span><span class="p">]</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="nb">type</span><span class="p">(</span><span class="n">point</span><span class="p">),</span> <span class="n">point</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">point</span><span class="o">.</span><span class="n">y</span>
<span class="go"><class 'Point'> 10.2 20.3</span>
</pre></div>
</div>
<p>A typecaster created by <tt class="xref py py-obj docutils literal"><span class="pre">new_type()</span></tt> can be also used with
<a class="reference internal" href="extensions.html#psycopg2.extensions.new_array_type" title="psycopg2.extensions.new_array_type"><tt class="xref py py-obj docutils literal"><span class="pre">new_array_type()</span></tt></a> to create a typecaster converting a
PostgreSQL array into a Python list.</p>
</div>
<div class="section" id="asynchronous-notifications">
<span id="async-notify"></span><span id="index-6"></span><h2>Asynchronous notifications<a class="headerlink" href="#asynchronous-notifications" title="Permalink to this headline">¶</a></h2>
<p>Psycopg allows asynchronous interaction with other database sessions using the
facilities offered by PostgreSQL commands <a class="reference external" href="http://www.postgresql.org/docs/current/static/sql-listen.html"><tt class="sql docutils literal"><span class="pre">LISTEN</span></tt></a> and <a class="reference external" href="http://www.postgresql.org/docs/current/static/sql-notify.html"><tt class="sql docutils literal"><span class="pre">NOTIFY</span></tt></a>. Please
refer to the PostgreSQL documentation for examples about how to use this form of
communication.</p>
<p>Notifications are instances of the <a class="reference internal" href="extensions.html#psycopg2.extensions.Notify" title="psycopg2.extensions.Notify"><tt class="xref py py-obj docutils literal"><span class="pre">Notify</span></tt></a> object made
available upon reception in the <a class="reference internal" href="connection.html#connection.notifies" title="connection.notifies"><tt class="xref py py-obj docutils literal"><span class="pre">connection.notifies</span></tt></a> list. Notifications can
be sent from Python code simply executing a <tt class="sql docutils literal"><span class="pre">NOTIFY</span></tt> command in an
<a class="reference internal" href="cursor.html#cursor.execute" title="cursor.execute"><tt class="xref py py-obj docutils literal"><span class="pre">execute()</span></tt></a> call.</p>
<p>Because of the way sessions interact with notifications (see <a class="reference external" href="http://www.postgresql.org/docs/current/static/sql-notify.html"><tt class="sql docutils literal"><span class="pre">NOTIFY</span></tt></a>
documentation), you should keep the connection in <a class="reference internal" href="connection.html#connection.autocommit" title="connection.autocommit"><tt class="xref py py-obj docutils literal"><span class="pre">autocommit</span></tt></a>
mode if you wish to receive or send notifications in a timely manner.</p>
<p>Notifications are received after every query execution. If the user is
interested in receiving notifications but not in performing any query, the
<a class="reference internal" href="connection.html#connection.poll" title="connection.poll"><tt class="xref py py-obj docutils literal"><span class="pre">poll()</span></tt></a> method can be used to check for new messages without
wasting resources.</p>
<p>A simple application could poll the connection from time to time to check if
something new has arrived. A better strategy is to use some I/O completion
function such as <a class="reference external" href="/usr/share/doc/python2.7-doc/html/library/select.html#select.select" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> to sleep until awaken from the kernel when there is
some data to read on the connection, thereby using no CPU unless there is
something to read:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">select</span>
<span class="kn">import</span> <span class="nn">psycopg2</span>
<span class="kn">import</span> <span class="nn">psycopg2.extensions</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">DSN</span><span class="p">)</span>
<span class="n">conn</span><span class="o">.</span><span class="n">set_isolation_level</span><span class="p">(</span><span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">ISOLATION_LEVEL_AUTOCOMMIT</span><span class="p">)</span>
<span class="n">curs</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">curs</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"LISTEN test;"</span><span class="p">)</span>
<span class="k">print</span> <span class="s">"Waiting for notifications on channel 'test'"</span>
<span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
<span class="k">if</span> <span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([</span><span class="n">conn</span><span class="p">],[],[],</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="p">([],[],[]):</span>
<span class="k">print</span> <span class="s">"Timeout"</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">conn</span><span class="o">.</span><span class="n">poll</span><span class="p">()</span>
<span class="k">while</span> <span class="n">conn</span><span class="o">.</span><span class="n">notifies</span><span class="p">:</span>
<span class="n">notify</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">notifies</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="k">print</span> <span class="s">"Got NOTIFY:"</span><span class="p">,</span> <span class="n">notify</span><span class="o">.</span><span class="n">pid</span><span class="p">,</span> <span class="n">notify</span><span class="o">.</span><span class="n">channel</span><span class="p">,</span> <span class="n">notify</span><span class="o">.</span><span class="n">payload</span>
</pre></div>
</div>
<p>Running the script and executing a command such as <tt class="sql docutils literal"><span class="pre">NOTIFY</span> <span class="pre">test,</span> <span class="pre">'hello'</span></tt>
in a separate <strong class="program">psql</strong> shell, the output may look similar to:</p>
<div class="highlight-python"><div class="highlight"><pre>Waiting for notifications on channel 'test'
Timeout
Timeout
Got NOTIFY: 6535 test hello
Timeout
...
</pre></div>
</div>
<p>Note that the payload is only available from PostgreSQL 9.0: notifications
received from a previous version server will have the
<a class="reference internal" href="extensions.html#psycopg2.extensions.Notify.payload" title="psycopg2.extensions.Notify.payload"><tt class="xref py py-obj docutils literal"><span class="pre">payload</span></tt></a> attribute set to the empty string.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Added <a class="reference internal" href="extensions.html#psycopg2.extensions.Notify" title="psycopg2.extensions.Notify"><tt class="xref py py-obj docutils literal"><span class="pre">Notify</span></tt></a> object and handling notification
payload.</p>
</div>
</div>
<div class="section" id="asynchronous-support">
<span id="async-support"></span><span id="index-7"></span><h2>Asynchronous support<a class="headerlink" href="#asynchronous-support" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.0.</span></p>
</div>
<p>Psycopg can issue asynchronous queries to a PostgreSQL database. An asynchronous
communication style is established passing the parameter <em>async</em>=1 to the
<a class="reference internal" href="module.html#psycopg2.connect" title="psycopg2.connect"><tt class="xref py py-obj docutils literal"><span class="pre">connect()</span></tt></a> function: the returned connection will work in
<em>asynchronous mode</em>.</p>
<p>In asynchronous mode, a Psycopg connection will rely on the caller to poll the
socket file descriptor, checking if it is ready to accept data or if a query
result has been transferred and is ready to be read on the client. The caller
can use the method <a class="reference internal" href="connection.html#connection.fileno" title="connection.fileno"><tt class="xref py py-obj docutils literal"><span class="pre">fileno()</span></tt></a> to get the connection file
descriptor and <a class="reference internal" href="connection.html#connection.poll" title="connection.poll"><tt class="xref py py-obj docutils literal"><span class="pre">poll()</span></tt></a> to make communication proceed according to
the current connection state.</p>
<p>The following is an example loop using methods <tt class="xref py py-obj docutils literal"><span class="pre">fileno()</span></tt> and <tt class="xref py py-obj docutils literal"><span class="pre">poll()</span></tt>
together with the Python <a class="reference external" href="/usr/share/doc/python2.7-doc/html/library/select.html#select.select" title="(in Python v2.7)"><tt class="xref py py-func docutils literal"><span class="pre">select()</span></tt></a> function in order to carry on
asynchronous operations with Psycopg:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">wait</span><span class="p">(</span><span class="n">conn</span><span class="p">):</span>
<span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
<span class="n">state</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">poll</span><span class="p">()</span>
<span class="k">if</span> <span class="n">state</span> <span class="o">==</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">POLL_OK</span><span class="p">:</span>
<span class="k">break</span>
<span class="k">elif</span> <span class="n">state</span> <span class="o">==</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">POLL_WRITE</span><span class="p">:</span>
<span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([],</span> <span class="p">[</span><span class="n">conn</span><span class="o">.</span><span class="n">fileno</span><span class="p">()],</span> <span class="p">[])</span>
<span class="k">elif</span> <span class="n">state</span> <span class="o">==</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">POLL_READ</span><span class="p">:</span>
<span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([</span><span class="n">conn</span><span class="o">.</span><span class="n">fileno</span><span class="p">()],</span> <span class="p">[],</span> <span class="p">[])</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">OperationalError</span><span class="p">(</span><span class="s">"poll() returned </span><span class="si">%s</span><span class="s">"</span> <span class="o">%</span> <span class="n">state</span><span class="p">)</span>
</pre></div>
</div>
<p>The above loop of course would block an entire application: in a real
asynchronous framework, <tt class="xref py py-obj docutils literal"><span class="pre">select()</span></tt> would be called on many file descriptors
waiting for any of them to be ready. Nonetheless the function can be used to
connect to a PostgreSQL server only using nonblocking commands and the
connection obtained can be used to perform further nonblocking queries. After
<tt class="xref py py-obj docutils literal"><span class="pre">poll()</span></tt> has returned <a class="reference internal" href="extensions.html#psycopg2.extensions.POLL_OK" title="psycopg2.extensions.POLL_OK"><tt class="xref py py-obj docutils literal"><span class="pre">POLL_OK</span></tt></a>, and thus <tt class="xref py py-obj docutils literal"><span class="pre">wait()</span></tt> has
returned, the connection can be safely used:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">aconn</span> <span class="o">=</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">database</span><span class="o">=</span><span class="s">'test'</span><span class="p">,</span> <span class="n">async</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">wait</span><span class="p">(</span><span class="n">aconn</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">acurs</span> <span class="o">=</span> <span class="n">aconn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that there are a few other requirements to be met in order to have a
completely non-blocking connection attempt: see the libpq documentation for
<a class="reference external" href="http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PQCONNECTSTARTPARAMS"><tt class="xref py py-obj docutils literal"><span class="pre">PQconnectStart()</span></tt></a>.</p>
<p>The same loop should be also used to perform nonblocking queries: after
sending a query via <a class="reference internal" href="cursor.html#cursor.execute" title="cursor.execute"><tt class="xref py py-obj docutils literal"><span class="pre">execute()</span></tt></a> or <a class="reference internal" href="cursor.html#cursor.callproc" title="cursor.callproc"><tt class="xref py py-obj docutils literal"><span class="pre">callproc()</span></tt></a>, call
<tt class="xref py py-obj docutils literal"><span class="pre">poll()</span></tt> on the connection available from <a class="reference internal" href="cursor.html#cursor.connection" title="cursor.connection"><tt class="xref py py-obj docutils literal"><span class="pre">cursor.connection</span></tt></a> until it
returns <tt class="xref py py-obj docutils literal"><span class="pre">POLL_OK</span></tt>, at which point the query has been completely sent to the
server and, if it produced data, the results have been transferred to the
client and available using the regular cursor methods:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">acurs</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">"SELECT pg_sleep(5); SELECT 42;"</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">wait</span><span class="p">(</span><span class="n">acurs</span><span class="o">.</span><span class="n">connection</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">acurs</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">42</span>
</pre></div>
</div>
<p>When an asynchronous query is being executed, <a class="reference internal" href="connection.html#connection.isexecuting" title="connection.isexecuting"><tt class="xref py py-obj docutils literal"><span class="pre">connection.isexecuting()</span></tt></a> returns
<tt class="xref py py-obj docutils literal"><span class="pre">True</span></tt>. Two cursors can’t execute concurrent queries on the same asynchronous
connection.</p>
<p>There are several limitations in using asynchronous connections: the
connection is always in <a class="reference internal" href="connection.html#connection.autocommit" title="connection.autocommit"><tt class="xref py py-obj docutils literal"><span class="pre">autocommit</span></tt></a> mode and it is not
possible to change it. So a
transaction is not implicitly started at the first query and is not possible
to use methods <a class="reference internal" href="connection.html#connection.commit" title="connection.commit"><tt class="xref py py-obj docutils literal"><span class="pre">commit()</span></tt></a> and <a class="reference internal" href="connection.html#connection.rollback" title="connection.rollback"><tt class="xref py py-obj docutils literal"><span class="pre">rollback()</span></tt></a>: you can
manually control transactions using <a class="reference internal" href="cursor.html#cursor.execute" title="cursor.execute"><tt class="xref py py-obj docutils literal"><span class="pre">execute()</span></tt></a> to send database
commands such as <tt class="sql docutils literal"><span class="pre">BEGIN</span></tt>, <tt class="sql docutils literal"><span class="pre">COMMIT</span></tt> and <tt class="sql docutils literal"><span class="pre">ROLLBACK</span></tt>. Similarly
<a class="reference internal" href="connection.html#connection.set_session" title="connection.set_session"><tt class="xref py py-obj docutils literal"><span class="pre">set_session()</span></tt></a> can’t be used but it is still possible to invoke the
<tt class="sql docutils literal"><span class="pre">SET</span></tt> command with the proper <tt class="sql docutils literal"><span class="pre">default_transaction_...</span></tt> parameter.</p>
<p>With asynchronous connections it is also not possible to use
<a class="reference internal" href="connection.html#connection.set_client_encoding" title="connection.set_client_encoding"><tt class="xref py py-obj docutils literal"><span class="pre">set_client_encoding()</span></tt></a>, <a class="reference internal" href="cursor.html#cursor.executemany" title="cursor.executemany"><tt class="xref py py-obj docutils literal"><span class="pre">executemany()</span></tt></a>, <a class="reference internal" href="usage.html#large-objects"><em>large
objects</em></a>, <a class="reference internal" href="usage.html#server-side-cursors"><em>named cursors</em></a>.</p>
<p><a class="reference internal" href="usage.html#copy"><em>COPY commands</em></a> are not supported either in asynchronous mode, but
this will be probably implemented in a future release.</p>
</div>
<div class="section" id="support-to-coroutine-libraries">
<span id="green-support"></span><span id="index-8"></span><h2>Support to coroutine libraries<a class="headerlink" href="#support-to-coroutine-libraries" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.0.</span></p>
</div>
<p>Psycopg can be used together with <a class="reference external" href="http://en.wikipedia.org/wiki/Coroutine">coroutine</a>-based libraries, and participate
to cooperative multithreading.</p>
<p>Coroutine-based libraries (such as <a class="reference external" href="http://eventlet.net/">Eventlet</a> or <a class="reference external" href="http://www.gevent.org/">gevent</a>) can usually patch the
Python standard library in order to enable a coroutine switch in the presence of
blocking I/O: the process is usually referred as making the system <em>green</em>, in
reference to the <a class="reference external" href="http://en.wikipedia.org/wiki/Green_threads">green threads</a>.</p>
<p>Because Psycopg is a C extension module, it is not possible for coroutine
libraries to patch it: Psycopg instead enables cooperative multithreading by
allowing the registration of a <em>wait callback</em> using the
<a class="reference internal" href="extensions.html#psycopg2.extensions.set_wait_callback" title="psycopg2.extensions.set_wait_callback"><tt class="xref py py-obj docutils literal"><span class="pre">psycopg2.extensions.set_wait_callback()</span></tt></a> function. When a wait callback is
registered, Psycopg will use <a class="reference external" href="http://www.postgresql.org/docs/current/static/libpq-async.html">libpq non-blocking calls</a> instead of the regular
blocking ones, and will delegate to the callback the responsibility to wait
for the socket to become readable or writable.</p>
<p>Working this way, the caller does not have the complete freedom to schedule the
socket check whenever they want as with an <a class="reference internal" href="#async-support"><em>asynchronous connection</em></a>, but has the advantage of maintaining a complete DB API 2.0
semantics: from the point of view of the end user, all Psycopg functions and
objects will work transparently in the coroutine environment (blocking the
calling green thread and giving other green threads the possibility to be
scheduled), allowing non modified code and third party libraries (such as
<a class="reference external" href="http://www.sqlalchemy.org/">SQLAlchemy</a>) to be used in coroutine-based programs.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Psycopg connections are not <em>green thread safe</em> and can’t be used
concurrently by different green threads. Trying to execute more than one
command at time using one cursor per thread will result in an error (or a
deadlock on versions before 2.4.2).</p>
<p class="last">Therefore, programmers are advised to either avoid sharing connections
between coroutines or to use a library-friendly lock to synchronize shared
connections, e.g. for pooling.</p>
</div>
<p>Coroutine libraries authors should provide a callback implementation (and
possibly a method to register it) to make Psycopg as green as they want. An
example callback (using <tt class="xref py py-obj docutils literal"><span class="pre">select()</span></tt> to block) is provided as
<a class="reference internal" href="extras.html#psycopg2.extras.wait_select" title="psycopg2.extras.wait_select"><tt class="xref py py-obj docutils literal"><span class="pre">psycopg2.extras.wait_select()</span></tt></a>: it boils down to something similar to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">wait_select</span><span class="p">(</span><span class="n">conn</span><span class="p">):</span>
<span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
<span class="n">state</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">poll</span><span class="p">()</span>
<span class="k">if</span> <span class="n">state</span> <span class="o">==</span> <span class="n">extensions</span><span class="o">.</span><span class="n">POLL_OK</span><span class="p">:</span>
<span class="k">break</span>
<span class="k">elif</span> <span class="n">state</span> <span class="o">==</span> <span class="n">extensions</span><span class="o">.</span><span class="n">POLL_READ</span><span class="p">:</span>
<span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([</span><span class="n">conn</span><span class="o">.</span><span class="n">fileno</span><span class="p">()],</span> <span class="p">[],</span> <span class="p">[])</span>
<span class="k">elif</span> <span class="n">state</span> <span class="o">==</span> <span class="n">extensions</span><span class="o">.</span><span class="n">POLL_WRITE</span><span class="p">:</span>
<span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([],</span> <span class="p">[</span><span class="n">conn</span><span class="o">.</span><span class="n">fileno</span><span class="p">()],</span> <span class="p">[])</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">OperationalError</span><span class="p">(</span><span class="s">"bad state from poll: </span><span class="si">%s</span><span class="s">"</span> <span class="o">%</span> <span class="n">state</span><span class="p">)</span>
</pre></div>
</div>
<p>Providing callback functions for the single coroutine libraries is out of
psycopg2 scope, as the callback can be tied to the libraries’ implementation
details. You can check the <a class="reference external" href="http://bitbucket.org/dvarrazzo/psycogreen/">psycogreen</a> project for further informations and
resources about the topic.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p><a class="reference internal" href="usage.html#copy"><em>COPY commands</em></a> are currently not supported when a wait callback
is registered, but they will be probably implemented in a future release.</p>
<p class="last"><a class="reference internal" href="usage.html#large-objects"><em>Large objects</em></a> are not supported either: they are
not compatible with asynchronous connections.</p>
</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 internal" href="#">More advanced topics</a><ul>
<li><a class="reference internal" href="#connection-and-cursor-factories">Connection and cursor factories</a></li>
<li><a class="reference internal" href="#adapting-new-python-types-to-sql-syntax">Adapting new Python types to SQL syntax</a></li>
<li><a class="reference internal" href="#type-casting-of-sql-types-into-python-objects">Type casting of SQL types into Python objects</a></li>
<li><a class="reference internal" href="#asynchronous-notifications">Asynchronous notifications</a></li>
<li><a class="reference internal" href="#asynchronous-support">Asynchronous support</a></li>
<li><a class="reference internal" href="#support-to-coroutine-libraries">Support to coroutine libraries</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="cursor.html"
title="previous chapter">The <tt class="docutils literal"><span class="pre">cursor</span></tt> class</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="extensions.html"
title="next chapter"><tt class="docutils literal"><span class="pre">psycopg2.extensions</span></tt> – Extensions to the DB API</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/advanced.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</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"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="extensions.html" title="psycopg2.extensions – Extensions to the DB API"
>next</a> |</li>
<li class="right" >
<a href="cursor.html" title="The cursor class"
>previous</a> |</li>
<li><a href="index.html">Psycopg 2.4.5 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2001-2011, Federico Di Gregorio. Documentation by Daniele Varrazzo.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.2.
</div>
</body>
</html>
|