The UnQLite object provides a pythonic interface for interacting with UnQLite databases. UnQLite is a lightweight, embedded NoSQL database and JSON document store.
Parameters: |
|
---|
Note
UnQLite supports in-memory databases, which can be created by passing in ':mem:' as the database file. This is the default behavior if no database file is specified.
Parameters: | flags – Optional flags to use when opening the database. |
---|---|
Raises : | Exception if an error occurred opening the database. |
Open the database connection. This method should only be called if the database was manually closed, or if the database was instantiated with open_manually=True.
Valid flags:
Detailed descriptions of these flags can be found in the unqlite_open docs.
Raises : | Exception if an error occurred closing the database. |
---|
Close the database connection.
Parameters: |
|
---|
Configure an attribute of the UnQLite database. The list of verbs and their parameters can be found in the unqlite_config docs.
Store a value in the given key.
Parameters: |
|
---|
Example:
db = UnQLite()
db.store('some key', 'some value')
db.store('another key', 'another value')
You can also use the dictionary-style [key] = value to store a value:
db['some key'] = 'some value'
Like store(), except that the value parameter is a printf()-style formatting string.
Example:
db.store_fmt('greeting', 'hello %s, you are %d years old', 'huey', 3)
Store the contents of a file in the given key. The method uses mmap to create a read-only memory-view of the file, which is then stored in the database.
Example:
for mp3_file in glob.glob('music/*.mp3'):
db.store_file(os.path.basename(mp3_file), mp3_file)
Append the given value to the data stored in the key. If no data exists, the operation is equivalent to store().
Parameters: |
|
---|
Return whether the given key exists in the database.
Parameters: | key (str) – |
---|---|
Returns: | A boolean value indicating whether the given key exists in the database. |
Example:
def get_expensive_data():
if not db.exists('cached-data'):
db.set('cached-data', calculate_expensive_data())
return db.get('cached-data')
You can also use the python in keyword to determine whether a key exists:
def get_expensive_data():
if 'cached-data' not in db:
db['cached-data'] = calculate_expensive_data()
return db['cached-data']
Retrieve the value stored at the given key. If no value exists, a KeyError will be raised.
Parameters: | key (str) – Identifier to retrieve |
---|---|
Returns: | The data stored at the given key |
Raises : | KeyError if the given key does not exist. |
Example:
db = UnQLite()
db.store('some key', 'some value')
value = db.fetch('some key')
You can also use the dictionary-style [key] lookup to retrieve a value:
value = db['some key']
Remove the key and its associated value from the database.
Parameters: | key (str) – The key to remove from the database. |
---|---|
Raises : | KeyError if the given key does not exist. |
Example:
def clear_cache():
db.delete('cached-data')
You can also use the python del keyword combined with a dictionary lookup:
def clear_cache():
del db['cached-data']
Parameters: | code (str) – a Jx9 script. |
---|---|
Returns: | a context manager yielding a VM instance. |
Compile the given Jx9 script and return an initialized VM instance.
Usage:
script = "$users = db_fetch_all('users');"
with db.compile_script(script) as vm:
vm.execute()
users = vm['users']
Parameters: | filename (str) – filename of Jx9 script |
---|---|
Returns: | a context manager yielding a VM instance. |
Compile the given Jx9 file and return an initialized VM instance.
Usage:
with db.compile_file('myscript.jx9') as vm:
vm.execute()
Parameters: | nbytes (int) – number of bytes to generate |
---|---|
Returns: | a string consisting of random lower-case letters (a-z). |
Returns: | a random positive integer |
---|
Parameters: | unqlite – A pointer to an unqlite struct. |
---|
Create and initialize a cursor. Cursors can be used as context managers, which ensures that they are closed.
Rather than instantiating this class directly, it is preferable to call the factory method UnQLite.cursor().
for i in range(4):
db['k%d' % i] = str(i)
# Cursor support iteration, which returns key/value pairs.
with db.cursor() as cursor:
all_items = [(key, value) for key, value in cursor]
# You can seek to a record, then iterate to retrieve a portion
# of results.
cursor.seek('k2')
k2, k3 = [key for key, _ in cursor]
# Previous cursor was closed automatically, open a new one.
with db.cursor() as cursor:
cursor.seek('k1') # Jump to the 2nd record, k1
assert cursor.key() == 'k1' # Use the key()/value() methods.
assert cursor.value() == '1'
cursor.delete() # Delete k1/v1
cursor.first() # Cursor now points to k0/0
cursor.next() # Cursor jumps to k2/2 since k1/1 is deleted.
assert cursor.key() == 'k2'
keys = [key for key, value in cursor] # Cursor iterates from k2->k3
assert keys == ['k2', 'k3']
Close and release the database cursor.
Advance the cursor to the given key using the comparison method described in the flags.
A detailed description of alternate flags and their usage can be found in the unqlite_kv_cursor docs.
Usage:
with db.cursor() as cursor:
cursor.seek('item.20140101')
while cursor.is_valid():
data_for_day = cursor.value()
# do something with data for day
handle_data(data_for_day)
if cursor.key() == 'item.20140201':
break
else:
cursor.next()
Place cursor at the first record.
Place cursor at the last record.
Return type: | bool |
---|
Indicate whether this cursor is pointing to a valid record, or has reached the end of the database.
Move the cursor to the next record.
Move the cursor to the previous record.
Reset the cursor, which also resets the pointer to the first record.
Delete the record currently pointed to by the cursor.
Return the key of the current record.
Return the value of the current record.
Parameters: | unqlite – A pointer to an unqlite struct. |
---|
Python wrapper around an UnQLite virtual machine. The VM is the primary means of executing Jx9 scripts and interacting with the JSON document store.
VM instances will rarely be created explicitly. Instead, they are yielded by calls to UnQLite.compile_script() and UnQLite.compile_file().
Rather than instantiating this class directly, it is preferable to call the factory method UnQLite.VM().
Note
For information on Jx9 scripting, see the Jx9 docs.
Example of passing values into a Jx9 script prior to execution, then extracting values afterwards:
script = """
$collection = 'users';
db_create($collection);
db_store($collection, $values);
$users = db_fetch_all($collection);
"""
# We can pass all sorts of interesting data in to our script.
values = [
{'username': 'huey', 'color': 'white'},
{'username': 'mickey', 'color': 'black'},
]
with self.db.compile_script(script) as vm:
# Set the value of the `values` variable in the Jx9 script:
vm['values'] = values
# Execute the script, which creates the collection and stores
# the two records.
vm.execute()
# After execution, we can extract the value of the `users` variable.
users = vm['users']
# Jx9 document store assigns a unique 0-based id to each record
# in a collection. The extracted variable `users` will now equal:
print users == [
{'username': 'huey', 'color': 'white', '__id': 0},
{'username': 'mickey', 'color': 'black', '__id': 1},
] # prints `True`
Parameters: | code (str) – A Jx9 script. |
---|
Compile the Jx9 script and initialize the VM.
Note
This does not execute the code. To execute the code, you must also call VM.execute().
Parameters: | code (str) – The filename of a Jx9 script. |
---|
Compile the Jx9 script file and initialize the VM.
Note
This does not execute the code. To execute the code, you must also call VM.execute().
Release the VM, deallocating associated memory. When using the VM as a context manager, this is handled automatically.
Reset the VM.
Execute the compiled Jx9 bytecode.
Parameters: |
|
---|
Configure an attribute of the VM. The list of verbs and their parameters can be found in the unqlite_vm_config docs.
Parameters: |
|
---|
Parameters: | name (str) – A variable name |
---|
Extract the value of a variable after the execution of a Jx9 script.