PageRenderTime 33ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/bsddb/dbtables.py

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