xref: /4.6.4/couchstore/python/couchstore.py (revision 38654116)
1# couchstore.py
2# Python interface to CouchStore library
3
4import errno
5import sys
6import traceback
7
8try:
9    from ctypes import *
10except ImportError:
11    cb_path = '/opt/couchbase/lib/python'
12    while cb_path in sys.path:
13        sys.path.remove(cb_path)
14    try:
15        from ctypes import *
16    except ImportError:
17        sys.exit('error: could not import ctypes module')
18    else:
19        sys.path.insert(0, cb_path)
20
21# Load the couchstore library and customize return types:
22for lib in ('libcouchstore.so',      # Linux
23            'libcouchstore.dylib',   # Mac OS
24            'couchstore.dll',        # Windows
25            'libcouchstore-1.dll'):  # Windows (pre-CMake)
26    try:
27        _lib = CDLL(lib)
28        break
29    except OSError, err:
30        continue
31else:
32    traceback.print_exc()
33    sys.exit(1)
34
35
36_lib.couchstore_strerror.restype = c_char_p
37
38
39class CouchStoreException(Exception):
40    """Exceptions raised by CouchStore APIs."""
41    def __init__(self, errcode):
42        Exception.__init__(self, _lib.couchstore_strerror(errcode))
43        self.code = errcode
44
45
46### INTERNAL FUNCTIONS:
47
48def _check(err):
49    if err == 0:
50        return
51    elif err == -3:
52        raise MemoryError()
53    elif err == -5:
54        raise KeyError()
55    elif err == -11:
56        raise OSError(errno.ENOENT)
57    else:
58        raise CouchStoreException(err)
59
60
61def _toString(key):
62    if not isinstance(key, basestring):
63        raise TypeError(key)
64    return str(key)
65
66
67### INTERNAL STRUCTS:
68
69class SizedBuf(Structure):
70    _fields_ = [("buf", POINTER(c_char)), ("size", c_size_t)]
71
72    def __init__(self, string):
73        if string != None:
74            string = _toString(string)
75            length = len(string)
76            buf = create_string_buffer(string, length)
77            Structure.__init__(self, buf, length)
78        else:
79            Structure.__init__(self, None, 0)
80
81    def __str__(self):
82        return string_at(self.buf, self.size)
83
84
85class DocStruct(Structure):
86    _fields_ = [("id", SizedBuf), ("data", SizedBuf)]
87
88
89class DocInfoStruct(Structure):
90    _fields_ = [("id", SizedBuf),
91                ("db_seq", c_ulonglong),
92                ("rev_seq", c_ulonglong),
93                ("rev_meta", SizedBuf),
94                ("deleted", c_int),
95                ("content_meta", c_ubyte),
96                ("bp", c_ulonglong),
97                ("size", c_size_t) ]
98
99
100class LocalDocStruct(Structure):
101    _fields_ = [("id", SizedBuf),
102                ("json", SizedBuf),
103                ("deleted", c_int) ]
104
105
106class DbInfoStruct(Structure):
107    _fields_ = [("filename", c_char_p),
108                ("last_sequence", c_ulonglong),
109                ("doc_count", c_ulonglong),
110                ("deleted_count", c_ulonglong),
111                ("space_used", c_ulonglong),
112                ("header_position", c_ulonglong) ]
113
114
115class CounterStruct(Structure):
116    _fields_ = [("count", c_ulonglong)]
117
118### DOCUMENT INFO CLASS:
119
120
121class DocumentInfo(object):
122    """Metadata of a document in a CouchStore database."""
123
124    # Values for contentType:
125    IS_JSON = 0
126    INVALID_JSON = 1
127    INVALID_JSON_KEY = 2
128    NON_JSON = 3
129
130    def __init__(self, id):
131        self.id = id
132        self.deleted = False
133        self.contentType = DocumentInfo.NON_JSON
134        self.revSequence = 0
135
136    @staticmethod
137    def _fromStruct(info, store = None):
138        self = DocumentInfo(str(info.id))
139        self.store = store
140        self.sequence = info.db_seq
141        self.revSequence = info.rev_seq
142        self.revMeta = str(info.rev_meta)
143        self.deleted = (info.deleted != 0)
144        self.contentType = info.content_meta & 0x0F
145        self.compressed = (info.content_meta & 0x80) != 0
146        self._bp = info.bp
147        self.physSize = info.size
148        return self
149
150    def _asStruct(self):
151        struct = DocInfoStruct(SizedBuf(self.id))
152        if hasattr(self, "sequence"): struct.db_seq = self.sequence
153        if hasattr(self, "revMeta"): struct.rev_meta = SizedBuf(self.revMeta)
154        struct.rev_seq = self.revSequence
155        struct.deleted = self.deleted
156        struct.content_meta = self.contentType & 0x0F
157        if hasattr(self, "compressed") and self.compressed:
158            struct.content_meta |= 0x80
159        if hasattr(self, "_bp"): struct.bp = self._bp
160        if hasattr(self, "physSize"): struct.size = self.physSize
161        return struct
162
163    def __str__(self):
164        return "DocumentInfo('%s', %d bytes)" % (self.id, self.size)
165
166    def __repr__(self):
167        return "DocumentInfo('%s', %d bytes)" % (self.id, self.size)
168
169    def dump(self):
170        return "DocumentInfo('%s', %d bytes, seq=%d, revSeq=%d, deleted=%s, contentType=%d, compressed=%d, bp=%d)" % \
171                 (self.id, self.physSize, self.sequence, self.revSequence, self.deleted, \
172                  self.contentType, self.compressed, self._bp)
173
174    def getContents(self, options =0):
175        """Fetches and returns the contents of a DocumentInfo returned from CouchStore's getInfo
176           or getInfoBySequence methods."""
177        if not hasattr(self, "store") or not hasattr(self, "_bp"):
178            raise Exception("Contents unknown")
179        info = self._asStruct()
180        docptr = pointer(DocStruct())
181        _lib.couchstore_open_doc_with_docinfo(self.store, byref(info), byref(docptr), c_uint64(options))
182        contents = str(docptr.contents.data)
183        _lib.couchstore_free_document(docptr)
184        return contents
185
186
187### LOCAL-DOCUMENTS CLASS:
188
189class LocalDocs(object):
190    """Collection that represents the local documents of a CouchStore."""
191    def __init__(self, couchstore):
192        self.couchstore = couchstore
193
194    def __getitem__(self, key):
195        """Returns the contents of a local document (as a string) given its ID."""
196        id = _toString(key)
197        docptr = pointer(LocalDocStruct())
198        err = _lib.couchstore_open_local_document(self.couchstore, id, c_size_t(len(id)), byref(docptr))
199        if err == -5 or (err == 0 and docptr.contents.deleted):
200            raise KeyError(id)
201        _check(err)
202        value = str(docptr.contents.json)
203        _lib.couchstore_free_document(docptr)
204        return value
205
206    def __setitem__(self, key, value):
207        """Saves a local document with the given ID, or deletes it if the value is None."""
208        idbuf = SizedBuf(key)
209        doc = LocalDocStruct(idbuf)
210        if value != None:
211            doc.json = SizedBuf(value)
212        else:
213            doc.deleted = True
214        _check(_lib.couchstore_save_local_document(self.couchstore, byref(doc)))
215
216    def __delitem__(self, key):
217        self.__setitem__(key, None)
218
219
220### COUCHSTORE CLASS:
221
222class CouchStore(object):
223    """Interface to a CouchStore database."""
224
225    def __init__(self, path, mode =None):
226        """Creates a CouchStore at a given path. The option mode parameter can be 'r' for
227           read-only access, or 'c' to create the file if it doesn't already exist."""
228        if mode == 'r':
229            flags = 2 # RDONLY
230        elif mode == 'c':
231            flags = 1 # CREATE
232        else:
233            flags = 0
234
235        db = c_void_p()
236        _check(_lib.couchstore_open_db(path, c_uint64(flags), byref(db)))
237        self._as_parameter_ = db
238        self.path = path
239
240    def __del__(self):
241        self.close()
242
243    def close(self):
244        """Closes the CouchStore."""
245        if hasattr(self, "_as_parameter_"):
246            _lib.couchstore_close_db(self)
247            del self._as_parameter_
248
249    def __str__(self):
250        return "CouchStore(%s)" % self.path
251
252    def getDbInfo(self):
253        """Returns an object with information about the database.
254           Its properties are filename, last_sequence, doc_count, deleted_count, space_used, header_position."""
255        info = DbInfoStruct()
256        _check(_lib.couchstore_db_info(self, byref(info)))
257        return info
258
259    def rewindHeader(self):
260        """Rewinds the database handle to the next-oldest committed header. Closes the handle if none can be found"""
261        if hasattr(self, "_as_parameter_"):
262            err = _lib.couchstore_rewind_db_header(self)
263            if err != 0:
264                del self._as_parameter_
265            _check(err)
266
267    COMPRESS = 1
268
269    def save(self, id, data, options =0):
270        """Saves a document with the given ID. Returns the sequence number."""
271        if isinstance(id, DocumentInfo):
272            infoStruct = id._asStruct()
273            idbuf = infoStruct.id
274        else:
275            idbuf = SizedBuf(id)
276            infoStruct = DocInfoStruct(idbuf)
277        if data != None:
278            doc = DocStruct(idbuf, SizedBuf(data))
279            docref = byref(doc)
280            if options & CouchStore.COMPRESS:
281                infoStruct.content_meta |= 0x80
282        else:
283            docref = None
284        _check(_lib.couchstore_save_document(self, docref, byref(infoStruct), c_uint64(options)))
285        if isinstance(id, DocumentInfo):
286            id.sequence = infoStruct.db_seq
287        return infoStruct.db_seq
288
289    def saveMultiple(self, ids, datas, options =0):
290        """Saves multiple documents. 'ids' is an array of either strings or DocumentInfo objects.
291           'datas' is a parallel array of value strings (or None, in which case the documents
292           will be deleted.) Returns an array of new sequence numbers."""
293        n = len(ids)
294        docStructs = (POINTER(DocStruct) * n)()
295        infoStructs = (POINTER(DocInfoStruct) * n)()
296        for i in xrange(0, n):
297            id = ids[i]
298            if isinstance(id, DocumentInfo):
299                info = id._asStruct()
300            else:
301                info = DocInfoStruct(SizedBuf(id))
302            doc = DocStruct(info.id)
303            if datas and datas[i]:
304                doc.data = SizedBuf(datas[i])
305            else:
306                info.deleted = True
307            infoStructs[i] = pointer(info)
308            docStructs[i] = pointer(doc)
309        _check(_lib.couchstore_save_documents(self, byref(docStructs), byref(infoStructs), c_uint(n), \
310                                              c_uint64(options)))
311        return [info.contents.db_seq for info in infoStructs]
312    pass
313
314    def commit(self):
315        """Ensures all saved data is flushed to disk."""
316        _check(_lib.couchstore_commit(self))
317
318    DECOMPRESS = 1
319
320    def get(self, id, options =0):
321        """Returns the contents of a document (as a string) given its ID."""
322        id = _toString(id)
323        docptr = pointer(DocStruct())
324        err = _lib.couchstore_open_document(self, id, c_size_t(len(id)), byref(docptr), options)
325        if err == -5:
326            raise KeyError(id)
327        _check(err)
328        data = str(docptr.contents.data)
329        _lib.couchstore_free_document(docptr)
330        return data
331
332    def __getitem__(self, key):
333        return self.get(key)
334
335    def __setitem__(self, key, value):
336        self.save(key, value)
337
338    def __delitem__(self, key):
339        self.save(key, None)
340
341    # Getting document info:
342
343    def _infoPtrToDoc(self, key, infoptr, err):
344        if err == -5:
345            raise KeyError(key)
346        _check(err)
347        info = infoptr.contents
348        if info == None:
349            return None
350        doc = DocumentInfo._fromStruct(info, self)
351        _lib.couchstore_free_docinfo(infoptr)
352        return doc
353
354    def getInfo(self, id):
355        """Returns the DocumentInfo object with the given ID."""
356        id = _toString(id)
357        infoptr = pointer(DocInfoStruct())
358        err = _lib.couchstore_docinfo_by_id(self, id, c_size_t(len(id)), byref(infoptr))
359        return self._infoPtrToDoc(id, infoptr, err)
360
361    def getInfoBySequence(self, sequence):
362        """Returns the DocumentInfo object with the given sequence number."""
363        infoptr = pointer(DocInfoStruct())
364        err = _lib.couchstore_docinfo_by_sequence(self, c_ulonglong(sequence), byref(infoptr))
365        return self._infoPtrToDoc(sequence, infoptr, err)
366
367    # Iterating:
368
369    ITERATORFUNC = CFUNCTYPE(c_int, c_void_p, POINTER(DocInfoStruct), c_void_p)
370
371    def forEachChange(self, since, fn):
372        """Calls the function "fn" once for every document sequence since the "since" parameter.
373           The single parameter to "fn" will be a DocumentInfo object. You can call
374           getContents() on it to get the document contents."""
375        def callback(dbPtr, docInfoPtr, context):
376            fn(DocumentInfo._fromStruct(docInfoPtr.contents, self))
377            return 0
378        _check(_lib.couchstore_changes_since(self, c_uint64(since), c_uint64(0), \
379               CouchStore.ITERATORFUNC(callback), c_void_p(0)))
380
381    def changesSince(self, since):
382        """Returns an array of DocumentInfo objects, for every document that's changed since the
383           sequence number "since"."""
384        changes = []
385        self.forEachChange(since, lambda docInfo: changes.append(docInfo))
386        return changes
387
388    def forEachDoc(self, startKey, endKey, fn):
389        def callback(dbPtr, docInfoPtr, context):
390            fn(DocumentInfo._fromStruct(docInfoPtr.contents, self))
391            return 0
392
393        ids = (SizedBuf * 2)()
394        numIDs = 1
395        if startKey:
396            ids[0] = SizedBuf(startKey)
397        if endKey:
398            ids[1] = SizedBuf(endKey)
399            numIDs = 2
400        _check(_lib.couchstore_docinfos_by_id(self, ids, c_uint(numIDs), c_uint64(1), \
401               CouchStore.ITERATORFUNC(callback), c_void_p(0)))
402
403    def changesCount(self, minimum, maximum):
404        cstruct = CounterStruct()
405        err = _lib.couchstore_changes_count(self, c_uint64(minimum), \
406                                            c_uint64(maximum), pointer(cstruct))
407        _check(err)
408        return cstruct.count
409
410    @property
411    def localDocs(self):
412        """A simple dictionary-like object that accesses the CouchStore's local documents."""
413        return LocalDocs(self)
414