181 lines
5.8 KiB
Python
Raw Permalink Normal View History

2017-02-21 16:27:49 -08:00
'''
doublethink/orm.py - rethinkdb ORM
2017-02-21 16:27:49 -08:00
2023-05-18 17:16:04 -07:00
Copyright (C) 2017-2023 Internet Archive
2017-02-21 16:27:49 -08:00
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
2023-05-18 17:16:04 -07:00
import rethinkdb as rdb
2017-02-21 16:27:49 -08:00
import logging
import doublethink
2017-02-21 16:27:49 -08:00
2023-05-18 17:16:04 -07:00
r = rdb.RethinkDB()
2017-02-23 16:07:14 -08:00
class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return self.fget(owner_cls)
class Document(dict):
2017-02-21 16:27:49 -08:00
'''
Base class for ORM.
2017-02-21 16:27:49 -08:00
You should subclass this class for each of your rethinkdb tables. You can
add custom functionality in your subclass if appropriate.
2017-02-21 16:27:49 -08:00
Call save() to persist changes to the model.
This class subclasses dict. Thus attributes can be accessed with
`doc['foo']` or `doc.get('foo')`, depending on what you want to happen if
the attribute is missing. In addition, this class overrides `__getattr__`
to point to `dict.get`, so that first level attributes can be accessed as
if they were member variables, e.g. `doc.foo`. If there is no attribute
foo, `doc.foo` returns None. (XXX is this definitely what we want?)
The default table name is the class name, lowercased. Subclasses can
specify different table name like so:
class Something(doublethink.Document):
table = 'my_table_name'
2017-02-21 16:27:49 -08:00
'''
2017-02-23 16:07:14 -08:00
@classproperty
def table(cls):
return cls.__name__.lower()
@classmethod
def load(cls, rr, pk):
2017-02-23 16:07:14 -08:00
'''
Retrieves a document from the database, by primary key.
2017-02-23 16:07:14 -08:00
'''
if pk is None:
return None
d = rr.table(cls.table).get(pk).run()
if d is None:
return None
doc = cls(rr, d)
2017-02-23 16:07:14 -08:00
return doc
@classmethod
def table_create(cls, rr):
2017-02-23 16:07:14 -08:00
'''
Creates the table. Subclasses may want to override this method to do
more things, such as creating secondary indexes.
2017-02-23 16:07:14 -08:00
'''
rr.table_create(cls.table).run()
2017-02-23 16:07:14 -08:00
2017-03-01 11:40:12 -08:00
@classmethod
def table_ensure(cls, rr):
'''
Creates the table if it doesn't exist.
'''
dbs = rr.db_list().run()
if not rr.dbname in dbs:
logging.info('creating rethinkdb database %s', repr(rr.dbname))
rr.db_create(rr.dbname).run()
tables = rr.table_list().run()
if not cls.table in tables:
logging.info(
'creating rethinkdb table %s in database %s',
repr(cls.table), repr(rr.dbname))
cls.table_create(rr)
def __init__(self, rr, d={}):
'''
Sets initial values from `d`, then calls `self.populate_defaults()`.
Args:
rr (doublethink.Rethinker): rethinker
d (dict): initial value
If you want to create a new document, and set the primary key yourself,
do not call `doc = MyDocument(rr, d={'id': 'my_id', ...})`. The
assumption is that if the primary key is set in the constructor, the
document already exists in the database. Thus a call to `doc.save()`
may not save anything. Do this instead:
doc = MyDocument(rr, d={'id': 'my_id', ...})
doc.id = 'my_id'
# ...whatever else...
doc.save()
'''
dict.__setattr__(self, 'rr', rr)
self._pk = None
self.update(d or {})
self.populate_defaults()
2017-02-21 16:27:49 -08:00
def __setitem__(self, key, value):
# keys starting with underscore are not part of the document
if key[:1] == '_':
dict.__setattr__(self, key, value)
else:
dict.__setitem__(self, key, value)
2017-02-21 16:27:49 -08:00
__setattr__ = __setitem__
__getattr__ = dict.get
2017-02-21 16:27:49 -08:00
@property
2017-02-23 16:07:14 -08:00
def pk_field(self):
2017-02-21 16:27:49 -08:00
'''
2017-02-23 16:07:14 -08:00
Name of the primary key field as retrieved from rethinkdb table
metadata, 'id' by default. Should not be overridden. Override
`table_create` if you want to use a nonstandard field as the primary
key.
2017-02-21 16:27:49 -08:00
'''
2017-02-23 16:07:14 -08:00
if not self._pk:
try:
pk = self.rr.db('rethinkdb').table('table_config').filter({
'db': self.rr.dbname, 'name': self.table}).get_field(
2017-02-23 16:07:14 -08:00
'primary_key')[0].run()
self._pk = pk
2017-02-23 16:07:14 -08:00
except Exception as e:
raise Exception(
'problem determining primary key for table %s.%s: %s',
self.rr.dbname, self.table, e)
2017-02-23 16:07:14 -08:00
return self._pk
2017-02-21 16:27:49 -08:00
2017-02-23 16:07:14 -08:00
@property
def pk_value(self):
2017-02-21 16:27:49 -08:00
'''
2017-02-23 16:07:14 -08:00
Value of primary key field.
2017-02-21 16:27:49 -08:00
'''
2017-02-23 16:07:14 -08:00
return getattr(self, self.pk_field)
2017-02-21 16:27:49 -08:00
def populate_defaults(self):
'''
This method is called by `__init__()`. Subclasses should override it to
populate default values if appropriate.
'''
pass
2017-02-23 16:07:14 -08:00
def save(self):
'''Persist changes to rethinkdb.'''
query = self.rr.table(self.table).insert(self, conflict='replace')
result = query.run()
if sorted([result['inserted'], result['replaced'], result['unchanged']]) != [0,0,1]:
raise Exception(
'unexpected result %s from rethinkdb query %s' % (
result, query))
if 'generated_keys' in result:
self[self.pk_field] = result['generated_keys'][0]
2017-02-21 16:27:49 -08:00
def refresh(self):
'''
Refresh the document from the database.
2017-02-21 16:27:49 -08:00
'''
d = self.rr.table(self.table).get(self.pk_value).run()
self.clear()
self.update(d)
2017-02-21 16:27:49 -08:00