2004-10-19 07:17:12 +04:00
|
|
|
# cursor.py - how to subclass the cursor type
|
|
|
|
#
|
2010-02-13 01:34:53 +03:00
|
|
|
# Copyright (C) 2004-2010 Federico Di Gregorio <fog@debian.org>
|
2004-10-19 07:17:12 +04:00
|
|
|
#
|
2010-02-13 01:34:53 +03:00
|
|
|
# psycopg2 is free software: you can redistribute it and/or modify it
|
|
|
|
# under the terms of the GNU Lesser General Public License as published
|
|
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
2004-10-19 07:17:12 +04:00
|
|
|
#
|
2010-02-13 01:34:53 +03:00
|
|
|
# psycopg2 is distributed in the hope that it will be useful, but WITHOUT
|
|
|
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
|
|
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
|
|
|
|
# License for more details.
|
2004-10-19 07:17:12 +04:00
|
|
|
|
|
|
|
## put in DSN your DSN string
|
|
|
|
|
|
|
|
DSN = 'dbname=test'
|
|
|
|
|
|
|
|
## don't modify anything below this line (except for experimenting)
|
|
|
|
|
|
|
|
import sys
|
2005-06-13 10:25:06 +04:00
|
|
|
import psycopg2
|
|
|
|
import psycopg2.extensions
|
2004-10-19 07:17:12 +04:00
|
|
|
|
|
|
|
if len(sys.argv) > 1:
|
|
|
|
DSN = sys.argv[1]
|
|
|
|
|
2017-11-28 11:30:15 +03:00
|
|
|
print("Opening connection using dsn:", DSN)
|
2005-06-13 10:25:06 +04:00
|
|
|
conn = psycopg2.connect(DSN)
|
2017-11-28 11:30:15 +03:00
|
|
|
print("Encoding for this connection is", conn.encoding)
|
2004-10-19 07:17:12 +04:00
|
|
|
|
|
|
|
|
2005-06-13 10:25:06 +04:00
|
|
|
class NoDataError(psycopg2.ProgrammingError):
|
2004-10-19 07:17:12 +04:00
|
|
|
"""Exception that will be raised by our cursor."""
|
|
|
|
pass
|
|
|
|
|
2005-06-13 10:25:06 +04:00
|
|
|
class Cursor(psycopg2.extensions.cursor):
|
2004-10-19 07:17:12 +04:00
|
|
|
"""A custom cursor."""
|
|
|
|
|
|
|
|
def fetchone(self):
|
|
|
|
"""Like fetchone but raise an exception if no data is available.
|
|
|
|
|
|
|
|
Note that to have .fetchmany() and .fetchall() to raise the same
|
|
|
|
exception we'll have to override them too; even if internally psycopg
|
|
|
|
uses the same function to fetch rows, the code path from Python is
|
|
|
|
different.
|
|
|
|
"""
|
2005-06-13 10:25:06 +04:00
|
|
|
d = psycopg2.extensions.cursor.fetchone(self)
|
2004-10-19 07:17:12 +04:00
|
|
|
if d is None:
|
|
|
|
raise NoDataError("no more data")
|
|
|
|
return d
|
|
|
|
|
2005-03-12 09:39:47 +03:00
|
|
|
curs = conn.cursor(cursor_factory=Cursor)
|
2004-10-19 07:17:12 +04:00
|
|
|
curs.execute("SELECT 1 AS foo")
|
2017-11-28 11:30:15 +03:00
|
|
|
print("Result of fetchone():", curs.fetchone())
|
2004-10-19 07:17:12 +04:00
|
|
|
|
|
|
|
# now let's raise the exception
|
|
|
|
try:
|
|
|
|
curs.fetchone()
|
2017-11-28 11:30:15 +03:00
|
|
|
except NoDataError as err:
|
|
|
|
print("Exception caught:", err)
|
2004-10-19 07:17:12 +04:00
|
|
|
|
|
|
|
conn.rollback()
|