diff --git a/python/fromdocs/connection/login.py b/python/fromdocs/connection/login.py new file mode 100644 index 0000000..76c1687 --- /dev/null +++ b/python/fromdocs/connection/login.py @@ -0,0 +1,43 @@ + +from grpc import RpcError +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + + +def main(): + client = ImmudbClient(URL) + # database parameter is optional + client.login(LOGIN, PASSWORD, database=DB) + client.logout() + + # Bad login + try: + client.login("verybadlogin", "verybadpassword") + except RpcError as exception: + print(exception.debug_error_string()) + print(exception.details()) + + + # Managed session support + with client.openManagedSession(LOGIN, PASSWORD, database=DB) as session: + transaction = session.newTx() + transaction.sqlExec("CREATE TABLE IF NOT EXISTS connectiontest1 (id INTEGER AUTO_INCREMENT, name VARCHAR[255], PRIMARY KEY(id))") + commited = transaction.commit() + print(commited) # If table was created exists - shows transaction informations + + # Not managed session. You need to handle keep alive request yourself + session = client.openSession(LOGIN, PASSWORD, database=DB) + transaction = session.newTx() + transaction.sqlExec("CREATE TABLE IF NOT EXISTS connectiontest2 (id INTEGER AUTO_INCREMENT, name VARCHAR[255], PRIMARY KEY(id))") + commited = transaction.commit() + print(commited) # If table was created - shows transaction informations + client.closeSession() + + + +if __name__ == "__main__": + main() diff --git a/python/fromdocs/kvoperations/dataexpiration/expire.py b/python/fromdocs/kvoperations/dataexpiration/expire.py new file mode 100644 index 0000000..e3b5363 --- /dev/null +++ b/python/fromdocs/kvoperations/dataexpiration/expire.py @@ -0,0 +1,22 @@ +from immudb import ImmudbClient +from datetime import datetime, timedelta +import time + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + client.expireableSet(b"TEST", b"test", datetime.now() + timedelta(seconds=3)) + print(client.get(b"TEST")) # b"test" + time.sleep(4) + try: + print(client.get(b"TEST")) + except: + pass # Key not found, because it expires, raises Exception + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/deleting/delete.py b/python/fromdocs/kvoperations/deleting/delete.py new file mode 100644 index 0000000..ab91cfd --- /dev/null +++ b/python/fromdocs/kvoperations/deleting/delete.py @@ -0,0 +1,20 @@ +from immudb import ImmudbClient +from immudb.datatypes import DeleteKeysRequest + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + client.set(b"immu", b"immudb-not-rulezz") + print(client.get(b"immu")) # b"immudb-not-rulezz" + + deleteRequest = DeleteKeysRequest(keys = [b"immu"]) + client.delete(deleteRequest) + print(client.get(b"immu")) # None + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/queriesandhistory/getreference.py b/python/fromdocs/kvoperations/queriesandhistory/getreference.py new file mode 100644 index 0000000..5098f7e --- /dev/null +++ b/python/fromdocs/kvoperations/queriesandhistory/getreference.py @@ -0,0 +1,41 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + client.verifiedSet(b'x', b'1') + client.verifiedSet(b'y', b'1') + retrieved = client.verifiedGet(b'x') + print(retrieved.refkey) # Entry reference key (None) + + client.verifiedSetReference(b'x', b'reference1') + client.setReference(b'x', b'reference2') + client.setReference(b'y', b'reference2') + client.verifiedSet(b'y', b'2') + + retrieved = client.verifiedGet(b'reference1') + print(retrieved.key) # Entry key (b'x') + print(retrieved.refkey) # Entry reference key (b'reference1') + print(retrieved.verified) # Entry verification status (True) + + retrieved = client.verifiedGet(b'reference2') + print(retrieved.key) # Entry key (b'y') + print(retrieved.refkey) # Entry reference key (b'reference2') + print(retrieved.verified) # Entry verification status (True) + print(retrieved.value) # Entry value (b'3') + + retrieved = client.verifiedGet(b'x') + print(retrieved.key) # Entry key (b'x') + print(retrieved.refkey) # Entry reference key (None) + print(retrieved.verified) # Entry verification status (True) + + retrieved = client.get(b'reference2') + print(retrieved.key) # Entry key (b'y') + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/queriesandhistory/history.py b/python/fromdocs/kvoperations/queriesandhistory/history.py new file mode 100644 index 0000000..7a365e7 --- /dev/null +++ b/python/fromdocs/kvoperations/queriesandhistory/history.py @@ -0,0 +1,28 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + + client.set(b'test', b'1') + client.set(b'test', b'2') + client.set(b'test', b'3') + + history = client.history(b'test', 0, 100, True) # List[immudb.datatypes.historyResponseItem] + responseItemFirst = history[0] + print(responseItemFirst.key) # Entry key (b'test') + print(responseItemFirst.value) # Entry value (b'3') + print(responseItemFirst.tx) # Transaction id + + responseItemThird = history[2] + print(responseItemThird.key) # Entry key (b'test') + print(responseItemThird.value) # Entry value (b'1') + print(responseItemThird.tx) # Transaction id + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/queriesandhistory/scan.py b/python/fromdocs/kvoperations/queriesandhistory/scan.py new file mode 100644 index 0000000..69d0798 --- /dev/null +++ b/python/fromdocs/kvoperations/queriesandhistory/scan.py @@ -0,0 +1,37 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + toSet = { + b"aaa": b'1', + b'bbb': b'2', + b'ccc': b'3', + b'acc': b'1', + b'aac': b'2', + b'aac:test1': b'3', + b'aac:test2': b'1', + b'aac:xxx:test': b'2' + } + client.setAll(toSet) + + result = client.scan(b'', b'', True, 100) # All entries + print(result) + result = client.scan(b'', b'aac', True, 100) # All entries with prefix 'aac' including 'aac' + print(result) + + # Seek key example (allows retrieve entries in proper chunks): + result = client.scan(b'', b'', False, 3) + while result: + for item, value in result.items(): + print("SEEK", item, value) + lastKey = list(result.keys())[-1] + result = client.scan(lastKey, b'', False, 3) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/queriesandhistory/setreference.py b/python/fromdocs/kvoperations/queriesandhistory/setreference.py new file mode 100644 index 0000000..5098f7e --- /dev/null +++ b/python/fromdocs/kvoperations/queriesandhistory/setreference.py @@ -0,0 +1,41 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + client.verifiedSet(b'x', b'1') + client.verifiedSet(b'y', b'1') + retrieved = client.verifiedGet(b'x') + print(retrieved.refkey) # Entry reference key (None) + + client.verifiedSetReference(b'x', b'reference1') + client.setReference(b'x', b'reference2') + client.setReference(b'y', b'reference2') + client.verifiedSet(b'y', b'2') + + retrieved = client.verifiedGet(b'reference1') + print(retrieved.key) # Entry key (b'x') + print(retrieved.refkey) # Entry reference key (b'reference1') + print(retrieved.verified) # Entry verification status (True) + + retrieved = client.verifiedGet(b'reference2') + print(retrieved.key) # Entry key (b'y') + print(retrieved.refkey) # Entry reference key (b'reference2') + print(retrieved.verified) # Entry verification status (True) + print(retrieved.value) # Entry value (b'3') + + retrieved = client.verifiedGet(b'x') + print(retrieved.key) # Entry key (b'x') + print(retrieved.refkey) # Entry reference key (None) + print(retrieved.verified) # Entry verification status (True) + + retrieved = client.get(b'reference2') + print(retrieved.key) # Entry key (b'y') + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/readwrites/getatrevision.py b/python/fromdocs/kvoperations/readwrites/getatrevision.py new file mode 100644 index 0000000..bf634e8 --- /dev/null +++ b/python/fromdocs/kvoperations/readwrites/getatrevision.py @@ -0,0 +1,36 @@ +from grpc import RpcError +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + first = client.set(b'x', b'y') # Not important, just to demonstrate + # that it will not affect atRevision + # for other keys + + key = b'immudb130130130' + + client.set(key, b'111') + client.set(key, b'222') + client.set(key, b'333') + + print(client.get(key, -2)) # b"111" - value on relative -2 point history + print(client.get(key, -1)) # b"222" - value on relative -1 point history + print(client.get(key, 0)) # b"333" - value on relative 0 (current) point history + + print(client.get(key, 1)) # b"111" - value at first revision of key + print(client.get(key, 2)) # b"222" - value on second revision of key + print(client.get(key, 3)) # b"333" - value on third revision of key + + try: + print(client.get(key, -20000)) + except RpcError as error: + print(error.details()) # invalid key revision number + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/readwrites/getatx.py b/python/fromdocs/kvoperations/readwrites/getatx.py new file mode 100644 index 0000000..7202a41 --- /dev/null +++ b/python/fromdocs/kvoperations/readwrites/getatx.py @@ -0,0 +1,40 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + + keyFirst = b'333' + keySecond = b'555' + + first = client.set(keyFirst, b'111') + firstTransaction = first.id + + second = client.set(keySecond, b'222') + secondTransaction = second.id + + toSet = { + b'1': b'test1', + b'2': b'test2', + b'3': b'test3' + } + + third = client.setAll(toSet) + thirdTransaction = third.id + + keysAtFirst = client.txById(firstTransaction) + keysAtSecond = client.txById(secondTransaction) + keysAtThird = client.txById(thirdTransaction) + + print(keysAtFirst) # [b'333'] + print(keysAtSecond) # [b'555'] + print(keysAtThird) # [b'1', b'2', b'3'] + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/readwrites/getset.py b/python/fromdocs/kvoperations/readwrites/getset.py new file mode 100644 index 0000000..354ea94 --- /dev/null +++ b/python/fromdocs/kvoperations/readwrites/getset.py @@ -0,0 +1,70 @@ +from immudb import ImmudbClient +import json + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def encode(what: str): + return what.encode("utf-8") + +def decode(what: bytes): + return what.decode("utf-8") + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + + # You have to operate on bytes + setResult = client.set(b'x', b'y') + print(setResult) # immudb.datatypes.SetResponse + print(setResult.id) # id of transaction + print(setResult.verified) # in this case verified = False + # see Tamperproof reading and writing + + # Also you get response in bytes + retrieved = client.get(b'x') + print(retrieved) # immudb.datatypes.GetResponse + print(retrieved.key) # Value is b'x' + print(retrieved.value) # Value is b'y' + print(retrieved.tx) # Transaction number + + print(type(retrieved.key)) # + print(type(retrieved.value)) # + + # Operating with strings + encodedHello = encode("Hello") + encodedImmutable = encode("Immutable") + client.set(encodedHello, encodedImmutable) + retrieved = client.get(encodedHello) + + print(decode(retrieved.value) == "Immutable") # Value is True + + notExisting = client.get(b'asdasd') + print(notExisting) # Value is None + + + # JSON example + toSet = {"hello": "immutable"} + encodedToSet = encode(json.dumps(toSet)) + client.set(encodedHello, encodedToSet) + + retrieved = json.loads(decode(client.get(encodedHello).value)) + print(retrieved) # Value is {"hello": "immutable"} + + # setAll example - sets all keys to value from dictionary + toSet = { + b'1': b'test1', + b'2': b'test2', + b'3': b'test3' + } + + client.setAll(toSet) + retrieved = client.getAll(list(toSet.keys())) + print(retrieved) + # Value is {b'1': b'test1', b'2': b'test2', b'3': b'test3'} + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/readwrites/getsetsincetx.py b/python/fromdocs/kvoperations/readwrites/getsetsincetx.py new file mode 100644 index 0000000..9137075 --- /dev/null +++ b/python/fromdocs/kvoperations/readwrites/getsetsincetx.py @@ -0,0 +1,59 @@ +from grpc import RpcError +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + first = client.set(b'justfirsttransaction', b'justfirsttransaction') + + key = b'123123' + + first = client.set(key, b'111') + firstTransaction = first.id + + second = client.set(key, b'222') + secondTransaction = second.id + + third = client.set(key, b'333') + thirdTransaction = third.id + + print(client.verifiedGetSince(key, firstTransaction)) # b"111" + # most recent value behind X ensuring + # the indexer has already processed at least + # given sinceTx transaction. + print(client.verifiedGetSince(key, firstTransaction + 1)) # b"222" + + try: + # This key wasn't set on this transaction + print(client.verifiedGetAt(key, firstTransaction - 1)) + except RpcError as exception: + print(exception.debug_error_string()) + print(exception.details()) + + verifiedFirst = client.verifiedGetAt(key, firstTransaction) + # immudb.datatypes.SafeGetResponse + print(verifiedFirst.id) # id of transaction + print(verifiedFirst.key) # Key that was modified + print(verifiedFirst.value) # Value after this transaction + print(verifiedFirst.refkey) # Reference key + # (Queries And History -> setReference) + print(verifiedFirst.verified) # Response is verified or not + print(verifiedFirst.timestamp) # Time of this transaction + + print(client.verifiedGetAt(key, secondTransaction)) + print(client.verifiedGetAt(key, thirdTransaction)) + + try: + # Transaction doesn't exists yet + print(client.verifiedGetAt(key, thirdTransaction + 1)) + except RpcError as exception: + print(exception.debug_error_string()) + print(exception.details()) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/secondaryindexes/sortedsets.py b/python/fromdocs/kvoperations/secondaryindexes/sortedsets.py new file mode 100644 index 0000000..ad9e2a4 --- /dev/null +++ b/python/fromdocs/kvoperations/secondaryindexes/sortedsets.py @@ -0,0 +1,27 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + client.set(b"user1", b"user1@mail.com") + client.set(b"user2", b"user2@mail.com") + client.set(b"user3", b"user3@mail.com") + client.set(b"user4", b"user3@mail.com") + + client.zAdd(b"age", 100, b"user1") + client.zAdd(b"age", 101, b"user2") + client.zAdd(b"age", 99, b"user3") + client.zAdd(b"age", 100, b"user4") + + scanResult = client.zScan(b"age", b"", 0, 0, True, 50, False, 100, 101) + print(scanResult) # Shows records with 'age' 100 <= score < 101 + # with descending order and limit = 50 + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/transactions/execall.py b/python/fromdocs/kvoperations/transactions/execall.py new file mode 100644 index 0000000..a8f8807 --- /dev/null +++ b/python/fromdocs/kvoperations/transactions/execall.py @@ -0,0 +1,27 @@ +from immudb import ImmudbClient +from immudb.datatypes import KeyValue, ZAddRequest, ReferenceRequest + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + + toExecute = [ + KeyValue(b'key', b'value'), + ZAddRequest(b'testscore', 100, b'key'), + KeyValue(b'key2', b'value2'), + ZAddRequest(b'testscore', 150, b'key2'), + ReferenceRequest(b'reference1', b'key') + ] + info = client.execAll(toExecute) + print(info.id) # All in one transaction + + print(client.zScan(b'testscore', b'', 0, 0, True, 10, True, 0, 200)) # Shows these entries + print(client.get(b'reference1')) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/transactions/getall.py b/python/fromdocs/kvoperations/transactions/getall.py new file mode 100644 index 0000000..cbab193 --- /dev/null +++ b/python/fromdocs/kvoperations/transactions/getall.py @@ -0,0 +1,20 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + + client.set(b'key1', b'value1') + client.set(b'key2', b'value2') + client.set(b'key3', b'value3') + + response = client.getAll([b'key1', b'key2', b'key3']) + print(response) # The same as dictToSetGet, retrieved in one step + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/kvoperations/transactions/setall.py b/python/fromdocs/kvoperations/transactions/setall.py new file mode 100644 index 0000000..3b5057c --- /dev/null +++ b/python/fromdocs/kvoperations/transactions/setall.py @@ -0,0 +1,23 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + dictToSetGet = { + b'key1': b'value1', + b'key2': b'value2', + b'key3': b'value3' + } + response = client.setAll(dictToSetGet) + print(response.id) # All in one transaction + + response = client.getAll([b'key1', b'key2', b'key3']) + print(response) # The same as dictToSetGet, retrieved in one step + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/management/database.py b/python/fromdocs/management/database.py new file mode 100644 index 0000000..785aa27 --- /dev/null +++ b/python/fromdocs/management/database.py @@ -0,0 +1,23 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + testDatabase = "test" + + databases = client.databaseList() + if(testDatabase not in databases): + client.createDatabase(testDatabase) + + client.useDatabase("test") + client.set(b"test", b"test") + client.databaseList() + print(client.get(b"test")) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/management/healthcheck.py b/python/fromdocs/management/healthcheck.py new file mode 100644 index 0000000..2f9c029 --- /dev/null +++ b/python/fromdocs/management/healthcheck.py @@ -0,0 +1,15 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + check = client.healthCheck() # Returns bool + print(check) # True + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/management/users.py b/python/fromdocs/management/users.py new file mode 100644 index 0000000..3f5cad4 --- /dev/null +++ b/python/fromdocs/management/users.py @@ -0,0 +1,82 @@ +from grpc import RpcError +from immudb import ImmudbClient +from immudb.constants import PERMISSION_ADMIN, PERMISSION_R, PERMISSION_RW +from immudb.grpc.schema_pb2 import GRANT, REVOKE +from enum import IntEnum + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + passwordForNewUsers = "Te1st!@#Test" + try: + client.createUser("tester1", passwordForNewUsers, PERMISSION_R, DB) + client.createUser("tester2", passwordForNewUsers, PERMISSION_RW, DB) + client.createUser("tester3", passwordForNewUsers, PERMISSION_ADMIN, DB) + except RpcError as exception: + print(exception.details()) + + users = client.listUsers().userlist.users # immudb.handler.listUsers.listUsersResponse + for user in users: + print("User", user.user) + print("Created by", user.createdby) + print("Creation date", user.createdat) + print("Is active", user.active) + for permission in user.permissions: + print("Permission", permission.database, permission.permission) + print("---") + + client.login("tester3", passwordForNewUsers, DB) + client.changePermission(GRANT, "tester2", DB, PERMISSION_ADMIN) + client.changePermission(REVOKE, "tester2", DB, PERMISSION_ADMIN) + + client.login(LOGIN, PASSWORD, database = DB) + # Changing password + client.changePassword("tester1", "N1ewpassword!", passwordForNewUsers) + + # User logs with new password + client.login("tester1", "N1ewpassword!") + + client.login(LOGIN, PASSWORD, database = DB) + client.changePassword("tester1", passwordForNewUsers, "N1ewpassword!") + + + client.login("tester1", passwordForNewUsers, DB) + + # No permissions to write + try: + client.set(b"test", b"test") + except RpcError as exception: + print(exception.details()) + + # But has permissions to read + result = client.get(b"test") + + client.login("tester3", passwordForNewUsers, DB) + + # Now will have permissions to write + client.changePermission(GRANT, "tester1", DB, PERMISSION_RW) + client.login("tester1", passwordForNewUsers, DB) + client.set(b"test", b"test") + result = client.get(b"test") + + client.login("tester3", passwordForNewUsers, DB) + + # Now will have permissions to nothing + client.changePermission(REVOKE, "tester1", DB, PERMISSION_RW) + + try: + client.login("tester1", passwordForNewUsers, DB) + except RpcError as exception: + print(exception.details()) + + client.login("tester3", passwordForNewUsers, DB) + client.changePermission(GRANT, "tester1", DB, PERMISSION_RW) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/sqloperations/transactions/transactions.py b/python/fromdocs/sqloperations/transactions/transactions.py new file mode 100644 index 0000000..ad36cee --- /dev/null +++ b/python/fromdocs/sqloperations/transactions/transactions.py @@ -0,0 +1,119 @@ +from immudb import ImmudbClient +from uuid import uuid4 + +URL = "localhost:3322" # ImmuDB running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + + client.sqlExec(""" + CREATE TABLE IF NOT EXISTS example ( + uniqueID VARCHAR[64], + value VARCHAR[32], + created TIMESTAMP, + PRIMARY KEY(uniqueID) + );""") + + client.sqlExec(""" + CREATE TABLE IF NOT EXISTS related ( + id INTEGER AUTO_INCREMENT, + uniqueID VARCHAR[64], + relatedValue VARCHAR[32], + PRIMARY KEY(id) + );""") + + uid1 = str(uuid4()) + uid2 = str(uuid4()) + params = { + "uid1": uid1, + "uid2": uid2 + } + + resp = client.sqlExec(""" + BEGIN TRANSACTION; + + INSERT INTO example (uniqueID, value, created) + VALUES (@uid1, 'test1', NOW()), (@uid2, 'test2', NOW()); + INSERT INTO related (uniqueID, relatedValue) + VALUES (@uid1, 'related1'), (@uid2, 'related2'); + INSERT INTO related (uniqueID, relatedValue) + VALUES (@uid1, 'related3'), (@uid2, 'related4'); + + COMMIT; + """, params) + + transactionId = resp.txs[0].header.id + + result = client.sqlQuery(""" + SELECT + related.id, + related.uniqueID, + example.value, + related.relatedValue, + example.created + FROM related + JOIN example + ON example.uniqueID = related.uniqueID; + """) + for item in result: + id, uid, value, relatedValue, created = item + print("ITEM", id, uid, value, relatedValue, created.isoformat()) + + + result = client.sqlQuery(f""" + SELECT + related.id, + related.uniqueID, + example.value, + related.relatedValue, + example.created + FROM related BEFORE TX {transactionId} + JOIN example BEFORE TX {transactionId} + ON example.uniqueID = related.uniqueID; + """) + print(result) # You can't see just added entries, + # my fellow time traveller + + + # interactive session + with client.openManagedSession(LOGIN, PASSWORD, database = DB) as session: + transaction = session.newTx() + for _ in range(3): + uidNow1 = str(uuid4()) + uidNow2 = str(uuid4()) + transaction.sqlExec("""INSERT INTO example (uniqueID, value, created) + VALUES (@uid1, 'test130', NOW()), (@uid2, 'test131', NOW());""", {"uid1": uidNow1, "uid2": uidNow2}) + resp = transaction.commit() + + transaction = session.newTx() + resultsSize = getResultsList(transaction) + print("RESULTS SIZE", resultsSize) # Results size is +6 becasue we commited new transaction + + for _ in range(3): + uidNow1 = str(uuid4()) + uidNow2 = str(uuid4()) + transaction.sqlExec("""INSERT INTO example (uniqueID, value, created) + VALUES (@uid1, 'test130', NOW()), (@uid2, 'test131', NOW());""", {"uid1": uidNow1, "uid2": uidNow2}) + + resultsSize = getResultsList(transaction) + print("RESULTS SIZE", resultsSize) # Results size is +6 becasue we still not commited transaction + + transaction.rollback() + + transaction = session.newTx() + + resultsSize = getResultsList(transaction) + print("RESULTS SIZE", resultsSize) # Results size is -6 becasue we rollback transaction + +def getResultsList(transaction): + results = transaction.sqlQuery(f""" + SELECT example.value FROM example""") + return len(results) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/state/currentstate.py b/python/fromdocs/state/currentstate.py new file mode 100644 index 0000000..0222ece --- /dev/null +++ b/python/fromdocs/state/currentstate.py @@ -0,0 +1,19 @@ +from immudb import ImmudbClient + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) + +def main(): + client = ImmudbClient(URL) + client.login(LOGIN, PASSWORD, database = DB) + + state = client.currentState() # immudb.rootService.State + print(state.db) # Current selected DB + print(state.txId) # Current transaction ID + print(state.txHash) # Current transaction hash + print(state.signature) # Current signature + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/state/verifystate.py b/python/fromdocs/state/verifystate.py new file mode 100644 index 0000000..a2ccc18 --- /dev/null +++ b/python/fromdocs/state/verifystate.py @@ -0,0 +1,24 @@ +from immudb import ImmudbClient +from immudb.client import PersistentRootService + +# By default RootService is writing state to RAM +# You can choose different implementation of RootService + +# Persistent root service will save to the disk after every verified transaction + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) +PERSISTENT_ROOT_SERVICE_PATH = "/tmp/psr.db" + +def main(): + client = ImmudbClient(URL, rs = PersistentRootService(PERSISTENT_ROOT_SERVICE_PATH)) + client.login(LOGIN, PASSWORD, database = DB) + client.verifiedSet(b'x', b'1') + client.verifiedGet(b'x') + client.verifiedSet(b'x', b'2') + client.verifiedGet(b'x') + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/fromdocs/state/verifystatesignature.py b/python/fromdocs/state/verifystatesignature.py new file mode 100644 index 0000000..95f83ca --- /dev/null +++ b/python/fromdocs/state/verifystatesignature.py @@ -0,0 +1,27 @@ +from immudb import ImmudbClient + +# All operations are checked against public/private key pair + +URL = "localhost:3322" # immudb running on your machine +LOGIN = "immudb" # Default username +PASSWORD = "immudb" # Default password +DB = b"defaultdb" # Default database name (must be in bytes) +KEYFILE = "../../../example-public.key" # Public key path + # needs immudb server with --signingKey option enabled + # pointing to corresponding private key + +def main(): + client = ImmudbClient(URL, publicKeyFile = KEYFILE) + client.login(LOGIN, PASSWORD, database = DB) + client.set(b'x', b'1') + client.verifiedGet(b'x') # This operation will also fail if public key + # is not paired with private one used in immudb + + state = client.currentState() # immudb.rootService.State + print(state.db) # Current selected DB + print(state.txId) # Current transaction ID + print(state.txHash) # Current transaction hash + print(state.signature) # Current signature + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/python/sql_pagination.py b/python/sql_pagination.py new file mode 100644 index 0000000..bb4ee31 --- /dev/null +++ b/python/sql_pagination.py @@ -0,0 +1,39 @@ +from immudb.client import ImmudbClient +import uuid +MAX_N = 2000 +def main(): + client = ImmudbClient("localhost:3322") + client.login("immudb", "immudb", "defaultdb") + client.sqlExec("""CREATE TABLE IF NOT EXISTS pagination( ID INTEGER AUTO_INCREMENT, VALUE VARCHAR[255], PRIMARY KEY(ID) )""") + + for index in range(0, MAX_N): + print("Adding records...", index, f"{round((index / MAX_N) * 100, 2)}%") + value = str(uuid.uuid4()) + client.sqlExec("INSERT INTO pagination(VALUE) VALUES(@someValue)", {"someValue": value}) + + query = """SELECT ID, VALUE FROM pagination ORDER BY ID LIMIT 999""" + + # Pagination method + wholeResult = [] + result = client.sqlQuery(query) + while result: + wholeResult.extend(result) + queryNext = """SELECT ID, VALUE FROM pagination WHERE id > @lastId ORDER BY ID LIMIT 999""" + lastId = result[-1][0] + result = client.sqlQuery(queryNext, {"lastId": lastId}) + print(len(wholeResult)) + + # Offset method - less performance + wholeResult = [] + result = client.sqlQuery(query) + offset = 0 + query = f"""SELECT ID, VALUE FROM pagination ORDER BY ID LIMIT 999""" + while result: + offset = offset + len(result) + wholeResult.extend(result) + queryNext = f"""SELECT ID, VALUE FROM pagination ORDER BY ID LIMIT 999 OFFSET {offset}""" + lastId = result[-1][0] + result = client.sqlQuery(queryNext) + print(len(wholeResult)) + +main() \ No newline at end of file