I wrote a little script to create DB and some tables inside a RethinkDB if database don't exist.
I'm using the Python shell to communicate with RethinkDB
import rethinkdb as r
r.connect('localhost', 28015).repl()
r.db_list().contains('atlas').do(lambda databaseExists:
r.branch(
databaseExists,
{ 'dbs_created': 0 },
r.db_create('atlas'),
r.db('atlas').table_create('Carts'),
r.db('atlas').table_create('Checkouts'),
r.db('atlas').table_create('Collections'),
r.db('atlas').table_create('Contents'),
r.db('atlas').table_create('Orders'),
r.db('atlas').table_create('Products'),
r.db('atlas').table_create('Users'),
r.db('atlas').table('Users').filter({'email': '{[email protected]}'}).update({'status': 'active', 'scope': ['admin']})
)
).run()
exit()
This work well and create database if not exist but it create only the first table Carts
and skip the next request.
I tried with this instead
r.expr(['Carts', 'Checkouts', 'Collections', 'Contents', 'Orders', 'Products', 'Users']).do(lambda tables:
for table in tables:
r.db('atlas').table_create(table)
),
But I get an invalid syntax error
File "<stdin>", line 10
r.expr(['Carts', 'Checkouts', 'Collections', 'Contents', 'Orders', 'Products', 'Users']).do(for table in tables:
^
SyntaxError: invalid syntax
How can I create all this tables once instead only the first table ?
In your first query, you pass 11 arguments to branch
. The behaviour of
r.branch(A, B, C, D, E, F, G)
it behaves like
if A:
return B
elif C:
return D
elif E:
return F
else:
return G
In your second query, you use for ... in ...
. This Python construct is not legal as the body of a lambda. It also does not work inside ReQL queries.
A useful way of combining write operations in a single RethinkDB query is to use for_each
. Here is an example:
r.branch(
r.db_list().contains('atlas'),
{ 'dbs_created': 0 },
r.expr([
r.db_create('atlas'),
r.db('atlas').table_create('Carts'),
r.db('atlas').table_create('Checkouts')
]).for_each(x => x))