blob: 1c4c0a3d203e6e1175bc579c0b66a4444f9c7a06 [file] [log] [blame]
Georg Brandl0a7ac7d2008-05-26 10:29:35 +00001:mod:`dbm` --- Interfaces to Unix "databases"
2=============================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: dbm
Georg Brandl0a7ac7d2008-05-26 10:29:35 +00005 :synopsis: Interfaces to various Unix "database" formats.
6
7:mod:`dbm` is a generic interface to variants of the DBM database ---
8:mod:`dbm.bsd` (requires :mod:`bsddb`), :mod:`dbm.gnu`, or :mod:`dbm.ndbm`. If
9none of these modules is installed, the slow-but-simple implementation in module
10:mod:`dbm.dumb` will be used.
11
12
13.. exception:: error
14
15 A tuple containing the exceptions that can be raised by each of the supported
16 modules, with a unique exception also named :exc:`dbm.error` as the first
17 item --- the latter is used when :exc:`dbm.error` is raised.
18
19
20.. function:: whichdb(filename)
21
22 This functionattempts to guess which of the several simple database modules
23 available --- :mod:`dbm.bsd`, :mod:`dbm.gnu`, :mod:`dbm.ndbm` or
24 :mod:`dbm.dumb` --- should be used to open a given file.
25
26 Returns one of the following values: ``None`` if the file can't be opened
27 because it's unreadable or doesn't exist; the empty string (``''``) if the
28 file's format can't be guessed; or a string containing the required module
29 name, such as ``'dbm.ndbm'`` or ``'dbm.gnu'``.
30
31
32.. function:: open(filename[, flag[, mode]])
33
34 Open the database file *filename* and return a corresponding object.
35
36 If the database file already exists, the :func:`whichdb` function is used to
37 determine its type and the appropriate module is used; if it does not exist,
38 the first module listed above that can be imported is used.
39
40 The optional *flag* argument can be ``'r'`` to open an existing database for
41 reading only, ``'w'`` to open an existing database for reading and writing,
42 ``'c'`` to create the database if it doesn't exist, or ``'n'``, which will
43 always create a new empty database. If not specified, the default value is
44 ``'r'``.
45
46 The optional *mode* argument is the Unix mode of the file, used only when the
47 database has to be created. It defaults to octal ``0o666`` (and will be
48 modified by the prevailing umask).
49
50
51The object returned by :func:`open` supports most of the same functionality as
52dictionaries; keys and their corresponding values can be stored, retrieved, and
53deleted, and the :keyword:`in` operator and the :meth:`keys` method are
54available. Keys and values must always be strings.
55
56The following example records some hostnames and a corresponding title, and
57then prints out the contents of the database::
58
59 import dbm
60
61 # Open database, creating it if necessary.
62 db = dbm.open('cache', 'c')
63
64 # Record some values
65 db['www.python.org'] = 'Python Website'
66 db['www.cnn.com'] = 'Cable News Network'
67
68 # Loop through contents. Other dictionary methods
69 # such as .keys(), .values() also work.
70 for k, v in db.iteritems():
71 print(k, '\t', v)
72
73 # Storing a non-string key or value will raise an exception (most
74 # likely a TypeError).
75 db['www.yahoo.com'] = 4
76
77 # Close when done.
78 db.close()
79
80
81.. seealso::
82
83 Module :mod:`shelve`
84 Persistence module which stores non-string data.
85
86
87The individual submodules are described in the following sections.
88
89
90:mod:`dbm.bsd` --- DBM-style interface to the BSD database library
91------------------------------------------------------------------
92
93.. module:: dbm.bsd
94 :synopsis: DBM-style interface to the BSD database library.
95.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
96
97.. index:: module: bsddb
98
99The :mod:`dbm.bsd` module provides a function to open databases using the BSD
100``db`` library. This module mirrors the interface of the other Python database
101modules that provide access to DBM-style databases. The :mod:`bsddb` module is
102required to use :mod:`dbm.bsd`.
103
104.. exception:: error
105
106 Exception raised on database errors other than :exc:`KeyError`. It is a synonym
107 for :exc:`bsddb.error`.
108
109
110.. function:: open(path[, flag[, mode]])
111
112 Open a ``db`` database and return the database object. The *path* argument is
113 the name of the database file.
114
115 The *flag* argument can be:
116
117 +---------+-------------------------------------------+
118 | Value | Meaning |
119 +=========+===========================================+
120 | ``'r'`` | Open existing database for reading only |
121 | | (default) |
122 +---------+-------------------------------------------+
123 | ``'w'`` | Open existing database for reading and |
124 | | writing |
125 +---------+-------------------------------------------+
126 | ``'c'`` | Open database for reading and writing, |
127 | | creating it if it doesn't exist |
128 +---------+-------------------------------------------+
129 | ``'n'`` | Always create a new, empty database, open |
130 | | for reading and writing |
131 +---------+-------------------------------------------+
132
133 For platforms on which the BSD ``db`` library supports locking, an ``'l'``
134 can be appended to indicate that locking should be used.
135
136 The optional *mode* parameter is used to indicate the Unix permission bits that
137 should be set if a new database must be created; this will be masked by the
138 current umask value for the process.
139
140 The database objects returned by :func:`open` provide the methods common to all
141 the DBM-style databases and mapping objects. The following methods are
142 available in addition to the standard methods:
143
144 .. method:: dbhash.first()
145
146 It's possible to loop over every key/value pair in the database using this
147 method and the :meth:`next` method. The traversal is ordered by the databases
148 internal hash values, and won't be sorted by the key values. This method
149 returns the starting key.
150
151 .. method:: dbhash.last()
152
153 Return the last key/value pair in a database traversal. This may be used to
154 begin a reverse-order traversal; see :meth:`previous`.
155
156 .. method:: dbhash.next()
157
158 Returns the key next key/value pair in a database traversal. The following code
159 prints every key in the database ``db``, without having to create a list in
160 memory that contains them all::
161
162 print(db.first())
163 for i in range(1, len(db)):
164 print(db.next())
165
166 .. method:: dbhash.previous()
167
168 Returns the previous key/value pair in a forward-traversal of the database. In
169 conjunction with :meth:`last`, this may be used to implement a reverse-order
170 traversal.
171
172 .. method:: dbhash.sync()
173
174 This method forces any unwritten data to be written to the disk.
175
176
177:mod:`dbm.gnu` --- GNU's reinterpretation of dbm
178------------------------------------------------
179
180.. module:: dbm.gnu
181 :platform: Unix
182 :synopsis: GNU's reinterpretation of dbm.
183
184
185This module is quite similar to the :mod:`dbm` module, but uses the GNU library
186``gdbm`` instead to provide some additional functionality. Please note that the
187file formats created by ``gdbm`` and ``dbm`` are incompatible.
188
189The :mod:`dbm.gnu` module provides an interface to the GNU DBM library.
190``gdbm`` objects behave like mappings (dictionaries), except that keys and
191values are always strings. Printing a :mod:`dbm.gnu` object doesn't print the
192keys and values, and the :meth:`items` and :meth:`values` methods are not
193supported.
194
195.. exception:: error
196
197 Raised on ``gdbm``\ -specific errors, such as I/O errors. :exc:`KeyError` is
198 raised for general mapping errors like specifying an incorrect key.
199
200
201.. function:: open(filename, [flag, [mode]])
202
203 Open a ``gdbm`` database and return a :class:`gdbm` object. The *filename*
204 argument is the name of the database file.
205
206 The optional *flag* argument can be:
207
208 +---------+-------------------------------------------+
209 | Value | Meaning |
210 +=========+===========================================+
211 | ``'r'`` | Open existing database for reading only |
212 | | (default) |
213 +---------+-------------------------------------------+
214 | ``'w'`` | Open existing database for reading and |
215 | | writing |
216 +---------+-------------------------------------------+
217 | ``'c'`` | Open database for reading and writing, |
218 | | creating it if it doesn't exist |
219 +---------+-------------------------------------------+
220 | ``'n'`` | Always create a new, empty database, open |
221 | | for reading and writing |
222 +---------+-------------------------------------------+
223
224 The following additional characters may be appended to the flag to control
225 how the database is opened:
226
227 +---------+--------------------------------------------+
228 | Value | Meaning |
229 +=========+============================================+
230 | ``'f'`` | Open the database in fast mode. Writes |
231 | | to the database will not be synchronized. |
232 +---------+--------------------------------------------+
233 | ``'s'`` | Synchronized mode. This will cause changes |
234 | | to the database to be immediately written |
235 | | to the file. |
236 +---------+--------------------------------------------+
237 | ``'u'`` | Do not lock database. |
238 +---------+--------------------------------------------+
239
240 Not all flags are valid for all versions of ``gdbm``. The module constant
241 :const:`open_flags` is a string of supported flag characters. The exception
242 :exc:`error` is raised if an invalid flag is specified.
243
244 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000245 database has to be created. It defaults to octal ``0o666``.
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000246
247 In addition to the dictionary-like methods, ``gdbm`` objects have the
248 following methods:
249
250 .. method:: gdbm.firstkey()
251
252 It's possible to loop over every key in the database using this method and the
253 :meth:`nextkey` method. The traversal is ordered by ``gdbm``'s internal
254 hash values, and won't be sorted by the key values. This method returns
255 the starting key.
256
257 .. method:: gdbm.nextkey(key)
258
259 Returns the key that follows *key* in the traversal. The following code prints
260 every key in the database ``db``, without having to create a list in memory that
261 contains them all::
262
263 k = db.firstkey()
264 while k != None:
265 print(k)
266 k = db.nextkey(k)
267
268 .. method:: gdbm.reorganize()
269
270 If you have carried out a lot of deletions and would like to shrink the space
271 used by the ``gdbm`` file, this routine will reorganize the database. ``gdbm``
272 will not shorten the length of a database file except by using this
273 reorganization; otherwise, deleted file space will be kept and reused as new
274 (key, value) pairs are added.
275
276 .. method:: gdbm.sync()
277
278 When the database has been opened in fast mode, this method forces any
279 unwritten data to be written to the disk.
280
281
282:mod:`dbm.ndbm` --- Interface based on ndbm
283-------------------------------------------
284
285.. module:: dbm.ndbm
Georg Brandl116aa622007-08-15 14:28:22 +0000286 :platform: Unix
287 :synopsis: The standard "database" interface, based on ndbm.
288
289
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000290The :mod:`dbm.ndbm` module provides an interface to the Unix "(n)dbm" library.
291Dbm objects behave like mappings (dictionaries), except that keys and values are
Georg Brandl116aa622007-08-15 14:28:22 +0000292always strings. Printing a dbm object doesn't print the keys and values, and the
293:meth:`items` and :meth:`values` methods are not supported.
294
295This module can be used with the "classic" ndbm interface, the BSD DB
296compatibility interface, or the GNU GDBM compatibility interface. On Unix, the
297:program:`configure` script will attempt to locate the appropriate header file
298to simplify building this module.
299
Georg Brandl116aa622007-08-15 14:28:22 +0000300.. exception:: error
301
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000302 Raised on dbm-specific errors, such as I/O errors. :exc:`KeyError` is raised
303 for general mapping errors like specifying an incorrect key.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305
306.. data:: library
307
308 Name of the ``ndbm`` implementation library used.
309
310
311.. function:: open(filename[, flag[, mode]])
312
313 Open a dbm database and return a dbm object. The *filename* argument is the
314 name of the database file (without the :file:`.dir` or :file:`.pag` extensions;
315 note that the BSD DB implementation of the interface will append the extension
316 :file:`.db` and only create one file).
317
318 The optional *flag* argument must be one of these values:
319
320 +---------+-------------------------------------------+
321 | Value | Meaning |
322 +=========+===========================================+
323 | ``'r'`` | Open existing database for reading only |
324 | | (default) |
325 +---------+-------------------------------------------+
326 | ``'w'`` | Open existing database for reading and |
327 | | writing |
328 +---------+-------------------------------------------+
329 | ``'c'`` | Open database for reading and writing, |
330 | | creating it if it doesn't exist |
331 +---------+-------------------------------------------+
332 | ``'n'`` | Always create a new, empty database, open |
333 | | for reading and writing |
334 +---------+-------------------------------------------+
335
336 The optional *mode* argument is the Unix mode of the file, used only when the
Georg Brandlf4a41232008-05-26 17:55:52 +0000337 database has to be created. It defaults to octal ``0o666`` (and will be
Georg Brandl116aa622007-08-15 14:28:22 +0000338 modified by the prevailing umask).
339
340
Georg Brandl116aa622007-08-15 14:28:22 +0000341
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000342:mod:`dbm.dumb` --- Portable DBM implementation
343-----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000345.. module:: dbm.dumb
346 :synopsis: Portable implementation of the simple DBM interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000348.. index:: single: databases
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Georg Brandl0a7ac7d2008-05-26 10:29:35 +0000350.. note::
351
352 The :mod:`dbm.dumb` module is intended as a last resort fallback for the
353 :mod:`dbm` module when no more robust module is available. The :mod:`dbm.dumb`
354 module is not written for speed and is not nearly as heavily used as the other
355 database modules.
356
357The :mod:`dbm.dumb` module provides a persistent dictionary-like interface which
358is written entirely in Python. Unlike other modules such as :mod:`gdbm` and
359:mod:`bsddb`, no external library is required. As with other persistent
360mappings, the keys and values must always be strings.
361
362The module defines the following:
363
364
365.. exception:: error
366
367 Raised on dbm.dumb-specific errors, such as I/O errors. :exc:`KeyError` is
368 raised for general mapping errors like specifying an incorrect key.
369
370
371.. function:: open(filename[, flag[, mode]])
372
373 Open a dumbdbm database and return a dumbdbm object. The *filename* argument is
374 the basename of the database file (without any specific extensions). When a
375 dumbdbm database is created, files with :file:`.dat` and :file:`.dir` extensions
376 are created.
377
378 The optional *flag* argument is currently ignored; the database is always opened
379 for update, and will be created if it does not exist.
380
381 The optional *mode* argument is the Unix mode of the file, used only when the
382 database has to be created. It defaults to octal ``0o666`` (and will be modified
383 by the prevailing umask).
384
385 In addition to the methods provided by the :class:`collections.MutableMapping` class,
386 :class:`dumbdbm` objects provide the following method:
387
388 .. method:: dumbdbm.sync()
389
390 Synchronize the on-disk directory and data files. This method is called
391 by the :meth:`Shelve.sync` method.