Пример #1
0
    def test_multi_value(self):
        cb = self.cb
        key = self.gen_key('sdArray')

        cb.upsert(key, {'array': []})
        cb.mutate_in(key, SD.array_append('array', True))
        self.assertEqual([True], cb.retrieve_in(key, 'array')[0])

        cb.mutate_in(key, SD.array_append('array', 1, 2, 3))
        self.assertEqual([True, 1, 2, 3], cb.retrieve_in(key, 'array')[0])

        cb.mutate_in(key, SD.array_prepend('array', [42]))
        self.assertEqual([[42], True, 1, 2, 3], cb.retrieve_in(key, 'array')[0])
Пример #2
0
    def test_multi_value(self):
        cb = self.cb
        key = self.gen_key('sdArray')

        cb.upsert(key, {'array': []})
        cb.mutate_in(key, SD.array_append('array', True))
        self.assertEqual([True], cb.retrieve_in(key, 'array')[0])

        cb.mutate_in(key, SD.array_append('array', 1, 2, 3))
        self.assertEqual([True, 1, 2, 3], cb.retrieve_in(key, 'array')[0])

        cb.mutate_in(key, SD.array_prepend('array', [42]))
        self.assertEqual([[42], True, 1, 2, 3],
                         cb.retrieve_in(key, 'array')[0])
Пример #3
0
 def test_eventing_processes_mutations_when_mutated_through_subdoc_api_and_set_expiry_through_sdk(self):
     # set expiry pager interval
     ClusterOperationHelper.flushctl_set(self.master, "exp_pager_stime", 1, bucket=self.src_bucket_name)
     url = 'couchbase://{ip}/{name}'.format(ip=self.master.ip, name=self.src_bucket_name)
     bucket = Bucket(url, username="******", password="******")
     for docid in ['customer123', 'customer1234', 'customer12345']:
         bucket.insert(docid, {'some': 'value'})
     body = self.create_save_function_body(self.function_name, self.handler_code,
                                           dcp_stream_boundary="from_now")
     # deploy eventing function
     self.deploy_function(body)
     # upserting a new sub-document
     bucket.mutate_in('customer123', SD.upsert('fax', '775-867-5309'))
     # inserting a sub-document
     bucket.mutate_in('customer1234', SD.insert('purchases.complete', [42, True, None], create_parents=True))
     # Creating and populating an array document
     bucket.mutate_in('customer12345', SD.array_append('purchases.complete', ['Hello'], create_parents=True))
     self.verify_eventing_results(self.function_name, 3, skip_stats_validation=True)
     for docid in ['customer123', 'customer1234', 'customer12345']:
         # set expiry on all the docs created using sub doc API
         bucket.touch(docid, ttl=5)
     self.sleep(10, "wait for expiry of the documents")
     # Wait for eventing to catch up with all the expiry mutations and verify results
     self.verify_eventing_results(self.function_name, 0, skip_stats_validation=True)
     self.undeploy_and_delete_function(body)
Пример #4
0
 def test_eventing_processes_mutations_when_mutated_through_subdoc_api_and_set_expiry_through_sdk(self):
     # set expiry pager interval
     ClusterOperationHelper.flushctl_set(self.master, "exp_pager_stime", 1, bucket=self.src_bucket_name)
     url = 'couchbase://{ip}/{name}'.format(ip=self.master.ip, name=self.src_bucket_name)
     bucket = Bucket(url, username="******", password="******")
     for docid in ['customer123', 'customer1234', 'customer12345']:
         bucket.insert(docid, {'some': 'value'})
     body = self.create_save_function_body(self.function_name, self.handler_code,
                                           dcp_stream_boundary="from_now")
     # deploy eventing function
     self.deploy_function(body)
     # upserting a new sub-document
     bucket.mutate_in('customer123', SD.upsert('fax', '775-867-5309'))
     # inserting a sub-document
     bucket.mutate_in('customer1234', SD.insert('purchases.complete', [42, True, None], create_parents=True))
     # Creating and populating an array document
     bucket.mutate_in('customer12345', SD.array_append('purchases.complete', ['Hello'], create_parents=True))
     self.verify_eventing_results(self.function_name, 3, skip_stats_validation=True)
     for docid in ['customer123', 'customer1234', 'customer12345']:
         # set expiry on all the docs created using sub doc API
         bucket.touch(docid, ttl=5)
     self.sleep(10, "wait for expiry of the documents")
     # Wait for eventing to catch up with all the expiry mutations and verify results
     self.verify_eventing_results(self.function_name, 0, skip_stats_validation=True)
     self.undeploy_and_delete_function(body)
