aboutsummaryrefslogtreecommitdiffstats
path: root/py_bindings/example.py
blob: 96040a9acc2ba55c0aa7756e2de0f5d24e60ff4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import tempfile
from pprint import pformat, pprint
from autere_db import Value, Bound, DB

# TODO: This should be imported from the autere_db module
# but exporting type aliases does not work automatically
Record = list[Value]

class Inst:
    def __init__(self, id: int, name: str):
        self.id = id
        self.name = name

    def into_record(self) -> Record:
        return [
            Value.int(self.id),
            Value.string(self.name),
        ]

    @staticmethod
    def from_record(rec: Record):
        return Inst(
            rec[0].as_int(),
            rec[1].as_string(),
        )

    def __repr__(self) -> str:
        return pformat(self.__dict__)

temp_dir = tempfile.TemporaryDirectory()

# Create a new database
db = DB \
    .configure() \
    .data_dir(temp_dir.name) \
    .fields(["id", "name"]) \
    .primary_key("id") \
    .secondary_keys(["name"]) \
    .initialize()

db.upsert(Inst(1, "foo").into_record())

#res = db.find_by("name", autere_db.Value.string("foo"))
#insts = [Inst.from_record(r) for r in res]
res = db.range_by("name",
    Bound.unbounded(),
    Bound.unbounded(),
)
# insts = [Inst.from_record(r) for r in res]

res = db.find_by("name", Value.string("foo"))
print("before delete count:", len(res))

res = db.delete_by("name", Value.string("foo"))
#res = db.delete_by("id", Value.int(1))

print("deleted instances:")
for r in res:
    pprint(Inst.from_record(r))

res = db.find_by("name", Value.string("foo"))
print("find name after delete count:", len(res))

res = db.find_by("id", Value.int(1))
print(f"find id after delete count: {len(res)}")

res = db.delete_by("name", Value.string("bar"))

db.tx_begin()
db.upsert(Inst(2, "bar").into_record())
db.tx_rollback()

res = db.find_by("name", Value.string("bar"))
print("find name after rollback count:", len(res))

db.tx_begin()
db.upsert(Inst(2, "bar").into_record())
db.tx_commit()

res = db.find_by("name", Value.string("bar"))
print("find name after commit count:", len(res))