Builder: Select and Insert¶
Showcase the fluent SQL builder API with a compact SQLite dataset.
uv run python docs/examples/patterns/builder/select_and_insert.py
Source¶
1"""Showcase SQL builder fluency with a compact SQLite dataset."""
2
3from docs.examples.shared.data import ARTICLES
4from sqlspec import SQLSpec, sql
5from sqlspec.adapters.sqlite import SqliteConfig
6
7__all__ = ("main",)
8
9
10def main() -> None:
11 """Create a table, insert demo rows, and fetch results with the builder API."""
12 registry = SQLSpec()
13 config = registry.add_config(SqliteConfig(pool_config={"database": ":memory:"}))
14 with registry.provide_session(config) as session:
15 session.execute(
16 """
17 CREATE TABLE articles (
18 id INTEGER PRIMARY KEY,
19 title TEXT NOT NULL,
20 body TEXT NOT NULL
21 )
22 """
23 )
24 session.execute_many(
25 """
26 INSERT INTO articles (id, title, body)
27 VALUES (:id, :title, :body)
28 """,
29 ARTICLES,
30 )
31 query = sql.select("id", "title").from_("articles").where("title LIKE ?")
32 rows = session.select(query, "%SQL%")
33 print({"rows": rows})
34
35
36if __name__ == "__main__":
37 main()