Пример #5
0
 def array_add_last(self, client, key = '', path = '', value = None, xattr=None, create_parents=None):
     try:
         new_path = self.generate_path(self.nesting_level, path)
         if self.is_sdk_client:
             client.mutate_in(key, SD.array_append(new_path, value, xattr=xattr, create_parents=create_parents))
         else:
             client.array_push_last_sd(key, new_path, json.dumps(value))
     except Exception as e:
         self.log.error(e)
         self.fail("Unable to add key {0} for path {1} after {2} tries".format(key, path, 1))
 def array_add_last(self, client, key = '', path = '', value = None):
     try:
         if self.verbose_func_usage:
             self.log.info(" array_add_last ----> {0} :: {1}".format(path, value))
         if self.use_sdk_client:
             client.mutate_in(key, SD.array_append(path, value, xattr=self.xattr))
         else:
             client.array_push_last_sd(key, path, value)
     except Exception:
         raise
 def array_add_last(self, client, key='', path='', value=None):
     try:
         if self.verbose_func_usage:
             self.log.info(" array_add_last ----> {0} :: {1}".format(path, value))
         if self.use_sdk_client:
             client.mutate_in(key, SD.array_append(path, value, xattr=self.xattr))
         else:
             client.array_push_last_sd(key, path, value)
     except Exception:
         raise
Пример #8
0
 def array_add_last(self, client, key = '', path = '', value = None, xattr=None, create_parents=None):
     try:
         new_path = self.generate_path(self.nesting_level, path)
         if self.is_sdk_client:
             client.mutate_in(key, SD.array_append(new_path, value, xattr=xattr, create_parents=create_parents))
         else:
             client.array_push_last_sd(key, new_path, json.dumps(value))
     except Exception as e:
         self.log.error(e)
         self.fail("Unable to add key {0} for path {1} after {2} tries".format(key, path, 1))
Пример #9
0
    def userflights(self, username):
        """List the flights that have been reserved by a user"""
        if request.method == 'GET':
            token = jwt.encode({'user': username}, 'cbtravelsample')
            bearer = request.headers['Authentication'].split(" ")[1]
            if token != bearer:
                return abortmsg(401, 'Username does not match token username')

            try:
                userdockey = make_user_key(username)
                subdoc = db.retrieve_in(userdockey, 'flights')
                flights = subdoc.get('flights', [])
                respjson = jsonify({'data': flights[1]})
                response = make_response(respjson)
                return response
            except NotFoundError:
                return abortmsg(500, "User does not exist")

        elif request.method == 'POST':
            userdockey = make_user_key(username)

            token = jwt.encode({'user': username}, 'cbtravelsample')
            bearer = request.headers['Authentication'].split(" ")[1]

            if token != bearer:
                return abortmsg(401, 'Username does not match token username')

            newflights = request.get_json()['flights'][0]

            try:
                db.mutate_in(
                    userdockey,
                    SD.array_append('flights', newflights,
                                    create_parents=True))
                resjson = {
                    'data': {
                        'added': newflights
                    },
                    'context': 'Update document ' + userdockey
                }
                return make_response(jsonify(resjson))
            except NotFoundError:
                return abortmsg(500, "User does not exist")
            except CouchbaseDataError:
                abortmsg(409, "Couldn't update flights")
