/Lib/bsddb/dbtables.py

http://unladen-swallow.googlecode.com/ · Python · 827 lines · 576 code · 88 blank · 163 comment · 128 complexity · 4199dc3d8bd99cde449754c75874d041 MD5 · raw file

  1. #-----------------------------------------------------------------------
  2. #
  3. # Copyright (C) 2000, 2001 by Autonomous Zone Industries
  4. # Copyright (C) 2002 Gregory P. Smith
  5. #
  6. # License: This is free software. You may use this software for any
  7. # purpose including modification/redistribution, so long as
  8. # this header remains intact and that you do not claim any
  9. # rights of ownership or authorship of this software. This
  10. # software has been tested, but no warranty is expressed or
  11. # implied.
  12. #
  13. # -- Gregory P. Smith <greg@krypto.org>
  14. # This provides a simple database table interface built on top of
  15. # the Python Berkeley DB 3 interface.
  16. #
  17. _cvsid = '$Id: dbtables.py 66088 2008-08-31 14:00:51Z jesus.cea $'
  18. import re
  19. import sys
  20. import copy
  21. import random
  22. import struct
  23. import cPickle as pickle
  24. try:
  25. # For Pythons w/distutils pybsddb
  26. from bsddb3 import db
  27. except ImportError:
  28. # For Python 2.3
  29. from bsddb import db
  30. # XXX(nnorwitz): is this correct? DBIncompleteError is conditional in _bsddb.c
  31. if not hasattr(db,"DBIncompleteError") :
  32. class DBIncompleteError(Exception):
  33. pass
  34. db.DBIncompleteError = DBIncompleteError
  35. class TableDBError(StandardError):
  36. pass
  37. class TableAlreadyExists(TableDBError):
  38. pass
  39. class Cond:
  40. """This condition matches everything"""
  41. def __call__(self, s):
  42. return 1
  43. class ExactCond(Cond):
  44. """Acts as an exact match condition function"""
  45. def __init__(self, strtomatch):
  46. self.strtomatch = strtomatch
  47. def __call__(self, s):
  48. return s == self.strtomatch
  49. class PrefixCond(Cond):
  50. """Acts as a condition function for matching a string prefix"""
  51. def __init__(self, prefix):
  52. self.prefix = prefix
  53. def __call__(self, s):
  54. return s[:len(self.prefix)] == self.prefix
  55. class PostfixCond(Cond):
  56. """Acts as a condition function for matching a string postfix"""
  57. def __init__(self, postfix):
  58. self.postfix = postfix
  59. def __call__(self, s):
  60. return s[-len(self.postfix):] == self.postfix
  61. class LikeCond(Cond):
  62. """
  63. Acts as a function that will match using an SQL 'LIKE' style
  64. string. Case insensitive and % signs are wild cards.
  65. This isn't perfect but it should work for the simple common cases.
  66. """
  67. def __init__(self, likestr, re_flags=re.IGNORECASE):
  68. # escape python re characters
  69. chars_to_escape = '.*+()[]?'
  70. for char in chars_to_escape :
  71. likestr = likestr.replace(char, '\\'+char)
  72. # convert %s to wildcards
  73. self.likestr = likestr.replace('%', '.*')
  74. self.re = re.compile('^'+self.likestr+'$', re_flags)
  75. def __call__(self, s):
  76. return self.re.match(s)
  77. #
  78. # keys used to store database metadata
  79. #
  80. _table_names_key = '__TABLE_NAMES__' # list of the tables in this db
  81. _columns = '._COLUMNS__' # table_name+this key contains a list of columns
  82. def _columns_key(table):
  83. return table + _columns
  84. #
  85. # these keys are found within table sub databases
  86. #
  87. _data = '._DATA_.' # this+column+this+rowid key contains table data
  88. _rowid = '._ROWID_.' # this+rowid+this key contains a unique entry for each
  89. # row in the table. (no data is stored)
  90. _rowid_str_len = 8 # length in bytes of the unique rowid strings
  91. def _data_key(table, col, rowid):
  92. return table + _data + col + _data + rowid
  93. def _search_col_data_key(table, col):
  94. return table + _data + col + _data
  95. def _search_all_data_key(table):
  96. return table + _data
  97. def _rowid_key(table, rowid):
  98. return table + _rowid + rowid + _rowid
  99. def _search_rowid_key(table):
  100. return table + _rowid
  101. def contains_metastrings(s) :
  102. """Verify that the given string does not contain any
  103. metadata strings that might interfere with dbtables database operation.
  104. """
  105. if (s.find(_table_names_key) >= 0 or
  106. s.find(_columns) >= 0 or
  107. s.find(_data) >= 0 or
  108. s.find(_rowid) >= 0):
  109. # Then
  110. return 1
  111. else:
  112. return 0
  113. class bsdTableDB :
  114. def __init__(self, filename, dbhome, create=0, truncate=0, mode=0600,
  115. recover=0, dbflags=0):
  116. """bsdTableDB(filename, dbhome, create=0, truncate=0, mode=0600)
  117. Open database name in the dbhome Berkeley DB directory.
  118. Use keyword arguments when calling this constructor.
  119. """
  120. self.db = None
  121. myflags = db.DB_THREAD
  122. if create:
  123. myflags |= db.DB_CREATE
  124. flagsforenv = (db.DB_INIT_MPOOL | db.DB_INIT_LOCK | db.DB_INIT_LOG |
  125. db.DB_INIT_TXN | dbflags)
  126. # DB_AUTO_COMMIT isn't a valid flag for env.open()
  127. try:
  128. dbflags |= db.DB_AUTO_COMMIT
  129. except AttributeError:
  130. pass
  131. if recover:
  132. flagsforenv = flagsforenv | db.DB_RECOVER
  133. self.env = db.DBEnv()
  134. # enable auto deadlock avoidance
  135. self.env.set_lk_detect(db.DB_LOCK_DEFAULT)
  136. self.env.open(dbhome, myflags | flagsforenv)
  137. if truncate:
  138. myflags |= db.DB_TRUNCATE
  139. self.db = db.DB(self.env)
  140. # this code relies on DBCursor.set* methods to raise exceptions
  141. # rather than returning None
  142. self.db.set_get_returns_none(1)
  143. # allow duplicate entries [warning: be careful w/ metadata]
  144. self.db.set_flags(db.DB_DUP)
  145. self.db.open(filename, db.DB_BTREE, dbflags | myflags, mode)
  146. self.dbfilename = filename
  147. if sys.version_info[0] >= 3 :
  148. class cursor_py3k(object) :
  149. def __init__(self, dbcursor) :
  150. self._dbcursor = dbcursor
  151. def close(self) :
  152. return self._dbcursor.close()
  153. def set_range(self, search) :
  154. v = self._dbcursor.set_range(bytes(search, "iso8859-1"))
  155. if v != None :
  156. v = (v[0].decode("iso8859-1"),
  157. v[1].decode("iso8859-1"))
  158. return v
  159. def __next__(self) :
  160. v = getattr(self._dbcursor, "next")()
  161. if v != None :
  162. v = (v[0].decode("iso8859-1"),
  163. v[1].decode("iso8859-1"))
  164. return v
  165. class db_py3k(object) :
  166. def __init__(self, db) :
  167. self._db = db
  168. def cursor(self, txn=None) :
  169. return cursor_py3k(self._db.cursor(txn=txn))
  170. def has_key(self, key, txn=None) :
  171. return getattr(self._db,"has_key")(bytes(key, "iso8859-1"),
  172. txn=txn)
  173. def put(self, key, value, flags=0, txn=None) :
  174. key = bytes(key, "iso8859-1")
  175. if value != None :
  176. value = bytes(value, "iso8859-1")
  177. return self._db.put(key, value, flags=flags, txn=txn)
  178. def put_bytes(self, key, value, txn=None) :
  179. key = bytes(key, "iso8859-1")
  180. return self._db.put(key, value, txn=txn)
  181. def get(self, key, txn=None, flags=0) :
  182. key = bytes(key, "iso8859-1")
  183. v = self._db.get(key, txn=txn, flags=flags)
  184. if v != None :
  185. v = v.decode("iso8859-1")
  186. return v
  187. def get_bytes(self, key, txn=None, flags=0) :
  188. key = bytes(key, "iso8859-1")
  189. return self._db.get(key, txn=txn, flags=flags)
  190. def delete(self, key, txn=None) :
  191. key = bytes(key, "iso8859-1")
  192. return self._db.delete(key, txn=txn)
  193. def close (self) :
  194. return self._db.close()
  195. self.db = db_py3k(self.db)
  196. else : # Python 2.x
  197. pass
  198. # Initialize the table names list if this is a new database
  199. txn = self.env.txn_begin()
  200. try:
  201. if not getattr(self.db, "has_key")(_table_names_key, txn):
  202. getattr(self.db, "put_bytes", self.db.put) \
  203. (_table_names_key, pickle.dumps([], 1), txn=txn)
  204. # Yes, bare except
  205. except:
  206. txn.abort()
  207. raise
  208. else:
  209. txn.commit()
  210. # TODO verify more of the database's metadata?
  211. self.__tablecolumns = {}
  212. def __del__(self):
  213. self.close()
  214. def close(self):
  215. if self.db is not None:
  216. self.db.close()
  217. self.db = None
  218. if self.env is not None:
  219. self.env.close()
  220. self.env = None
  221. def checkpoint(self, mins=0):
  222. try:
  223. self.env.txn_checkpoint(mins)
  224. except db.DBIncompleteError:
  225. pass
  226. def sync(self):
  227. try:
  228. self.db.sync()
  229. except db.DBIncompleteError:
  230. pass
  231. def _db_print(self) :
  232. """Print the database to stdout for debugging"""
  233. print "******** Printing raw database for debugging ********"
  234. cur = self.db.cursor()
  235. try:
  236. key, data = cur.first()
  237. while 1:
  238. print repr({key: data})
  239. next = cur.next()
  240. if next:
  241. key, data = next
  242. else:
  243. cur.close()
  244. return
  245. except db.DBNotFoundError:
  246. cur.close()
  247. def CreateTable(self, table, columns):
  248. """CreateTable(table, columns) - Create a new table in the database.
  249. raises TableDBError if it already exists or for other DB errors.
  250. """
  251. assert isinstance(columns, list)
  252. txn = None
  253. try:
  254. # checking sanity of the table and column names here on
  255. # table creation will prevent problems elsewhere.
  256. if contains_metastrings(table):
  257. raise ValueError(
  258. "bad table name: contains reserved metastrings")
  259. for column in columns :
  260. if contains_metastrings(column):
  261. raise ValueError(
  262. "bad column name: contains reserved metastrings")
  263. columnlist_key = _columns_key(table)
  264. if getattr(self.db, "has_key")(columnlist_key):
  265. raise TableAlreadyExists, "table already exists"
  266. txn = self.env.txn_begin()
  267. # store the table's column info
  268. getattr(self.db, "put_bytes", self.db.put)(columnlist_key,
  269. pickle.dumps(columns, 1), txn=txn)
  270. # add the table name to the tablelist
  271. tablelist = pickle.loads(getattr(self.db, "get_bytes",
  272. self.db.get) (_table_names_key, txn=txn, flags=db.DB_RMW))
  273. tablelist.append(table)
  274. # delete 1st, in case we opened with DB_DUP
  275. self.db.delete(_table_names_key, txn=txn)
  276. getattr(self.db, "put_bytes", self.db.put)(_table_names_key,
  277. pickle.dumps(tablelist, 1), txn=txn)
  278. txn.commit()
  279. txn = None
  280. except db.DBError, dberror:
  281. if txn:
  282. txn.abort()
  283. if sys.version_info[0] < 3 :
  284. raise TableDBError, dberror[1]
  285. else :
  286. raise TableDBError, dberror.args[1]
  287. def ListTableColumns(self, table):
  288. """Return a list of columns in the given table.
  289. [] if the table doesn't exist.
  290. """
  291. assert isinstance(table, str)
  292. if contains_metastrings(table):
  293. raise ValueError, "bad table name: contains reserved metastrings"
  294. columnlist_key = _columns_key(table)
  295. if not getattr(self.db, "has_key")(columnlist_key):
  296. return []
  297. pickledcolumnlist = getattr(self.db, "get_bytes",
  298. self.db.get)(columnlist_key)
  299. if pickledcolumnlist:
  300. return pickle.loads(pickledcolumnlist)
  301. else:
  302. return []
  303. def ListTables(self):
  304. """Return a list of tables in this database."""
  305. pickledtablelist = self.db.get_get(_table_names_key)
  306. if pickledtablelist:
  307. return pickle.loads(pickledtablelist)
  308. else:
  309. return []
  310. def CreateOrExtendTable(self, table, columns):
  311. """CreateOrExtendTable(table, columns)
  312. Create a new table in the database.
  313. If a table of this name already exists, extend it to have any
  314. additional columns present in the given list as well as
  315. all of its current columns.
  316. """
  317. assert isinstance(columns, list)
  318. try:
  319. self.CreateTable(table, columns)
  320. except TableAlreadyExists:
  321. # the table already existed, add any new columns
  322. txn = None
  323. try:
  324. columnlist_key = _columns_key(table)
  325. txn = self.env.txn_begin()
  326. # load the current column list
  327. oldcolumnlist = pickle.loads(
  328. getattr(self.db, "get_bytes",
  329. self.db.get)(columnlist_key, txn=txn, flags=db.DB_RMW))
  330. # create a hash table for fast lookups of column names in the
  331. # loop below
  332. oldcolumnhash = {}
  333. for c in oldcolumnlist:
  334. oldcolumnhash[c] = c
  335. # create a new column list containing both the old and new
  336. # column names
  337. newcolumnlist = copy.copy(oldcolumnlist)
  338. for c in columns:
  339. if not oldcolumnhash.has_key(c):
  340. newcolumnlist.append(c)
  341. # store the table's new extended column list
  342. if newcolumnlist != oldcolumnlist :
  343. # delete the old one first since we opened with DB_DUP
  344. self.db.delete(columnlist_key, txn=txn)
  345. getattr(self.db, "put_bytes", self.db.put)(columnlist_key,
  346. pickle.dumps(newcolumnlist, 1),
  347. txn=txn)
  348. txn.commit()
  349. txn = None
  350. self.__load_column_info(table)
  351. except db.DBError, dberror:
  352. if txn:
  353. txn.abort()
  354. if sys.version_info[0] < 3 :
  355. raise TableDBError, dberror[1]
  356. else :
  357. raise TableDBError, dberror.args[1]
  358. def __load_column_info(self, table) :
  359. """initialize the self.__tablecolumns dict"""
  360. # check the column names
  361. try:
  362. tcolpickles = getattr(self.db, "get_bytes",
  363. self.db.get)(_columns_key(table))
  364. except db.DBNotFoundError:
  365. raise TableDBError, "unknown table: %r" % (table,)
  366. if not tcolpickles:
  367. raise TableDBError, "unknown table: %r" % (table,)
  368. self.__tablecolumns[table] = pickle.loads(tcolpickles)
  369. def __new_rowid(self, table, txn) :
  370. """Create a new unique row identifier"""
  371. unique = 0
  372. while not unique:
  373. # Generate a random 64-bit row ID string
  374. # (note: might have <64 bits of true randomness
  375. # but it's plenty for our database id needs!)
  376. blist = []
  377. for x in xrange(_rowid_str_len):
  378. blist.append(random.randint(0,255))
  379. newid = struct.pack('B'*_rowid_str_len, *blist)
  380. if sys.version_info[0] >= 3 :
  381. newid = newid.decode("iso8859-1") # 8 bits
  382. # Guarantee uniqueness by adding this key to the database
  383. try:
  384. self.db.put(_rowid_key(table, newid), None, txn=txn,
  385. flags=db.DB_NOOVERWRITE)
  386. except db.DBKeyExistError:
  387. pass
  388. else:
  389. unique = 1
  390. return newid
  391. def Insert(self, table, rowdict) :
  392. """Insert(table, datadict) - Insert a new row into the table
  393. using the keys+values from rowdict as the column values.
  394. """
  395. txn = None
  396. try:
  397. if not getattr(self.db, "has_key")(_columns_key(table)):
  398. raise TableDBError, "unknown table"
  399. # check the validity of each column name
  400. if not self.__tablecolumns.has_key(table):
  401. self.__load_column_info(table)
  402. for column in rowdict.keys() :
  403. if not self.__tablecolumns[table].count(column):
  404. raise TableDBError, "unknown column: %r" % (column,)
  405. # get a unique row identifier for this row
  406. txn = self.env.txn_begin()
  407. rowid = self.__new_rowid(table, txn=txn)
  408. # insert the row values into the table database
  409. for column, dataitem in rowdict.items():
  410. # store the value
  411. self.db.put(_data_key(table, column, rowid), dataitem, txn=txn)
  412. txn.commit()
  413. txn = None
  414. except db.DBError, dberror:
  415. # WIBNI we could just abort the txn and re-raise the exception?
  416. # But no, because TableDBError is not related to DBError via
  417. # inheritance, so it would be backwards incompatible. Do the next
  418. # best thing.
  419. info = sys.exc_info()
  420. if txn:
  421. txn.abort()
  422. self.db.delete(_rowid_key(table, rowid))
  423. if sys.version_info[0] < 3 :
  424. raise TableDBError, dberror[1], info[2]
  425. else :
  426. raise TableDBError, dberror.args[1], info[2]
  427. def Modify(self, table, conditions={}, mappings={}):
  428. """Modify(table, conditions={}, mappings={}) - Modify items in rows matching 'conditions' using mapping functions in 'mappings'
  429. * table - the table name
  430. * conditions - a dictionary keyed on column names containing
  431. a condition callable expecting the data string as an
  432. argument and returning a boolean.
  433. * mappings - a dictionary keyed on column names containing a
  434. condition callable expecting the data string as an argument and
  435. returning the new string for that column.
  436. """
  437. try:
  438. matching_rowids = self.__Select(table, [], conditions)
  439. # modify only requested columns
  440. columns = mappings.keys()
  441. for rowid in matching_rowids.keys():
  442. txn = None
  443. try:
  444. for column in columns:
  445. txn = self.env.txn_begin()
  446. # modify the requested column
  447. try:
  448. dataitem = self.db.get(
  449. _data_key(table, column, rowid),
  450. txn=txn)
  451. self.db.delete(
  452. _data_key(table, column, rowid),
  453. txn=txn)
  454. except db.DBNotFoundError:
  455. # XXXXXXX row key somehow didn't exist, assume no
  456. # error
  457. dataitem = None
  458. dataitem = mappings[column](dataitem)
  459. if dataitem <> None:
  460. self.db.put(
  461. _data_key(table, column, rowid),
  462. dataitem, txn=txn)
  463. txn.commit()
  464. txn = None
  465. # catch all exceptions here since we call unknown callables
  466. except:
  467. if txn:
  468. txn.abort()
  469. raise
  470. except db.DBError, dberror:
  471. if sys.version_info[0] < 3 :
  472. raise TableDBError, dberror[1]
  473. else :
  474. raise TableDBError, dberror.args[1]
  475. def Delete(self, table, conditions={}):
  476. """Delete(table, conditions) - Delete items matching the given
  477. conditions from the table.
  478. * conditions - a dictionary keyed on column names containing
  479. condition functions expecting the data string as an
  480. argument and returning a boolean.
  481. """
  482. try:
  483. matching_rowids = self.__Select(table, [], conditions)
  484. # delete row data from all columns
  485. columns = self.__tablecolumns[table]
  486. for rowid in matching_rowids.keys():
  487. txn = None
  488. try:
  489. txn = self.env.txn_begin()
  490. for column in columns:
  491. # delete the data key
  492. try:
  493. self.db.delete(_data_key(table, column, rowid),
  494. txn=txn)
  495. except db.DBNotFoundError:
  496. # XXXXXXX column may not exist, assume no error
  497. pass
  498. try:
  499. self.db.delete(_rowid_key(table, rowid), txn=txn)
  500. except db.DBNotFoundError:
  501. # XXXXXXX row key somehow didn't exist, assume no error
  502. pass
  503. txn.commit()
  504. txn = None
  505. except db.DBError, dberror:
  506. if txn:
  507. txn.abort()
  508. raise
  509. except db.DBError, dberror:
  510. if sys.version_info[0] < 3 :
  511. raise TableDBError, dberror[1]
  512. else :
  513. raise TableDBError, dberror.args[1]
  514. def Select(self, table, columns, conditions={}):
  515. """Select(table, columns, conditions) - retrieve specific row data
  516. Returns a list of row column->value mapping dictionaries.
  517. * columns - a list of which column data to return. If
  518. columns is None, all columns will be returned.
  519. * conditions - a dictionary keyed on column names
  520. containing callable conditions expecting the data string as an
  521. argument and returning a boolean.
  522. """
  523. try:
  524. if not self.__tablecolumns.has_key(table):
  525. self.__load_column_info(table)
  526. if columns is None:
  527. columns = self.__tablecolumns[table]
  528. matching_rowids = self.__Select(table, columns, conditions)
  529. except db.DBError, dberror:
  530. if sys.version_info[0] < 3 :
  531. raise TableDBError, dberror[1]
  532. else :
  533. raise TableDBError, dberror.args[1]
  534. # return the matches as a list of dictionaries
  535. return matching_rowids.values()
  536. def __Select(self, table, columns, conditions):
  537. """__Select() - Used to implement Select and Delete (above)
  538. Returns a dictionary keyed on rowids containing dicts
  539. holding the row data for columns listed in the columns param
  540. that match the given conditions.
  541. * conditions is a dictionary keyed on column names
  542. containing callable conditions expecting the data string as an
  543. argument and returning a boolean.
  544. """
  545. # check the validity of each column name
  546. if not self.__tablecolumns.has_key(table):
  547. self.__load_column_info(table)
  548. if columns is None:
  549. columns = self.tablecolumns[table]
  550. for column in (columns + conditions.keys()):
  551. if not self.__tablecolumns[table].count(column):
  552. raise TableDBError, "unknown column: %r" % (column,)
  553. # keyed on rows that match so far, containings dicts keyed on
  554. # column names containing the data for that row and column.
  555. matching_rowids = {}
  556. # keys are rowids that do not match
  557. rejected_rowids = {}
  558. # attempt to sort the conditions in such a way as to minimize full
  559. # column lookups
  560. def cmp_conditions(atuple, btuple):
  561. a = atuple[1]
  562. b = btuple[1]
  563. if type(a) is type(b):
  564. if isinstance(a, PrefixCond) and isinstance(b, PrefixCond):
  565. # longest prefix first
  566. return cmp(len(b.prefix), len(a.prefix))
  567. if isinstance(a, LikeCond) and isinstance(b, LikeCond):
  568. # longest likestr first
  569. return cmp(len(b.likestr), len(a.likestr))
  570. return 0
  571. if isinstance(a, ExactCond):
  572. return -1
  573. if isinstance(b, ExactCond):
  574. return 1
  575. if isinstance(a, PrefixCond):
  576. return -1
  577. if isinstance(b, PrefixCond):
  578. return 1
  579. # leave all unknown condition callables alone as equals
  580. return 0
  581. if sys.version_info[0] < 3 :
  582. conditionlist = conditions.items()
  583. conditionlist.sort(cmp_conditions)
  584. else : # Insertion Sort. Please, improve
  585. conditionlist = []
  586. for i in conditions.items() :
  587. for j, k in enumerate(conditionlist) :
  588. r = cmp_conditions(k, i)
  589. if r == 1 :
  590. conditionlist.insert(j, i)
  591. break
  592. else :
  593. conditionlist.append(i)
  594. # Apply conditions to column data to find what we want
  595. cur = self.db.cursor()
  596. column_num = -1
  597. for column, condition in conditionlist:
  598. column_num = column_num + 1
  599. searchkey = _search_col_data_key(table, column)
  600. # speedup: don't linear search columns within loop
  601. if column in columns:
  602. savethiscolumndata = 1 # save the data for return
  603. else:
  604. savethiscolumndata = 0 # data only used for selection
  605. try:
  606. key, data = cur.set_range(searchkey)
  607. while key[:len(searchkey)] == searchkey:
  608. # extract the rowid from the key
  609. rowid = key[-_rowid_str_len:]
  610. if not rejected_rowids.has_key(rowid):
  611. # if no condition was specified or the condition
  612. # succeeds, add row to our match list.
  613. if not condition or condition(data):
  614. if not matching_rowids.has_key(rowid):
  615. matching_rowids[rowid] = {}
  616. if savethiscolumndata:
  617. matching_rowids[rowid][column] = data
  618. else:
  619. if matching_rowids.has_key(rowid):
  620. del matching_rowids[rowid]
  621. rejected_rowids[rowid] = rowid
  622. key, data = cur.next()
  623. except db.DBError, dberror:
  624. if sys.version_info[0] < 3 :
  625. if dberror[0] != db.DB_NOTFOUND:
  626. raise
  627. else :
  628. if dberror.args[0] != db.DB_NOTFOUND:
  629. raise
  630. continue
  631. cur.close()
  632. # we're done selecting rows, garbage collect the reject list
  633. del rejected_rowids
  634. # extract any remaining desired column data from the
  635. # database for the matching rows.
  636. if len(columns) > 0:
  637. for rowid, rowdata in matching_rowids.items():
  638. for column in columns:
  639. if rowdata.has_key(column):
  640. continue
  641. try:
  642. rowdata[column] = self.db.get(
  643. _data_key(table, column, rowid))
  644. except db.DBError, dberror:
  645. if sys.version_info[0] < 3 :
  646. if dberror[0] != db.DB_NOTFOUND:
  647. raise
  648. else :
  649. if dberror.args[0] != db.DB_NOTFOUND:
  650. raise
  651. rowdata[column] = None
  652. # return the matches
  653. return matching_rowids
  654. def Drop(self, table):
  655. """Remove an entire table from the database"""
  656. txn = None
  657. try:
  658. txn = self.env.txn_begin()
  659. # delete the column list
  660. self.db.delete(_columns_key(table), txn=txn)
  661. cur = self.db.cursor(txn)
  662. # delete all keys containing this tables column and row info
  663. table_key = _search_all_data_key(table)
  664. while 1:
  665. try:
  666. key, data = cur.set_range(table_key)
  667. except db.DBNotFoundError:
  668. break
  669. # only delete items in this table
  670. if key[:len(table_key)] != table_key:
  671. break
  672. cur.delete()
  673. # delete all rowids used by this table
  674. table_key = _search_rowid_key(table)
  675. while 1:
  676. try:
  677. key, data = cur.set_range(table_key)
  678. except db.DBNotFoundError:
  679. break
  680. # only delete items in this table
  681. if key[:len(table_key)] != table_key:
  682. break
  683. cur.delete()
  684. cur.close()
  685. # delete the tablename from the table name list
  686. tablelist = pickle.loads(
  687. getattr(self.db, "get_bytes", self.db.get)(_table_names_key,
  688. txn=txn, flags=db.DB_RMW))
  689. try:
  690. tablelist.remove(table)
  691. except ValueError:
  692. # hmm, it wasn't there, oh well, that's what we want.
  693. pass
  694. # delete 1st, incase we opened with DB_DUP
  695. self.db.delete(_table_names_key, txn=txn)
  696. getattr(self.db, "put_bytes", self.db.put)(_table_names_key,
  697. pickle.dumps(tablelist, 1), txn=txn)
  698. txn.commit()
  699. txn = None
  700. if self.__tablecolumns.has_key(table):
  701. del self.__tablecolumns[table]
  702. except db.DBError, dberror:
  703. if txn:
  704. txn.abort()
  705. if sys.version_info[0] < 3 :
  706. raise TableDBError, dberror[1]
  707. else :
  708. raise TableDBError, dberror.args[1]