8000 feat: prepared queries with plain Python bind values (minigraf#181) by adityamukho · Pull Request #14 · project-minigraf/minigraf-python · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ path = "src/uniffi_bindgen.rs"

[dependencies]
# Unreleased v3 core (format v8). Switches to minigraf = "=3.0.0" at the v3.0.0 release.
minigraf = { git = "https://github.com/project-minigraf/minigraf", rev = "949813ce27273d0c2820690df844e76951cb7996" }
minigraf = { git = "https://github.com/project-minigraf/minigraf", rev = "5f2ba46e0c5a9954d90e52f60daaad2128d91973" }
uniffi = { version = "0.31.1", features = ["cli"] }
thiserror = "2.0.18"
serde_json = "1.0.149"
Expand Down
26 changes: 25 additions & 1 deletion README.md
8000
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,29 @@ with db.query("(query [:find ?n :where [?e :name ?n]])") as cursor:
print(row)
```

## Prepared queries

`db.prepare()` parses a query once; `execute()` and `query()` run it with its `$slots`
bound, from keyword arguments or a dict (names without the `$`). Each run reads the
database as it is then. A prepared query keeps its database open until both are freed.

```python
pq = db.prepare("(query [:find ?n :where [?e :age $age] [?e :name ?n]])")
print(json.loads(pq.execute(age=30))["results"])
print(json.loads(pq.execute({"age": 40}))["results"])
with pq.query(age=30) as cursor:
for row in cursor:
print(row)
```

`bool`, `int`, `float`, `str` and `None` bind as values, and a `uuid.UUID` as an entity
(it also fits a value slot as a ref). For the other kinds use `minigraf.Value.KEYWORD(":k")`,
`minigraf.Value.REF(uuid_str)`, `minigraf.Entity(uuid)`, `minigraf.TxCount(n)` or
`minigraf.Timestamp(ms)` for `:as-of`, and `minigraf.ANY_VALID_TIME` for `:valid-at`. Any
other Python type raises `TypeError`. A missing slot raises `MiniGrafError.Api` with
`[API-022]`, a slot in an attribute position `[API-023]`, and a value of the wrong kind
for its slot `[API-024]`.

## Fact log and log writer

`db.fact_log(filter)` streams every fact version (assertions and retractions, with
Expand Down Expand Up @@ -103,7 +126,8 @@ with src.fact_log(FactFilter()) as log, LogWriter.create("new.graph", OpenOption
## Errors

Every error is a `MiniGrafError` whose `msg` starts with its code, such as
`[API-015]`. See the [error reference](https://github.com/project-minigraf/minigraf/blob/main/docs/ERROR_REFERENCE.md).
`[API-015]`. Its class follows the code's category: `MiniGrafError.Parse`, `.Query`,
`.Storage`, `.Api` (a bad argument, a closed object, a bind mistake) or `.Other`. See the [error reference](https://github.com/project-minigraf/minigraf/blob/main/docs/ERROR_REFERENCE.md).
`append_batch` stops at the first rejected record and ends the message with
`(batch index N)`; the records before it stay appended.

Expand Down
11 changes: 10 additions & 1 deletion consumer-test/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import os
import sys

from minigraf import MiniGrafDb, MiniGrafError
from minigraf import MiniGrafDb, MiniGrafError, Value

QUERY = "(query [:find ?n :where [?e :name ?n]])"

Expand All @@ -22,6 +22,15 @@ def names(db):
assert names(mem) == ["Alice"], "query in memory returns Alice"
print("ok: in memory")

mem.execute('(transact [[:bob :name "Bob"]])')
prepared = mem.prepare("(query [:find ?n :where [?e :name $name] [?e :name ?n]])")
for name in ("Alice", "Bob"):
found = json.loads(prepared.execute(name=name))["results"]
assert found == [[name]], f"prepared query finds {name}"
typed = json.loads(prepared.execute(name=Value.TEXT("Alice")))["results"]
assert typed == [["Alice"]], "prepared query takes a typed value"
print("ok: prepared query runs with plain and typed bind values")

try:
mem.execute("(query [:find")
except MiniGrafError:
Expand Down
94 changes: 94 additions & 0 deletions minigraf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json as _json
import uuid as _uuid

from .minigraf_ffi import (
FactFilter,
Expand All @@ -8,7 +9,9 @@
MiniGrafDb,
MiniGrafError,
MiniGrafFactLog,
MiniGrafBindValue,
MiniGrafLogWriter,
MiniGrafPreparedQuery,
MiniGrafValue,
OpenOptions,
SyncMode,
Expand All @@ -19,6 +22,8 @@
FactLog = MiniGrafFactLog
LogWriter = MiniGrafLogWriter
Value = MiniGrafValue
BindValue = MiniGrafBindValue
PreparedQuery = MiniGrafPreparedQuery

#: ``valid_to`` of a fact that is valid forever.
VALID_TIME_FOREVER = 2**63 - 1
Expand Down Expand Up @@ -62,6 +67,87 @@ def open(
)


# ─── Bind values for prepared queries (#181) ─────────────────────────────────


def Entity(entity):
"""Bind an entity (a UUID or its string). It also fits a value slot as a ref."""
return MiniGrafBindValue.ENTITY(str(entity))


def TxCount(n):
"""Bind ``:as-of $slot`` to the transaction counter ``n``."""
return MiniGrafBindValue.TX_COUNT(n)


def Timestamp(ms):
"""Bind ``:as-of $slot`` or ``:valid-at $slot`` to Unix milliseconds."""
return MiniGrafBindValue.TIMESTAMP(ms)


#: Bind ``:valid-at $slot`` to every valid time, like ``:any-valid-time``.
ANY_VALID_TIME = MiniGrafBindValue.ANY_VALID_TIME()

_I64_MIN, _I64_MAX = -(2**63), 2**63 - 1


def _bind_value(name, v):
"""A plain Python value or a typed form as a ``MiniGrafBindValue``."""
if isinstance(v, MiniGrafBindValue):
return v
if isinstance(v, MiniGrafValue):
return MiniGrafBindValue.VALUE(v)
# bool before int: True is an int in Python.
if isinstance(v, bool):
return MiniGrafBindValue.VALUE(MiniGrafValue.BOOL(v))
if isinstance(v, int):
if not _I64_MIN <= v <= _I64_MAX:
raise MiniGrafError.Api(
f"[API-017] invalid argument: slot ${name}: {v} is outside the 64-bit integer range"
)
return MiniGrafBindValue.VALUE(MiniGrafValue.INT64(v))
if isinstance(v, float):
return MiniGrafBindValue.VALUE(MiniGrafValue.FLOAT64(v))
if isinstance(v, str):
return MiniGrafBindValue.VALUE(MiniGrafValue.TEXT(v))
if v is None:
return MiniGrafBindValue.VALUE(MiniGrafValue.NULL())
if isinstance(v, _uuid.UUID):
return MiniGrafBindValue.ENTITY(str(v))
raise TypeError(
f"slot ${name}: cannot bind a {type(v).__name__}; use bool, int, float, str, "
"None, uuid.UUID, a minigraf.Value or minigraf.Entity/TxCount/Timestamp/ANY_VALID_TIME"
)


def _bindings(mapping, kwargs):
merged = dict(mapping or {})
merged.update(kwargs)
return {name: _bind_value(name, v) for name, v in merged.items()}


_prepared_execute = MiniGrafPreparedQuery.execute
_prepared_query = MiniGrafPreparedQuery.query


def _execute(self, bindings=None, /, **kwargs):
"""Run the query with its slots bound, from a dict and/or keyword
arguments named without the ``$``; returns JSON like ``MiniGrafDb.execute``.
Plain ``bool``, ``int``, ``float``, ``str``, ``None`` and ``uuid.UUID``
values bind as they are."""
return _prepared_execute(self, _bindings(bindings, kwargs))


def _query(self, bindings=None, /, **kwargs):
"""Run the query with its slots bound, as ``execute`` does, and return a
cursor over its rows."""
return _prepared_query(self, _bindings(bindings, kwargs))


MiniGrafPreparedQuery.execute = _execute
MiniGrafPreparedQuery.query = _query


def _close_on_exit(self, *exc):
self.close()
return False
Expand Down Expand Up @@ -110,7 +196,10 @@ def _writer_exit(self, exc_type, exc, tb):
MiniGrafLogWriter.__exit__ = _writer_exit

__all__ = [
"ANY_VALID_TIME",
"BindValue",
"Cursor",
"Entity",
"FactFilter",
"FactLog",
"FactOrder",
Expand All @@ -120,10 +209,15 @@ def _writer_exit(self, exc_type, exc, tb):
"MiniGrafDb",
"MiniGrafError",
"MiniGrafFactLog",
"MiniGrafBindValue",
"MiniGrafLogWriter",
"MiniGrafPreparedQuery",
"MiniGrafValue",
"OpenOptions",
"PreparedQuery",
"SyncMode",
"Timestamp",
"TxCount",
"VALID_TIME_FOREVER",
"WAL_CHECKPOINT_NEVER",
"Value",
Expand Down
Loading
Loading
0