blob: 95196e516d8fe3e855e1dad0847510837e96731e [file] [log] [blame]
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +00001#-----------------------------------------------------------------------
2#
3# Copyright (C) 2000, 2001 by Autonomous Zone Industries
Martin v. Löwisb2c7aff2002-11-23 11:26:07 +00004# Copyright (C) 2002 Gregory P. Smith
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +00005#
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@electricrain.com>
14
15# This provides a simple database table interface built on top of
16# the Python BerkeleyDB 3 interface.
17#
18_cvsid = '$Id$'
19
20import string
21import sys
22try:
23 import cPickle
24 pickle = cPickle
25except ImportError:
26 import pickle
27import whrandom
28import xdrlib
29import re
30import copy
31
Martin v. Löwis7a3bae42002-11-19 17:48:49 +000032from bsddb.db import *
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000033
34
35class TableDBError(StandardError): pass
36class TableAlreadyExists(TableDBError): pass
37
38
39class Cond:
40 """This condition matches everything"""
41 def __call__(self, s):
42 return 1
43
44class ExactCond(Cond):
45 """Acts as an exact match condition function"""
46 def __init__(self, strtomatch):
47 self.strtomatch = strtomatch
48 def __call__(self, s):
49 return s == self.strtomatch
50
51class PrefixCond(Cond):
52 """Acts as a condition function for matching a string prefix"""
53 def __init__(self, prefix):
54 self.prefix = prefix
55 def __call__(self, s):
56 return s[:len(self.prefix)] == self.prefix
57
Martin v. Löwisb2c7aff2002-11-23 11:26:07 +000058class PostfixCond(Cond):
59 """Acts as a condition function for matching a string postfix"""
60 def __init__(self, postfix):
61 self.postfix = postfix
62 def __call__(self, s):
63 return s[-len(self.postfix):] == self.postfix
64
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +000065class LikeCond(Cond):
66 """
67 Acts as a function that will match using an SQL 'LIKE' style
68 string. Case insensitive and % signs are wild cards.
69 This isn't perfect but it should work for the simple common cases.
70 """
71 def __init__(self, likestr, re_flags=re.IGNORECASE):
72 # escape python re characters
73 chars_to_escape = '.*+()[]?'
74 for char in chars_to_escape :
75 likestr = string.replace(likestr, char, '\\'+char)
76 # convert %s to wildcards
77 self.likestr = string.replace(likestr, '%', '.*')
78 self.re = re.compile('^'+self.likestr+'$', re_flags)
79 def __call__(self, s):
80 return self.re.match(s)
81
82#
83# keys used to store database metadata
84#
85_table_names_key = '__TABLE_NAMES__' # list of the tables in this db
86_columns = '._COLUMNS__' # table_name+this key contains a list of columns
87def _columns_key(table) : return table + _columns
88
89#
90# these keys are found within table sub databases
91#
92_data = '._DATA_.' # this+column+this+rowid key contains table data
93_rowid = '._ROWID_.' # this+rowid+this key contains a unique entry for each
94 # row in the table. (no data is stored)
95_rowid_str_len = 8 # length in bytes of the unique rowid strings
96def _data_key(table, col, rowid) : return table + _data + col + _data + rowid
97def _search_col_data_key(table, col) : return table + _data + col + _data
98def _search_all_data_key(table) : return table + _data
99def _rowid_key(table, rowid) : return table + _rowid + rowid + _rowid
100def _search_rowid_key(table) : return table + _rowid
101
102def contains_metastrings(s) :
103 """Verify that the given string does not contain any
104 metadata strings that might interfere with dbtables database operation.
105 """
106 if string.find(s, _table_names_key) >= 0 or \
107 string.find(s, _columns) >= 0 or \
108 string.find(s, _data) >= 0 or \
109 string.find(s, _rowid) >= 0 :
110 return 1
111 else :
112 return 0
113
114
115class bsdTableDB :
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000116 def __init__(self, filename, dbhome, create=0, truncate=0, mode=0600,
117 recover=0, dbflags=0) :
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000118 """bsdTableDB.open(filename, dbhome, create=0, truncate=0, mode=0600)
119 Open database name in the dbhome BerkeleyDB directory.
120 Use keyword arguments when calling this constructor.
121 """
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000122 self.db = None
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000123 myflags = DB_THREAD
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000124 if create:
125 myflags |= DB_CREATE
126 flagsforenv = (DB_INIT_MPOOL | DB_INIT_LOCK | DB_INIT_LOG |
127 DB_INIT_TXN | dbflags)
128 # DB_AUTO_COMMIT isn't a valid flag for env.open()
129 try:
130 dbflags |= DB_AUTO_COMMIT
131 except AttributeError:
132 pass
133 if recover:
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000134 flagsforenv = flagsforenv | DB_RECOVER
135 self.env = DBEnv()
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000136 # enable auto deadlock avoidance
137 self.env.set_lk_detect(DB_LOCK_DEFAULT)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000138 self.env.open(dbhome, myflags | flagsforenv)
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000139 if truncate:
140 myflags |= DB_TRUNCATE
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000141 self.db = DB(self.env)
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000142 # allow duplicate entries [warning: be careful w/ metadata]
143 self.db.set_flags(DB_DUP)
144 self.db.open(filename, DB_BTREE, dbflags | myflags, mode)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000145 self.dbfilename = filename
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000146 # Initialize the table names list if this is a new database
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000147 txn = self.env.txn_begin()
148 try:
149 if not self.db.has_key(_table_names_key, txn):
150 self.db.put(_table_names_key, pickle.dumps([], 1), txn=txn)
151 # Yes, bare except
152 except:
153 txn.abort()
154 raise
155 else:
156 txn.commit()
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000157 # TODO verify more of the database's metadata?
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000158 self.__tablecolumns = {}
159
160 def __del__(self):
161 self.close()
162
163 def close(self):
164 if self.db is not None:
165 self.db.close()
166 self.db = None
167 if self.env is not None:
168 self.env.close()
169 self.env = None
170
171 def checkpoint(self, mins=0):
172 try:
173 self.env.txn_checkpoint(mins)
174 except DBIncompleteError:
175 pass
176
177 def sync(self):
178 try:
179 self.db.sync()
180 except DBIncompleteError:
181 pass
182
183 def _db_print(self) :
184 """Print the database to stdout for debugging"""
185 print "******** Printing raw database for debugging ********"
186 cur = self.db.cursor()
187 try:
188 key, data = cur.first()
189 while 1 :
190 print `{key: data}`
191 next = cur.next()
192 if next:
193 key, data = next
194 else:
195 cur.close()
196 return
197 except DBNotFoundError:
198 cur.close()
199
200
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000201 def CreateTable(self, table, columns):
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000202 """CreateTable(table, columns) - Create a new table in the database
203 raises TableDBError if it already exists or for other DB errors.
204 """
205 assert type(columns) == type([])
206 txn = None
207 try:
208 # checking sanity of the table and column names here on
209 # table creation will prevent problems elsewhere.
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000210 if contains_metastrings(table):
211 raise ValueError(
212 "bad table name: contains reserved metastrings")
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000213 for column in columns :
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000214 if contains_metastrings(column):
215 raise ValueError(
216 "bad column name: contains reserved metastrings")
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000217
218 columnlist_key = _columns_key(table)
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000219 if self.db.has_key(columnlist_key):
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000220 raise TableAlreadyExists, "table already exists"
221
222 txn = self.env.txn_begin()
223 # store the table's column info
224 self.db.put(columnlist_key, pickle.dumps(columns, 1), txn=txn)
225
226 # add the table name to the tablelist
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000227 tablelist = pickle.loads(self.db.get(_table_names_key, txn=txn,
228 flags=DB_RMW))
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000229 tablelist.append(table)
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000230 # delete 1st, in case we opened with DB_DUP
231 self.db.delete(_table_names_key, txn)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000232 self.db.put(_table_names_key, pickle.dumps(tablelist, 1), txn=txn)
233
234 txn.commit()
235 txn = None
236
237 except DBError, dberror:
238 if txn :
239 txn.abort()
240 raise TableDBError, dberror[1]
241
242
243 def ListTableColumns(self, table):
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000244 """Return a list of columns in the given table.
245 [] if the table doesn't exist.
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000246 """
247 assert type(table) == type('')
248 if contains_metastrings(table) :
249 raise ValueError, "bad table name: contains reserved metastrings"
250
251 columnlist_key = _columns_key(table)
252 if not self.db.has_key(columnlist_key):
253 return []
254 pickledcolumnlist = self.db.get(columnlist_key)
255 if pickledcolumnlist:
256 return pickle.loads(pickledcolumnlist)
257 else:
258 return []
259
260 def ListTables(self):
261 """Return a list of tables in this database."""
262 pickledtablelist = self.db.get(_table_names_key)
263 if pickledtablelist:
264 return pickle.loads(pickledtablelist)
265 else:
266 return []
267
268 def CreateOrExtendTable(self, table, columns):
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000269 """CreateOrExtendTable(table, columns)
270
271 - Create a new table in the database.
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000272 If a table of this name already exists, extend it to have any
273 additional columns present in the given list as well as
274 all of its current columns.
275 """
276 assert type(columns) == type([])
277 try:
278 self.CreateTable(table, columns)
279 except TableAlreadyExists:
280 # the table already existed, add any new columns
281 txn = None
282 try:
283 columnlist_key = _columns_key(table)
284 txn = self.env.txn_begin()
285
286 # load the current column list
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000287 oldcolumnlist = pickle.loads(
288 self.db.get(columnlist_key, txn=txn, flags=DB_RMW))
289 # create a hash table for fast lookups of column names in the
290 # loop below
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000291 oldcolumnhash = {}
292 for c in oldcolumnlist:
293 oldcolumnhash[c] = c
294
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000295 # create a new column list containing both the old and new
296 # column names
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000297 newcolumnlist = copy.copy(oldcolumnlist)
298 for c in columns:
299 if not oldcolumnhash.has_key(c):
300 newcolumnlist.append(c)
301
302 # store the table's new extended column list
303 if newcolumnlist != oldcolumnlist :
304 # delete the old one first since we opened with DB_DUP
305 self.db.delete(columnlist_key, txn)
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000306 self.db.put(columnlist_key,
307 pickle.dumps(newcolumnlist, 1),
308 txn=txn)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000309
310 txn.commit()
311 txn = None
312
313 self.__load_column_info(table)
314 except DBError, dberror:
315 if txn:
316 txn.abort()
317 raise TableDBError, dberror[1]
318
319
320 def __load_column_info(self, table) :
321 """initialize the self.__tablecolumns dict"""
322 # check the column names
323 try:
324 tcolpickles = self.db.get(_columns_key(table))
325 except DBNotFoundError:
326 raise TableDBError, "unknown table: " + `table`
327 if not tcolpickles:
328 raise TableDBError, "unknown table: " + `table`
329 self.__tablecolumns[table] = pickle.loads(tcolpickles)
330
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000331 def __new_rowid(self, table, txn) :
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000332 """Create a new unique row identifier"""
333 unique = 0
334 while not unique :
335 # Generate a random 64-bit row ID string
336 # (note: this code has <64 bits of randomness
337 # but it's plenty for our database id needs!)
338 p = xdrlib.Packer()
339 p.pack_int(int(whrandom.random()*2147483647))
340 p.pack_int(int(whrandom.random()*2147483647))
341 newid = p.get_buffer()
342
343 # Guarantee uniqueness by adding this key to the database
344 try:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000345 self.db.put(_rowid_key(table, newid), None, txn=txn,
346 flags=DB_NOOVERWRITE)
347 except DBKeyExistError:
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000348 pass
349 else:
350 unique = 1
351
352 return newid
353
354
355 def Insert(self, table, rowdict) :
356 """Insert(table, datadict) - Insert a new row into the table
357 using the keys+values from rowdict as the column values.
358 """
359 txn = None
360 try:
361 if not self.db.has_key(_columns_key(table)) :
362 raise TableDBError, "unknown table"
363
364 # check the validity of each column name
365 if not self.__tablecolumns.has_key(table) :
366 self.__load_column_info(table)
367 for column in rowdict.keys() :
368 if not self.__tablecolumns[table].count(column) :
369 raise TableDBError, "unknown column: "+`column`
370
371 # get a unique row identifier for this row
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000372 txn = self.env.txn_begin()
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000373 rowid = self.__new_rowid(table, txn=txn)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000374
375 # insert the row values into the table database
376 for column, dataitem in rowdict.items() :
377 # store the value
378 self.db.put(_data_key(table, column, rowid), dataitem, txn=txn)
379
380 txn.commit()
381 txn = None
382
383 except DBError, dberror:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000384 # WIBNI we could just abort the txn and re-raise the exception?
385 # But no, because TableDBError is not related to DBError via
386 # inheritance, so it would be backwards incompatible. Do the next
387 # best thing.
388 info = sys.exc_info()
389 if txn:
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000390 txn.abort()
391 self.db.delete(_rowid_key(table, rowid))
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000392 raise TableDBError, dberror[1], info[2]
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000393
394
395 def Modify(self, table, conditions={}, mappings={}) :
396 """Modify(table, conditions) - Modify in rows matching 'conditions'
397 using mapping functions in 'mappings'
398 * conditions is a dictionary keyed on column names
399 containing condition functions expecting the data string as an
400 argument and returning a boolean.
401 * mappings is a dictionary keyed on column names containint condition
402 functions expecting the data string as an argument and returning the
403 new string for that column.
404 """
405 try:
406 matching_rowids = self.__Select(table, [], conditions)
407
408 # modify only requested columns
409 columns = mappings.keys()
410 for rowid in matching_rowids.keys() :
411 txn = None
412 try:
413 for column in columns :
414 txn = self.env.txn_begin()
415 # modify the requested column
416 try:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000417 dataitem = self.db.get(
418 _data_key(table, column, rowid),
419 txn)
420 self.db.delete(
421 _data_key(table, column, rowid),
422 txn)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000423 except DBNotFoundError:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000424 # XXXXXXX row key somehow didn't exist, assume no
425 # error
426 dataitem = None
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000427 dataitem = mappings[column](dataitem)
428 if dataitem <> None:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000429 self.db.put(
430 _data_key(table, column, rowid),
431 dataitem, txn=txn)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000432 txn.commit()
433 txn = None
434
435 except DBError, dberror:
436 if txn :
437 txn.abort()
438 raise
439
440 except DBError, dberror:
441 raise TableDBError, dberror[1]
442
443 def Delete(self, table, conditions={}) :
444 """Delete(table, conditions) - Delete items matching the given
445 conditions from the table.
446 * conditions is a dictionary keyed on column names
447 containing condition functions expecting the data string as an
448 argument and returning a boolean.
449 """
450 try:
451 matching_rowids = self.__Select(table, [], conditions)
452
453 # delete row data from all columns
454 columns = self.__tablecolumns[table]
455 for rowid in matching_rowids.keys() :
456 txn = None
457 try:
458 txn = self.env.txn_begin()
459 for column in columns :
460 # delete the data key
461 try:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000462 self.db.delete(_data_key(table, column, rowid),
463 txn)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000464 except DBNotFoundError:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000465 # XXXXXXX column may not exist, assume no error
466 pass
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000467
468 try:
469 self.db.delete(_rowid_key(table, rowid), txn)
470 except DBNotFoundError:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000471 # XXXXXXX row key somehow didn't exist, assume no error
472 pass
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000473 txn.commit()
474 txn = None
475 except DBError, dberror:
476 if txn :
477 txn.abort()
478 raise
479
480 except DBError, dberror:
481 raise TableDBError, dberror[1]
482
483
484 def Select(self, table, columns, conditions={}) :
485 """Select(table, conditions) - retrieve specific row data
486 Returns a list of row column->value mapping dictionaries.
487 * columns is a list of which column data to return. If
488 columns is None, all columns will be returned.
489 * conditions is a dictionary keyed on column names
490 containing callable conditions expecting the data string as an
491 argument and returning a boolean.
492 """
493 try:
494 if not self.__tablecolumns.has_key(table) :
495 self.__load_column_info(table)
496 if columns is None :
497 columns = self.__tablecolumns[table]
498 matching_rowids = self.__Select(table, columns, conditions)
499 except DBError, dberror:
500 raise TableDBError, dberror[1]
501
502 # return the matches as a list of dictionaries
503 return matching_rowids.values()
504
505
506 def __Select(self, table, columns, conditions) :
507 """__Select() - Used to implement Select and Delete (above)
508 Returns a dictionary keyed on rowids containing dicts
509 holding the row data for columns listed in the columns param
510 that match the given conditions.
511 * conditions is a dictionary keyed on column names
512 containing callable conditions expecting the data string as an
513 argument and returning a boolean.
514 """
515 # check the validity of each column name
516 if not self.__tablecolumns.has_key(table) :
517 self.__load_column_info(table)
518 if columns is None :
519 columns = self.tablecolumns[table]
520 for column in (columns + conditions.keys()) :
521 if not self.__tablecolumns[table].count(column) :
522 raise TableDBError, "unknown column: "+`column`
523
524 # keyed on rows that match so far, containings dicts keyed on
525 # column names containing the data for that row and column.
526 matching_rowids = {}
527
528 rejected_rowids = {} # keys are rowids that do not match
529
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000530 # attempt to sort the conditions in such a way as to minimize full
531 # column lookups
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000532 def cmp_conditions(atuple, btuple):
533 a = atuple[1]
534 b = btuple[1]
535 if type(a) == type(b) :
536 if isinstance(a, PrefixCond) and isinstance(b, PrefixCond):
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000537 # longest prefix first
538 return cmp(len(b.prefix), len(a.prefix))
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000539 if isinstance(a, LikeCond) and isinstance(b, LikeCond):
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000540 # longest likestr first
541 return cmp(len(b.likestr), len(a.likestr))
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000542 return 0
543 if isinstance(a, ExactCond):
544 return -1
545 if isinstance(b, ExactCond):
546 return 1
547 if isinstance(a, PrefixCond):
548 return -1
549 if isinstance(b, PrefixCond):
550 return 1
551 # leave all unknown condition callables alone as equals
552 return 0
553
554 conditionlist = conditions.items()
555 conditionlist.sort(cmp_conditions)
556
557 # Apply conditions to column data to find what we want
558 cur = self.db.cursor()
559 column_num = -1
560 for column, condition in conditionlist :
561 column_num = column_num + 1
562 searchkey = _search_col_data_key(table, column)
563 # speedup: don't linear search columns within loop
564 if column in columns :
565 savethiscolumndata = 1 # save the data for return
566 else :
567 savethiscolumndata = 0 # data only used for selection
568
569 try:
570 key, data = cur.set_range(searchkey)
571 while key[:len(searchkey)] == searchkey :
572 # extract the rowid from the key
573 rowid = key[-_rowid_str_len:]
574
575 if not rejected_rowids.has_key(rowid) :
576 # if no condition was specified or the condition
577 # succeeds, add row to our match list.
578 if not condition or condition(data) :
Martin v. Löwisb2c7aff2002-11-23 11:26:07 +0000579 if not matching_rowids.has_key(rowid) :
580 matching_rowids[rowid] = {}
581 if savethiscolumndata :
582 matching_rowids[rowid][column] = data
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000583 else :
584 if matching_rowids.has_key(rowid) :
585 del matching_rowids[rowid]
586 rejected_rowids[rowid] = rowid
587
588 key, data = cur.next()
589
590 except DBError, dberror:
591 if dberror[0] != DB_NOTFOUND :
592 raise
593 continue
594
595 cur.close()
596
597 # we're done selecting rows, garbage collect the reject list
598 del rejected_rowids
599
600 # extract any remaining desired column data from the
601 # database for the matching rows.
602 if len(columns) > 0 :
603 for rowid, rowdata in matching_rowids.items() :
604 for column in columns :
605 if rowdata.has_key(column) :
606 continue
607 try:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000608 rowdata[column] = self.db.get(
609 _data_key(table, column, rowid))
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000610 except DBError, dberror:
611 if dberror[0] != DB_NOTFOUND :
612 raise
613 rowdata[column] = None
614
615 # return the matches
616 return matching_rowids
617
618
619 def Drop(self, table) :
620 """Remove an entire table from the database
621 """
622 txn = None
623 try:
624 txn = self.env.txn_begin()
625
626 # delete the column list
627 self.db.delete(_columns_key(table), txn)
628
629 cur = self.db.cursor(txn)
630
631 # delete all keys containing this tables column and row info
632 table_key = _search_all_data_key(table)
633 while 1 :
634 try:
635 key, data = cur.set_range(table_key)
636 except DBNotFoundError:
637 break
638 # only delete items in this table
639 if key[:len(table_key)] != table_key :
640 break
641 cur.delete()
642
643 # delete all rowids used by this table
644 table_key = _search_rowid_key(table)
645 while 1 :
646 try:
647 key, data = cur.set_range(table_key)
648 except DBNotFoundError:
649 break
650 # only delete items in this table
651 if key[:len(table_key)] != table_key :
652 break
653 cur.delete()
654
655 cur.close()
656
657 # delete the tablename from the table name list
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000658 tablelist = pickle.loads(
659 self.db.get(_table_names_key, txn=txn, flags=DB_RMW))
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000660 try:
661 tablelist.remove(table)
662 except ValueError:
Barry Warsaw9a0d7792002-12-30 20:53:52 +0000663 # hmm, it wasn't there, oh well, that's what we want.
664 pass
665 # delete 1st, incase we opened with DB_DUP
666 self.db.delete(_table_names_key, txn)
Martin v. Löwis6aa4a1f2002-11-19 08:09:52 +0000667 self.db.put(_table_names_key, pickle.dumps(tablelist, 1), txn=txn)
668
669 txn.commit()
670 txn = None
671
672 if self.__tablecolumns.has_key(table) :
673 del self.__tablecolumns[table]
674
675 except DBError, dberror:
676 if txn :
677 txn.abort()
678 raise TableDBError, dberror[1]