Пример #10
0
 def run(self, *args, **kw):
     cb = SDKClient(scheme="couchbase", hosts=[SERVER_IP],
       bucket='default').cb
     for x in range(ITERATIONS):
         cb.mutate_in(DOCID, SD.array_append('recs', 1))
 def run(self, *args, **kw):
     cb = SDK_Bucket(CONNSTR)
     for x in range(ITERATIONS):
         cb.mutate_in(DOCID, SD.array_append('recs', 1))
 def run(self, *args, **kw):
     cb = SDK_Bucket(CONNSTR)
     for x in range(ITERATIONS):
         cb.mutate_in(DOCID, SD.array_append('recs', 1))
Пример #13
0
 def run(self, *args, **kw):
     cb = SDKClient(scheme="couchbase", hosts=[SERVER_IP],
       bucket='default').cb
     for x in range(ITERATIONS):
         cb.mutate_in(DOCID, SD.array_append('recs', 1))
Пример #14
0
    print("Path exists, cannot use insert.")
# end::mutate_in_insert[]

# tag::combine_dict[]
collection.mutate_in(
    "customer123",
    (SD.remove("addresses.billing"),
     SD.replace(
        "email",
        "*****@*****.**")))
# end::combine_dict[]

# NOTE:  the mutate_in() operation expects a tuple or list
# tag::array_append[]
collection.mutate_in(
    "customer123", (SD.array_append(
                    "purchases.complete", 777),))

# purchases.complete is now [339, 976, 442, 666, 777]
# end::array_append[]

# tag::array_prepend[]
collection.mutate_in(
    "customer123", [
        SD.array_prepend(
            "purchases.abandoned", 18)])

# purchases.abandoned is now [18, 157, 42, 999]
# end::array_prepend[]

# tag::create_array[]
collection.upsert("my_array", [])
Пример #15
0
from couchbase.bucket import Bucket
import couchbase.exceptions as E
import couchbase.subdocument as SD

cb = Bucket('couchbase://localhost/default')

cb.upsert('docid', {
    'name': 'Mark',
    'email': '*****@*****.**',
    'array': [1, 2, 3, 4]
})

cb.mutate_in('docid',
             # Add 42 as a new element to 'array'
             SD.array_append('array', '42'),
             # Increment the numeric value of the first element by 99
             SD.counter('array[0]', 99),
             # Add a new 'description' field
             SD.upsert('description', 'just a dev'))

print('Document is now:', cb.get('docid').value)

try:
    cb.mutate_in('docid', SD.upsert('deep.nested.path', 'some-value'))
except E.SubdocPathNotFoundError as e:
    print('Caught exception', e)

# Use `create`
cb.mutate_in('docid', SD.upsert(
    'deep.nested.path', 'some-value', create_parents=True))
Пример #16
0
#end::combine_dict[]
"""----

NOTE: `mutateIn` is an _atomic_ operation.
    If any single `ops` fails, then the entire document is left unchanged.

                                                                == Array append and prepend

The _subdoc-array-prepend_ and _subdoc-array-append_ operations are true array prepend and append operations.
    Unlike fulldoc _append_/_prepend_ operations (which simply concatenate bytes to the existing value), _subdoc-array-append_ and _subdoc-array-prepend_ are JSON-aware:

[source,csharp]
----
"""
#tag::arrayappend[]
collection.mutate_in("customer123", SD.array_append("purchases.complete", 777))

# purchases.complete is now [339, 976, 442, 666, 777]
#end::arrayappend[]
"""
----

[source,csharp]
----
"""
#tag::arrayprepend[]
collection.mutate_in("customer123",
                     [SD.array_prepend("purchases.abandoned", 18)])

# purchases.abandoned is now [18, 157, 49, 999]
#end::arrayprepend[]