Esempio n. 1
0
def create_indices(client):
    #
    # Create two indexes here. The first index is to query customers when you know specific id's.
    # The second is used to query customers by range. Examples of each type of query are presented
    # below.
    #
    res = client.query([
        q.create_index({
            "name": "customer_by_id",
            "source": q.class_("customers"),
            "unique": True,
            "terms": {"field": ["data", "id"]}
        }),
        q.create_index({
            "name": "customer_id_filter",
            "source": q.class_("customers"),
            "unique": True,
            "values": [{"field": ["data", "id"]}, {"field": ["ref"]}]
        }),
        q.create_index({
            "name": "transaction_uuid_filter",
            "source": q.class_("transactions"),
            "unique": True,
            "values": [{"field": ["data", "id"]}, {"field": ["ref"]}]
        })
    ])
    print('Create \'customer_by_id\', \'customer_id_filter\' and \'transaction_uuid_filter\' indices')
    pprint.pprint(res)
Esempio n. 2
0
 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)
Esempio n. 3
0
def create_customers(client, num_customers, init_balance):
    #
    # Create 'numCustomers' customer records with ids from 1 to 'numCustomers'
    #
    # in this example we use a list of dictionary items to build the 'data'
    # payload for the create function in Fauna
    #
    # THe return is a list of Fauna RefV that can be used to access records
    # directly.
    #
    cust_list = []
    for cust_id in range(1, num_customers + 1):
        customer = {"id": cust_id, "balance": init_balance}
        cust_list.append(customer)

    res = client.query(
        q.map_(
            lambda customer: q.create(q.class_("customers"),
                                {"data": customer}),
            cust_list)
    )
    print('Create {0} customers:'.format(num_customers))

    cust_refs = []
    for cust_ref in res:
        cust_refs.append(cust_ref['ref'])

    return cust_refs
Esempio n. 4
0
    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()
Esempio n. 5
0
def create_customer(client, cust_id, balance):
    #
    # Create a customer (record) using a python dictionary
    #
    customer = {"id": cust_id, "balance": balance}
    res = client.query(
        q.create(q.class_("customers"), {"data": customer})
    )
    print('Create \'customer\' {0}:'.format(cust_id))
    pprint.pprint(res)
Esempio n. 6
0
def create_customer(client, cust_id, balance):
    #
    # Create a customer (record)
    #
    res = client.query(
        q.create(q.class_("customers"),
                 {"data": {
                     "id": cust_id,
                     "balance": balance
                 }}))
    print('Create \'customer\' {0}: {1}'.format(cust_id, res))
def create_customers(client):
    #
    # Create 20 customer records with ids from 1 to 20
    #
    client.query(
        q.map_(
            lambda id: q.create(q.class_("customers"),
                                {"data": {
                                    "id": id,
                                    "balance": 100.0
                                }}), list(range(1, 21))))
    def test_labels_are_created():
        database_client = mock_dependencies.annotation_database(None).client
        database_client.query.assert_has_calls([
            call(
                q.create(q.class_("DocumentLabel"), {'data': {
                    'label': label
                }}))
        ])

        result = handle(event, {}, dependencies=mock_dependencies)
        test_labels_are_created()
        assert json.loads(result) == {'ref': '1234', 'label': label}
def create_schema(client):
    #
    # Create an class to hold customers
    #
    res = client.query(q.create_class({"name": "customers"}))
    print('Create \'customer\' class: {0}'.format(res))

    #
    # Create two indexes here. The first index is to query customers when you know specific id's.
    # The second is used to query customers by range. Examples of each type of query are presented
    # below.
    #
    res = client.query([
        q.create_index({
            "name": "customer_by_id",
            "source": q.class_("customers"),
            "unique": True,
            "terms": {
                "field": ["data", "id"]
            }
        }),
        q.create_index({
            "name":
            "customer_id_filter",
            "source":
            q.class_("customers"),
            "unique":
            True,
            "values": [{
                "field": ["data", "id"]
            }, {
                "field": ["ref"]
            }]
        })
    ])
    print(
        'Create \'customer_by_id\' index & \'customer_id_filter\' index : {0}'.
        format(res))
Esempio n. 10
0
    def delete(self, post_id):
        try:
            post_id = post_id.encode('ascii', 'ignore')
            result = client.query(q.delete(q.ref(q.class_("posts"), post_id)))
        except fauna_error.NotFound as e:
            app.logger.debug(e)
            return Response(
                jsonify('Failed to delete a post - post not found.'),
                status=404,
                mimetype='application/json')
        except Exception as e:
            app.logger.debug(e)
            return Response(jsonify('Failed to delete a post.'),
                            status=500,
                            mimetype='application/json')

        return Response(json.dumps(to_json(result)),
                        status=204,
                        mimetype='application/json')
Esempio n. 11
0
def create_transaction(client, num_customers, max_txn_amount):
    #
    # This method is going to create a random transaction that moves a random amount
    # from a source customer to a destination customer. Prior to committing the transaction
    # a check will be performed to insure that the source customer has a sufficient balance
    # to cover the amount and not go into an overdrawn state.
    #
    uuid = uuid4().urn[9:]

    source_id = randint(1, num_customers)
    dest_id = randint(1, num_customers)
    while dest_id == source_id:
        dest_id = randint(1, num_customers)
    amount = randint(1, max_txn_amount)

    transaction = {"uuid": uuid, "sourceCust": source_id, "destCust": dest_id , "amount": amount}

    res = client.query(
        q.let(
            {"source_customer": q.get(q.match(q.index("customer_by_id"), source_id)),
             "dest_customer": q.get(q.match(q.index("customer_by_id"), dest_id))},
            q.let(
                {"source_balance": q.select(["data", "balance"], q.var("source_customer")),
                 "dest_balance": q.select(["data", "balance"], q.var("dest_customer"))},
                q.let(
                    {"new_source_balance": q.subtract(q.var("source_balance"), amount),
                     "new_dest_balance": q.add(q.var("dest_balance"), amount)},
                    q.if_(
                        q.gte(q.var("new_source_balance"), 0),
                        q.do(
                            q.create(q.class_("transactions"), {"data": transaction}),
                            q.update(q.select("ref", q.var("source_customer")),
                                     {"data": {"txnID": uuid, "balance": q.var("new_source_balance")}}),
                            q.update(q.select("ref", q.var("dest_customer")),
                                     {"data": {"txnID": uuid, "balance": q.var("new_dest_balance")}})
                        ),
                        "Error. Insufficient funds."
                    )
                )
            )
        )
    )
Esempio n. 12
0
def create_schema(client):
    #
    # Create an class to hold customers
    #
    res = client.query(q.create_class({"name": "customers"}))
    print('Create \'customer\' class: {0}'.format(res))

    #
    # Create an index to access customer records by id
    #
    res = client.query(
        q.create_index({
            "name": "customer_by_id",
            "source": q.class_("customers"),
            "unique": True,
            "terms": {
                "field": ["data", "id"]
            }
        }))
    print('Create \'customer_by_id\' index: {0}'.format(res))
Esempio n. 13
0
 def _create(self, instance: T) -> T:
     result = self.client.query(
         q.create(q.class_(instance.name()), {'data': instance.as_query()}))
     ref = result['ref']
     return instance.clone(ref=ref)
Esempio n. 14
0
 def _get(self, cls: Type[T], ref: str) -> T:
     result = self.client.query(q.get(q.ref(q.class_(cls.name()), ref)))
     return _initialize_from_result(cls, result)