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
|
#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# Copyright (c) Priit Jrv 2009, 2010, 2013
#
# This file is part of WhiteDB
#
# WhiteDB is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WhiteDB 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WhiteDB. If not, see <http://www.gnu.org/licenses/>.
"""@file whitedb.py
High level Python API for WhiteDB database
"""
# This module is implemented loosely following the guidelines
# in Python DBI spec (http://www.python.org/dev/peps/pep-0249/).
# Due to the wgdb feature set being much slimmer than typical
# SQL databases, it does not make sense to follow DBI fully,
# but where there are overlaps in functionality, similar
# naming and object structure should be generally used.
import wgdb
### Error classes (by DBI recommendation) ###
#
class DatabaseError(wgdb.error):
"""Base class for database errors"""
pass
class ProgrammingError(DatabaseError):
"""Exception class to indicate invalid database usage"""
pass
class DataError(DatabaseError):
"""Exception class to indicate invalid data passed to the db adapter"""
pass
class InternalError(DatabaseError):
"""Exception class to indicate invalid internal state of the module"""
pass
############## DBI classes: ###############
#
class Connection(object):
"""The Connection class acts as a container for
wgdb.Database and provides all connection-related
and record accessing functions."""
def __init__(self, shmname=None, shmsize=0, local=0):
if local:
self._db = wgdb.attach_database(size=shmsize, local=local)
elif shmname:
self._db = wgdb.attach_database(shmname, shmsize)
else:
self._db = wgdb.attach_database(size=shmsize)
self.shmname = shmname
self.locking = 1
self._lock_id = None
def close(self):
"""Close the connection."""
if self._db:
wgdb.detach_database(self._db)
self._db = None
def cursor(self):
"""Return a DBI-style database cursor"""
if self._db is None:
raise InternalError("Connection is closed.")
return Cursor(self)
# Locking support
#
def set_locking(self, mode):
"""Set locking mode (1=on, 0=off)"""
self.locking = mode
def start_write(self):
"""Start writing transaction"""
if self._lock_id:
raise ProgrammingError("Transaction already started.")
self._lock_id = wgdb.start_write(self._db)
def end_write(self):
"""Finish writing transaction"""
if not self._lock_id:
raise ProgrammingError("No current transaction.")
wgdb.end_write(self._db, self._lock_id)
self._lock_id = None
def start_read(self):
"""Start reading transaction"""
if self._lock_id:
raise ProgrammingError("Transaction already started.")
self._lock_id = wgdb.start_read(self._db)
def end_read(self):
"""Finish reading transaction"""
if not self._lock_id:
raise ProgrammingError("No current transaction.")
wgdb.end_read(self._db, self._lock_id)
self._lock_id = None
def commit(self):
"""Commit the transaction (no-op)"""
pass
def rollback(self):
"""Roll back the transaction (no-op)"""
pass
# Record operations. Wrap wgdb.Record object into Record class.
#
def _new_record(self, rec):
"""Create a Record instance from wgdb record object (internal)"""
r = Record(self, rec)
if self.locking:
self.start_read()
try:
r.size = wgdb.get_record_len(self._db, rec)
finally:
if self.locking:
self.end_read()
return r
def first_record(self):
"""Get first record from database."""
if self.locking:
self.start_read()
try:
r = wgdb.get_first_record(self._db)
except wgdb.error:
r = None
finally:
if self.locking:
self.end_read()
if not r:
return None
return self._new_record(r)
def next_record(self, rec):
"""Get next record from database."""
if self.locking:
self.start_read()
try:
r = wgdb.get_next_record(self._db, rec.get__rec())
except wgdb.error:
r = None
finally:
if self.locking:
self.end_read()
if not r:
return None
return self._new_record(r)
def create_record(self, size):
"""Create new record with given size."""
if size <= 0:
raise DataError("Invalid record size")
if self.locking:
self.start_write()
try:
r = wgdb.create_record(self._db, size)
finally:
if self.locking:
self.end_write()
return self._new_record(r)
def delete_record(self, rec):
"""Delete record."""
if self.locking:
self.start_write()
try:
r = wgdb.delete_record(self._db, rec.get__rec())
finally:
if self.locking:
self.end_write()
rec.set__rec(None) # prevent future usage
def atomic_create_record(self, fields):
"""Create a record and set field contents atomically."""
if not fields:
raise DataError("Cannot create an empty record")
l = len(fields)
tupletype = type(())
if self.locking:
self.start_write()
try:
r = wgdb.create_raw_record(self._db, l)
for i in range(l):
if type(fields[i]) == tupletype:
data = fields[i][0]
extarg = fields[i][1:]
else:
data = fields[i]
extarg = ()
if isinstance(data, Record):
data = data.get__rec()
fargs = (self._db, r, i, data) + extarg
wgdb.set_new_field(*fargs)
finally:
if self.locking:
self.end_write()
return self._new_record(r)
def atomic_update_record(self, rec, fields):
"""Set the contents of the entire record atomically."""
# fields should be a sequence
l = len(fields)
sz = rec.get_size()
r = rec.get__rec()
tupletype = type(())
if self.locking:
self.start_write()
try:
for i in range(l):
if type(fields[i]) == tupletype:
data = fields[i][0]
extarg = fields[i][1:]
else:
data = fields[i]
extarg = ()
if isinstance(data, Record):
data = data.get__rec()
fargs = (self._db, r, i, data) + extarg
wgdb.set_field(*fargs)
if l < sz:
# fill the remainder:
for i in range(l, sz):
wgdb.set_field(self._db, r, i, None)
finally:
if self.locking:
self.end_write()
# alias for atomic_create_record()
def insert(self, fields):
"""Insert a record into database"""
return self.atomic_create_record(fields)
# Field operations. Expect Record instances as argument
#
def get_field(self, rec, fieldnr):
"""Return data field contents"""
if self.locking:
self.start_read()
try:
data = wgdb.get_field(self._db, rec.get__rec(), fieldnr)
finally:
if self.locking:
self.end_read()
if wgdb.is_record(data):
return self._new_record(data)
else:
return data
def set_field(self, rec, fieldnr, data, *arg, **kwarg):
"""Set data field contents"""
if isinstance(data, Record):
data = data.get__rec()
if self.locking:
self.start_write()
try:
r = wgdb.set_field(self._db,
rec.get__rec(), fieldnr, data, *arg, **kwarg)
finally:
if self.locking:
self.end_write()
return r
# Query operations
#
def make_query(self, matchrec=None, *arg, **kwarg):
"""Create a query object."""
if isinstance(matchrec, Record):
matchrec = matchrec.get__rec()
if self.locking:
self.start_write() # write lock for parameter encoding
try:
query = wgdb.make_query(self._db,
matchrec, *arg, **kwarg)
finally:
if self.locking:
self.end_write()
return query
def fetch(self, query):
"""Get next record from query result set."""
if self.locking:
self.start_read()
try:
r = wgdb.fetch(self._db, query)
except wgdb.error:
r = None
finally:
if self.locking:
self.end_read()
if not r:
return None
return self._new_record(r)
def free_query(self, cur):
"""Free query belonging to a cursor."""
if not self._db: # plausible enough to warrant special handling
raise ProgrammingError("Database closed before freeing query "\
"(Hint: use Cursor.close() before Connection.close())")
if self.locking:
self.start_write() # may write shared memory
try:
r = wgdb.free_query(self._db, cur.get__query())
finally:
if self.locking:
self.end_write()
cur.set__query(None) # prevent future usage
class Cursor(object):
"""Cursor object. Supports wgdb-style queries based on match
records or argument lists. Does not currently support SQL."""
def __init__(self, conn):
self._query = None
self._conn = conn
self.rowcount = -1
def get__query(self):
"""Return low level query object"""
return self._query
def set__query(self, query):
"""Overwrite low level query object"""
self._query = query
def fetchone(self):
"""Fetch the next record from the result set"""
if not self._query:
raise ProgrammingError("No results to fetch.")
return self._conn.fetch(self._query)
def fetchall(self):
"""Fetch all (remaining) records from the result set"""
result = []
while 1:
r = self.fetchone()
if not r:
break
result.append(r)
return result
# includes sql parameter for future extension. Current
# wgdb queries should use arglist and matchrec keyword parameters.
def execute(self, sql="", matchrec=None, arglist=None):
"""Execute a database query"""
self._query = self._conn.make_query(matchrec=matchrec,
arglist=arglist)
if self._query.res_count is not None:
self.rowcount = self._query.res_count
# using cursors to insert data does not make sense
# in WhiteDB context, since there is no relation at all
# between the current cursor state and new records.
# This functionality will be moved to Connection object.
def insert(self, fields):
"""Insert a record into database --DEPRECATED--"""
return self._conn.atomic_create_record(fields)
def close(self):
"""Close the cursor"""
if self._query:
self._conn.free_query(self)
############## Additional classes: ###############
#
class Record(object):
"""Record data representation. Allows field-level and record-level
manipulation of data. Supports iterator and (partial) sequence protocol."""
def __init__(self, conn, rec):
self._rec = rec
self._conn = conn
self.size = 0
def get__rec(self):
"""Return low level record object"""
return self._rec
def set__rec(self, rec):
"""Overwrite low level record object"""
self._rec = rec
def get_size(self):
"""Return record size"""
return self.size
def get_field(self, fieldnr):
"""Return data field contents"""
if fieldnr < 0 or fieldnr >= self.size:
raise DataError("Field number out of bounds.")
return self._conn.get_field(self, fieldnr)
def set_field(self, fieldnr, data, *arg, **kwarg):
"""Set data field contents with optional encoding"""
if fieldnr < 0 or fieldnr >= self.size:
raise DataError("Field number out of bounds.")
return self._conn.set_field(self, fieldnr, data, *arg, **kwarg)
def update(self, fields):
"""Set the contents of the entire record"""
self._conn.atomic_update_record(self, fields)
def delete(self):
"""Delete the record from database"""
self._conn.delete_record(self)
# iterator protocol
def __iter__(self):
for fieldnr in range(self.size):
yield self.get_field(fieldnr)
# sequence protocol
def __getitem__(self, index):
return self.get_field(index)
def __setitem__(self, index, data, *arg, **kwarg):
# XXX: should we allow this?
# Could be counter-intuitive for users.
return self.set_field(index, data, *arg, **kwarg)
def __len__(self):
return self.size
############## DBI API functions: ###############
#
def connect(shmname=None, shmsize=0, local=0):
"""Attaches to (or creates) a database. Returns a database object"""
return Connection(shmname, shmsize, local)
|