]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/database.py
4 A lightweight wrapper around psycopg2.
6 Originally part of the Tornado framework. The tornado.database module
7 is slated for removal in Tornado 3.0, and it is now available separately
14 class Connection(object):
16 A lightweight wrapper around MySQLdb DB-API connections.
18 The main value we provide is wrapping rows in a dict/object so that
19 columns can be accessed by name. Typical usage::
21 db = torndb.Connection("localhost", "mydatabase")
22 for article in db.query("SELECT * FROM articles"):
25 Cursors are hidden by the implementation, but other than that, the methods
26 are very similar to the DB-API.
28 We explicitly set the timezone to UTC and the character encoding to
29 UTF-8 on all connections to avoid time zone and encoding errors.
31 def __init__(self
, host
, database
, user
=None, password
=None):
33 self
.database
= database
38 "database" : database
,
40 "password" : password
,
46 logging
.error("Cannot connect to database on %s", self
.host
, exc_info
=True)
53 Closes this database connection.
55 if getattr(self
, "_db", None) is not None:
61 Closes the existing database connection and re-opens it.
65 self
._db
= psycopg2
.connect(**self
._db
_args
)
66 self
._db
.autocommit
= True
68 # Initialize the timezone setting.
69 self
.execute("SET TIMEZONE TO 'UTC'")
71 def query(self
, query
, *parameters
, **kwparameters
):
73 Returns a row list for the given query and parameters.
75 cursor
= self
._cursor
()
77 self
._execute
(cursor
, query
, parameters
, kwparameters
)
78 column_names
= [d
[0] for d
in cursor
.description
]
79 return [Row(zip(column_names
, row
)) for row
in cursor
]
83 def get(self
, query
, *parameters
, **kwparameters
):
85 Returns the first row returned for the given query.
87 rows
= self
.query(query
, *parameters
, **kwparameters
)
91 raise Exception("Multiple rows returned for Database.get() query")
95 def execute(self
, query
, *parameters
, **kwparameters
):
97 Executes the given query, returning the lastrowid from the query.
99 return self
.execute_lastrowid(query
, *parameters
, **kwparameters
)
101 def execute_lastrowid(self
, query
, *parameters
, **kwparameters
):
103 Executes the given query, returning the lastrowid from the query.
105 cursor
= self
._cursor
()
107 self
._execute
(cursor
, query
, parameters
, kwparameters
)
108 return cursor
.lastrowid
112 def execute_rowcount(self
, query
, *parameters
, **kwparameters
):
114 Executes the given query, returning the rowcount from the query.
116 cursor
= self
._cursor
()
118 self
._execute
(cursor
, query
, parameters
, kwparameters
)
119 return cursor
.rowcount
123 def executemany(self
, query
, parameters
):
125 Executes the given query against all the given param sequences.
127 We return the lastrowid from the query.
129 return self
.executemany_lastrowid(query
, parameters
)
131 def executemany_lastrowid(self
, query
, parameters
):
133 Executes the given query against all the given param sequences.
135 We return the lastrowid from the query.
137 cursor
= self
._cursor
()
139 cursor
.executemany(query
, parameters
)
140 return cursor
.lastrowid
144 def executemany_rowcount(self
, query
, parameters
):
146 Executes the given query against all the given param sequences.
148 We return the rowcount from the query.
150 cursor
= self
._cursor
()
153 cursor
.executemany(query
, parameters
)
154 return cursor
.rowcount
158 def _ensure_connected(self
):
160 logging
.warning("Database connection was lost...")
165 self
._ensure
_connected
()
166 return self
._db
.cursor()
168 def _execute(self
, cursor
, query
, parameters
, kwparameters
):
169 logging
.debug("SQL Query: %s" % (query
% (kwparameters
or parameters
)))
172 return cursor
.execute(query
, kwparameters
or parameters
)
173 except (OperationalError
, psycopg2
.ProgrammingError
):
174 logging
.error("Error connecting to database on %s", self
.host
)
178 def transaction(self
):
179 return Transaction(self
)
183 """A dict that allows for object-like property access syntax."""
184 def __getattr__(self
, name
):
188 raise AttributeError(name
)
191 class Transaction(object):
192 def __init__(self
, db
):
195 self
.db
.execute("START TRANSACTION")
200 def __exit__(self
, exctype
, excvalue
, traceback
):
201 if exctype
is not None:
202 self
.db
.execute("ROLLBACK")
204 self
.db
.execute("COMMIT")
207 # Alias some common exceptions
208 IntegrityError
= psycopg2
.IntegrityError
209 OperationalError
= psycopg2
.OperationalError