-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect_usage.py
More file actions
42 lines (29 loc) · 1.08 KB
/
Copy pathselect_usage.py
File metadata and controls
42 lines (29 loc) · 1.08 KB
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
"""Compile rules and show a SQLAlchemy select() string.
Run from the repo root after installing SQLRules and its SQLite provider.
python examples/select_usage.py
"""
from __future__ import annotations
from typing import Annotated, Literal
from pydantic import Field
from sqlalchemy import Column, Integer, MetaData, String, Table
from sqlrules_sqlite import SQLitePlugin
import sqlrules
from sqlrules import Compiler, RuleSchema
items = Table(
"items",
MetaData(),
Column("qty", Integer),
Column("status", String),
)
class ItemFilter(RuleSchema):
qty: Annotated[int, Field(ge=1, le=100)]
status: Literal["active", "pending"]
def main() -> None:
compiler = Compiler(plugins=[SQLitePlugin()])
compiled = compiler.compile(ItemFilter, items)
stmt = items.select().where(*sqlrules.where(compiled))
# Compile without a live DB — expressions use bound parameters.
compiled_stmt = stmt.compile(compile_kwargs={"literal_binds": False})
print("\n".join(line.rstrip() for line in str(compiled_stmt).splitlines()))
if __name__ == "__main__":
main()