diff --git a/doublethink/orm.py b/doublethink/orm.py index be4452c..d796e09 100644 --- a/doublethink/orm.py +++ b/doublethink/orm.py @@ -175,6 +175,22 @@ class Document(dict, object): ''' rr.table_create(cls.table).run() + @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={}): dict.__setattr__(self, 'rr', rr) self._pk = None diff --git a/tests/test_rethinker.py b/tests/test_rethinker.py index 3ad3487..da3fe24 100644 --- a/tests/test_rethinker.py +++ b/tests/test_rethinker.py @@ -284,6 +284,7 @@ def test_orm(rr): table = 'some_doc' SomeDoc.table_create(rr) + SomeDoc.table_ensure(rr) with pytest.raises(Exception): SomeDoc.table_create(rr) @@ -467,7 +468,7 @@ def test_orm_pk(rr): with pytest.raises(Exception): NonstandardPrimaryKey.load(rr, 'no_such_thing') - NonstandardPrimaryKey.table_create(rr) + NonstandardPrimaryKey.table_ensure(rr) # new empty doc f = NonstandardPrimaryKey(rr, {})