-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo.py
93 lines (74 loc) · 2.66 KB
/
demo.py
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
82
83
84
85
86
87
88
89
90
91
92
93
"""Demonstration script showcasing basic SQLiter functionality.
This script provides a practical example of using SQLiter in a
simple application scenario. It demonstrates setting up models,
establishing a database connection, and performing various database
operations including inserts, queries, and updates. This serves as
both a functional test and a usage guide for the SQLiter library.
"""
from __future__ import annotations
import logging
from typing import Optional
from sqliter import SqliterDB
from sqliter.exceptions import RecordInsertionError
from sqliter.model import BaseDBModel
# User model inheriting from the 'BaseDBModel' class
class UserModel(BaseDBModel):
"""This subclass represents a User model for the database."""
slug: str
name: str
content: Optional[str]
admin: bool = False
class Meta:
"""Override the table name for the UserModel."""
table_name: str = "users" # Explicitly define the table name
def main() -> None:
"""Simple example to demonstrate the usage of the 'sqliter' package."""
# set up logging
logging.basicConfig(
level=logging.DEBUG, format="%(levelname)-8s%(message)s"
)
db = SqliterDB(
"demo.db", memory=False, auto_commit=True, debug=True, reset=True
)
with db:
db.create_table(UserModel) # Create the users table
user1 = UserModel(
slug="jdoe",
name="John Doe",
content="This is information about John Doe.",
admin=True,
)
user2 = UserModel(
slug="jdoe2",
name="Jane Doe",
content="This is information about Jane Doe.",
)
user3 = UserModel(
slug="jb",
name="Yogie Bear",
content=None,
)
try:
db.insert(user1)
user2_instance = db.insert(user2)
db.insert(user3)
except RecordInsertionError as exc:
logging.error(exc) # noqa: TRY400
# Example queries
users = db.select(UserModel).filter(name="John Doe").fetch_all()
logging.info(users)
all_users = db.select(UserModel).fetch_all()
logging.info(all_users)
all_reversed = (
db.select(UserModel).order("name", reverse=True).fetch_all()
)
logging.info(all_reversed)
if user2_instance is None:
logging.error("User2 ID not found.")
else:
fetched_user = db.get(UserModel, user2_instance.pk)
logging.info("Fetched (%s)", fetched_user)
count = db.select(UserModel).count()
logging.info("Total Users: %s", count)
if __name__ == "__main__":
main()