def test_nested_keys(self): client = self.create_new_database(self.admin_client, "db-for-keys") client.query(query.create_database({"name": "db-test"})) server_key = client.query( query.create_key({ "database": query.database("db-test"), "role": "server" })) admin_key = client.query( query.create_key({ "database": query.database("db-test"), "role": "admin" })) self.assertEqual( client.query(query.paginate(query.keys()))["data"], [server_key["ref"], admin_key["ref"]]) self.assertEqual( self.admin_client.query( query.paginate(query.keys( query.database("db-for-keys"))))["data"], [server_key["ref"], admin_key["ref"]])
def main(argv): # # Create an admin client. This is the client we will use to create the database. # scheme = "http" domain = "127.0.0.1" port = "8443" secret = "secret" adminClient = FaunaClient(secret=secret, domain=domain, scheme=scheme, port=port) # # If you are using the the FaunaDB-Cloud use these lines to create the connection. # Change the secret to your value and comment out the lines above # # secret = "Your Secret Goes here" # adminClient = FaunaClient(secret=secret) dbName = "TestDB" # # Call to Create the database # res = adminClient.query(q.create_database({"name": dbName})) print('DB {0} created: {1}'.format(dbName, res)) # # Call to check to see if database exists and to delete it id it does. # res = adminClient.query( q.if_(q.exists(q.database(dbName)), q.delete(q.database(dbName)), True)) print('DB {0} deleted: {1}'.format(dbName, res))
def test_move_database(self): q = query.move_database(query.database("src-db"), query.database("dest-db")) self.assertJson( q, '{"move_database":{"database":"src-db"},"to":{"database":"dest-db"}}' )
def create_database(scheme, domain, port, secret, db_name): # # Create an admin client. This is the client we will use to create the database. # # If you are using the the FaunaDB-Cloud you will need to replace the value of the # 'secret' in the command below with your "secret". # adminClient = FaunaClient(secret=secret, domain=domain, scheme=scheme, port=port) print("Connected to FaunaDB as admin!") # # The code below creates the Database that will be used for this example. Please note that # the existence of the database is evaluated, deleted if it exists and recreated with a single # call to the Fauna DB. # res = adminClient.query( q.if_( q.exists(q.database(db_name)), [q.delete(q.database(db_name)), q.create_database({"name": db_name})], q.create_database({"name": db_name})) ) print('DB {0} created:'.format(db_name)) pprint.pprint(res) # # Create a key specific to the database we just created. We will use this to # create a new client we will use in the remainder of the examples. # res = adminClient.query(q.select(["secret"], q.create_key({"database": q.database(db_name), "role": "server"}))) print('DB {0} secret: {1}'.format(db_name, res)) return res
def test_move_database(self): self.admin_client.query(query.create_database({"name": "mvdb_src"})) self.admin_client.query(query.create_database({"name": "mvdb_dst"})) self.admin_client.query(query.move_database(query.database("mvdb_src"), query.database("mvdb_dst"))) self.assertEqual(self.admin_client.query( query.exists(query.database("mvdb_src"))), False) self.assertEqual(self.admin_client.query(query.exists(query.database("mvdb_src", query.database("mvdb_dst")))), True)
def test_create_database(self): self.admin_client.query( query.create_database({"name": "database_for_test"})) self.assertTrue( self.admin_client.query( query.exists(query.database("database_for_test"))))
def create_database(self, name: str, database: Type['FaunaDatabase'], key_type: str) -> Secret: self.client.query(q.create_database({'name': name})) key = self.client.query( q.create_key({ 'database': q.database(name), 'role': key_type })) secret = Secret(key['secret']) database_instance = database(secret, self.client_factory) for class_ in database.classes(): log.info(f'creating class {class_}') database_instance._create_class(class_) for name, index in database.indices().items(): log.info(f'creating index {name}') database_instance.client.query( q.create_index({ 'name': name, 'source': q.class_(index.source.name()), 'terms': [{ 'field': ['data', field] } for field in index.fields], 'values': [{ 'field': ["data", value] } for value in index.values] + [{ 'field': ['ref'] }], 'unique': index.unique })) return Secret(secret)
async def asyncSetUp(self): # Turn off annoying logging about reset connections. getLogger("requests").setLevel(WARNING) self.root_client = self._get_client() rnd = ''.join(random.choice(string.ascii_lowercase) for _ in range(10)) self.db_name = "faunadb-python-test" + rnd self.db_ref = query.database(self.db_name) exists = await self.root_client.query(query.exists(self.db_ref)) if exists: await self.root_client.query(query.delete(self.db_ref)) await self.root_client.query( query.create_database({"name": self.db_name})) res = await self.root_client.query( query.create_key({ "database": self.db_ref, "role": "server" })) self.server_key = res["secret"] self.client = self.root_client.new_session_client( secret=self.server_key) res = await self.root_client.query( query.create_key({ "database": self.db_ref, "role": "admin" })) self.admin_key = res["secret"] self.admin_client = self.root_client.new_session_client( secret=self.admin_key)
def setUpClass(cls): super(FaunaTestCase, cls).setUpClass() # Turn off annoying logging about reset connections. getLogger("requests").setLevel(WARNING) cls.root_client = cls._get_client() rnd = ''.join(random.choice(string.ascii_lowercase) for _ in range(10)) cls.db_name = "faunadb-python-test" + rnd cls.db_ref = query.database(cls.db_name) if cls.root_client.query(query.exists(cls.db_ref)): cls.root_client.query(query.delete(cls.db_ref)) cls.root_client.query(query.create_database({"name": cls.db_name})) cls.server_key = cls.root_client.query( query.create_key({ "database": cls.db_ref, "role": "server" }))["secret"] cls.client = cls.root_client.new_session_client(secret=cls.server_key) cls.admin_key = cls.root_client.query( query.create_key({ "database": cls.db_ref, "role": "admin" }))["secret"] cls.admin_client = cls.root_client.new_session_client( secret=cls.admin_key)
def create_new_database(self, client, name): client.query(query.create_database({"name": name})) key = client.query( query.create_key({ "database": query.database(name), "role": "admin" })) return client.new_session_client(secret=key["secret"])
def test_create_key(self): self.assertJson( query.create_key({ "database": query.database("db-name"), "role": "client" }), '{"create_key":{"object":{"database":{"database":"db-name"},"role":"client"}}}' )
def fauna_delete_database(self, **kwargs: str) -> Tuple[bool, Any, str]: """Fauna delete database.""" client = self.get_fauna_connection() database: str = kwargs["database"] try: return client.query(q.delete(q.database(database))) except (BadRequest) as _error: # pragma: no cover raise ValueError("Fauna error.") from _error
def test_nested_references(self): client1 = self.create_new_database(self.admin_client, "parent-database") client2 = self.create_new_database(client1, "child-database") client2.query(query.create_collection({"name": "a_collection"})) client2.query( query.create_role({ "name": "a_role", "privileges": { "resource": query.collections(), "actions": { "read": True } } })) nested_database_ref = query.database("child-database", query.database("parent-database")) nested_collection_ref = query.collection("a_collection", nested_database_ref) nested_role_ref = query.role("a_role", nested_database_ref) self.assertEqual( self.admin_client.query(query.exists(nested_collection_ref)), True) self.assertEqual( self.admin_client.query(query.exists(nested_role_ref)), True) parent_db_ref = Ref("parent-database", Native.DATABASES) child_db_ref = Ref("child-database", Native.DATABASES, parent_db_ref) self.assertEqual( self.admin_client.query( query.paginate( query.collections(nested_database_ref)))["data"], [Ref("a_collection", Native.COLLECTIONS, child_db_ref)]) self.assertEqual( self.admin_client.query( query.paginate(query.roles(nested_database_ref)))["data"], [Ref("a_role", Native.ROLES, child_db_ref)])
def test_create_key(self): self.admin_client.query(query.create_database({"name": "database_for_key_test"})) resource = self.admin_client.query(query.create_key({ "database": query.database("database_for_key_test"), "role": "server"})) new_client = self.admin_client.new_session_client(secret=resource["secret"]) new_client.query(query.create_collection({"name": "collection_for_test"})) self.assertTrue(new_client.query(query.exists(query.collection("collection_for_test"))))
def test_nested_keys(self): client = self.create_new_database(self.admin_client, "db-for-keys") client.query(query.create_database({"name": "db-test"})) server_key = client.query(query.create_key({ "database": query.database("db-test"), "role": "server" })) admin_key = client.query(query.create_key({ "database": query.database("db-test"), "role": "admin" })) server_key_ref = Ref(server_key["ref"].id(), cls=Ref("keys", db=Ref("db-for-keys", cls=Native.DATABASES))) admin_key_ref = Ref(admin_key["ref"].id(), cls=Ref( "keys", db=Ref("db-for-keys", cls=Native.DATABASES))) self.assertEqual( self.admin_client.query(query.paginate(query.keys(query.database("db-for-keys"))))["data"], [server_key_ref, admin_key_ref] )
def test_queries_are_made(): # The client mock is used by both the # database and annotation database # so here we assert calls for both # could maybe be improved by changing the way databases are created? create_annotation_database_queries = [ q.create_database({'name': '1234-annotations'}), q.create_key( {'database': q.database('1234-annotations'), 'role': 'server'} ) ] mock_dependencies.database.client.query.assert_has_calls( [call(query) for query in create_annotation_database_queries] ) setup_annotation_database_queries = [ q.create_class({'name': 'SpanLabel'}), q.create_class({'name': 'DocumentLabel'}), q.create_class({'name': 'RelationLabel'}), q.create_class({'name': 'Relation'}), q.create_class({'name': 'Span'}), q.create_class({'name': 'Document'}), q.create_index( {'name': 'documents', 'source': q.class_('Document')}), q.create_index( {'name': 'span_labels', 'source': q.class_('SpanLabel')} ), q.create_index( {'name': 'relation_labels', 'source': q.class_('RelationLabel')} ), q.create_index( {'name': 'document_labels', 'source': q.class_('DocumentLabel')} ) ] mock_dependencies.database.client.query.assert_has_calls( [call(query) for query in setup_annotation_database_queries] ) event = event_reader('post_confirmation_event.json') handle(event, {}, dependencies=mock_dependencies) assert event == event test_buckets_are_created() test_queries_are_made() test_user_attributes_are_updated()
def __init__(self, database="Balthus", collection="domains"): self.database = database self.collection = collection FAUNA_SECRET = os.getenv("FAUNA_SECRET") self.client = FaunaClient(secret=FAUNA_SECRET) try: self.client.query(q.create_database({"name": database})) except: print("Database: {} already exist".format(database)) ref = self.client.query( q.create_key({ "database": q.database(database), "role": "server" })) self.client = FaunaClient(secret=ref['secret']) try: self.client.query(q.create_collection({"name": collection})) except: print("Collection: {} already exist".format(collection))
def __init__(self, collection_name: str, model): """ Each CRUD requires that: - Fauna client is connected to db - collection_name is created / exists - Collection is created / exists """ self.collection_name = collection_name self.model = model self.client = FaunaClient(secret=settings.FAUNADB_SECRET) if not self.client.query( query.exists(query.database( db_name=settings.FAUNADB_DBNAME, ))): self.database = self.client.query( query.create_database(db_params={ 'name': settings.FAUNADB_DBNAME, }), ) if not self.client.query( query.exists( query.collection(collection_name=collection_name, ))): self.collection = self.client.query( query.create_collection(collection_params={ 'name': collection_name, }), )
def test_access_provider(self): self.assertJson( query.access_provider("name", query.database("db1")), '{"access_provider":"name","scope":{"database":"db1"}}') self.assertJson(query.access_provider("name"), '{"access_provider":"name"}')
def test_database(self): self.assertJson(query.database("db-name"), '{"database":"db-name"}')
def test_database(self): self.assertEqual(self._q(query.database("db-name")), Ref("db-name", Native.DATABASES))
def delete_database(stack_name): client = FaunaClient(secret=os.environ['FAUNADB_SECRET']) client.query(q.delete(q.database(stack_name)))
from faunadb.client import FaunaClient client = FaunaClient(secret="secret", domain="localhost", scheme="http", port="8443") # create db client.query(q.create_database({"name": "my_app"})) # Accessing the database # Create an initial server key by using an admin key. The server key has unrestricted access to a single database; # in this case, the server key will only access the blog post database we just created. client.query(q.create_key({ "database": q.database("my_app"), "role": "server" })) # Set up a collection # Create a collection using the CreateCollection function with a param_object containing the name of the collection. # We shall name our collection "posts": client.query(q.create_collection({"name": "posts"})) # Create an index # The customary way to access documents within a collection is by specifying a criteria for one of the fields. # To enable criteria-based searches, we need to first create an index using the path of the field within the document. client.query( q.create_index({ "name": "posts_by_title",
def test_typecheckfns(self): coll = query.collection("typecheck_coll") db = query.database("typecheck_db") fn = query.function("typecheck_fn") index = query.index("typecheck_index") self.admin_client.query(query.create_collection({"name": "typecheck_coll"})) self.admin_client.query(query.create_index( {"name": "typecheck_index", "source": coll, "active": True})) doc = self.admin_client.query(query.create( coll, {"data": {}, "credentials": {"password": "******"}})) self.admin_client.query(query.create_database({"name": "typecheck_db"})) function = self._q(query.create_function( {"name": "typecheck_fn", "body": query.query(query.lambda_("x", query.now()))})) key = self.admin_client.query( query.create_key({"database": db, "role": "admin"})) token = self._q(query.login(doc["ref"], {"password": "******"})) credentials = self._q(query.select(['data', 0], query.paginate(query.credentials()))) role = self.admin_client.query(query.create_role( {"name": "typecheck_role", "membership": [], "privileges": []})) values = [ None, bytearray([12,3,4,5]), credentials, 90, 3.14, True, query.to_date(query.now()), query.date("1970-01-01"), query.now(), query.epoch(1, "second"), query.time("1970-01-01T00:00:00Z"), {"x": 10}, query.get(doc["ref"]), query.paginate(query.collections()), [1, 2, 3], "a string", coll, query.collections(), query.match(index), query.union(query.match(index)), doc["ref"], query.get(doc["ref"]), index, db, coll, token["ref"], role["ref"], key["ref"], function["ref"], query.get(function["ref"]), query.query(query.lambda_("x", query.var("x"))), ] pairs = [ ["array", query.is_array], ["object", query.is_object], ["string", query.is_string], ["null", query.is_null], ["number", query.is_number], ["bytes", query.is_bytes], ["date", query.is_date], ["timestamp", query.is_timestamp], ["set", query.is_set], ["ref", query.is_ref], ["boolean", query.is_boolean], ["double", query.is_double], ["integer", query.is_integer], ["database", query.is_database], ["index", query.is_index], ["collection", query.is_collection], ["token", query.is_token], ["function", query.is_function], ["collection", query.is_collection], ["role", query.is_role], ["credentials", query.is_credentials], ["key", query.is_key], ] expected = { "array": 1, "boolean": 1, "bytes": 1, "collection": 3, "credentials": 1, "database": 1, "date": 2, "double": 1, "function": 2, "integer": 1, "index": 1, "key": 1, "null": 1, "number": 2, "object": 5, "ref": 11, "role": 1, "set": 3, "string": 1, "timestamp": 3, "token": 1, } q = [] for p in pairs: d = dict() d[p[0]] = query.count(query.filter_(query.lambda_("v", p[1](query.var("v"))), query.var("vals"))) q.append(d) actual = self._q(query.let({"vals": values}, query.merge({}, q))) self.assertEqual(actual, expected)
from faunadb import query as q client = FaunaClient(secret=os.environ['FAUNADB_SECRET']) # CRUD examples ## Databases ### Create a database client.query(q.create_database({"name": "annuvin"})) ### Paginate all databases client.query(q.paginate(q.databases())) ### Get a database client.query(q.get(q.database("annuvin"))) ### Rename a database client.query(q.update(q.database("annuvin"), {"name": "llyr"})) ### Annotate a database client.query(q.update(q.database("llyr"), {"data": {"env": "test"}})) ### Delete a database client.query(q.delete(q.database("llyr"))) ## Keys client.query(q.create_database({"name": "caledonia"})) ### Create a key ref = client.query(
def test_access_providers(self): self.assertJson(query.access_providers(query.database("db1")), '{"access_providers":{"database":"db1"}}')