Created
April 19, 2013 20:33
-
-
Save BrianHicks/5423037 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'really simple ORM for RethinkDB objects' | |
import inflect | |
import re | |
import rethinkdb as r | |
p = inflect.engine() | |
class DocumentMetaClass(type): | |
def __new__(meta, classname, bases, attrs): | |
if '_table' not in attrs: | |
base = re.sub("(.)([A-Z])", r'\1_\2', classname).lower() | |
attrs['_table'] = p.plural(base) | |
attrs['r'] = r.table(attrs['_table']) | |
return type.__new__(meta, classname, bases, attrs) | |
class Document(dict): | |
'wrapper and convenience methods for rethinkdb documents' | |
__metaclass__ = DocumentMetaClass | |
#_db = None | |
_pk = 'id' | |
def save(self, conn): | |
if self._pk in self: | |
return self.update(conn) | |
else: | |
return self.insert(conn) | |
def update(self, conn): | |
'update this document' | |
if self.pk not in self: | |
raise TypeError('Need a PK to update with') | |
return self.r.update(self).run(conn) | |
def insert(self, conn): | |
'insert this document' | |
response = self.r.insert(self).run(conn) | |
if self._pk not in self: | |
self[self._pk] = response['generated_keys'][0] | |
return response | |
def delete(self, conn): | |
'delete this document' | |
return self.r.get(self[self._pk]).delete().run(conn) | |
def __getattr__(self, attr): | |
return self[attr] | |
def __setattr__(self, attr, value): | |
self[attr] = value | |
@classmethod | |
def convert(cls, cursor_or_obj): | |
return cls(cursor_or_obj) | |
@classmethod | |
def convert_cursor(cls, cursor): | |
for item in cursor: | |
yield cls.convert(item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment