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
12 changes: 8 additions & 4 deletions docs/06-fragments-and-views.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,11 @@ await gom.load_all(Account, where=refs(Account).email.eq_ignore_case("Ada@Exampl

- **The copy.** Every `save`, `create`, `update`, `save_all`, `patch` and `patch_all`, and the save of a view's root
and related nodes, writes a lowercased copy of the property beside it, under `__drivine.lower.<property>` (the name it
is stored under, after `GraphProperty`). The database lowercases it, as it lowercases the value a lookup compares
with, so drivine-python, drivine4j and TypeScript's Drivine store and match the same thing. A property with no value
has no copy. A load doesn't read it, and a flat `PropertyBag` never holds it. The copy is no part of whether a save
changed the node, so a save that only fills one in keeps the node's stamp. Cypher you send yourself doesn't: see
is stored under, after `GraphProperty`); on a SQL store, which holds a property named `$mail` as `$$mail`, the copy
is still `__drivine.lower.$mail`. The database lowercases it, as it lowercases the value a lookup compares with, so
drivine-python, drivine4j and TypeScript's Drivine store and match the same thing. A property with no value has no
copy. A load doesn't read it, and a flat `PropertyBag` never holds it. The copy is no part of whether a save changed
the node, so a save that only fills one in keeps the node's stamp. Cypher you send yourself doesn't: see
[below](#cypher-of-your-own).
- **The index.** `RangeIndex(ignore_case=True)`, `Unique(ignore_case=True)`, `range_index(label, property,
ignore_case=True)` and `uniqueness_constraint(label, property, ignore_case=True)` are made over the copy, under their
Expand All @@ -152,6 +153,9 @@ await gom.load_all(Account, where=refs(Account).email.eq_ignore_case("Ada@Exampl
- **Filling it in.** Ensuring an item that ignores case first fills the copy in on every node of the label that lacks
it, 10,000 nodes a statement, and records that every node has it: on the store's `DrivineStore` node on the graph
engines, in the graph's catalog on Oracle and Postgres. An item made anew, or recreated, fills the copies in again.
On Oracle, Postgres and SQLite every ensure also fills in again the copy of a property named with a `$`, though
recorded: an earlier version wrote none, or wrote it under the held name, `__drivine.lower.$$mail`, which no lookup
reads, so a node it saved is missed by a lookup until an ensure has run.
- **The lookup.** Once the copy is recorded, `eq_ignore_case` and `contains_ignore_case` on the field compare with the
copy: in a load, a count, a `delete_all`, a grouped read and a patch's condition, on the root's own fields. Until
then, and for an empty value or a related node's field, they lowercase the property, as for any field: the same
Expand Down
14 changes: 9 additions & 5 deletions drivine/backend/oracle/oracle_save_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,9 +604,10 @@ def prelude(graph: OracleGraph, declarations: Sequence[str], lowers: bool = Fals

def _lower_node(nodes: str) -> str:
"""
`lower_node`: writes on the node the lowercased copy of each property `p_keys`, a JSON array, names, from what it
holds, and removes the copy of one that holds nothing, which an empty text is on Oracle. Oracle lowercases it, as it
lowercases what a lookup compares the copy with: see lower_copies. It is called once a write's change is told, so
`lower_node`: writes on the node the lowercased copy of each property `p_keys`, a JSON array, names as the node
holds it (see held_key), from what it holds, under the user's name (`__drivine.lower.$mail` for `$$mail`), and
removes the copy of one that holds nothing, which an empty text is on Oracle. Oracle lowercases it, as it lowercases
what a lookup compares the copy with: see lower_copies. It is called once a write's change is told, so
the copies are no part of it. The copy is read and written as a CLOB, so a text past what a VARCHAR2 holds has its
copy too.
"""
Expand All @@ -617,17 +618,20 @@ def _lower_node(nodes: str) -> str:
o JSON_OBJECT_T;
lowered JSON_ARRAY_T := JSON_ARRAY_T.parse(p_keys);
k VARCHAR2(4000);
c VARCHAR2(4000);
v CLOB;
BEGIN
SELECT props INTO held FROM {nodes} WHERE nid = p;
o := JSON_OBJECT_T(held);
FOR i IN 0 .. lowered.get_size - 1 LOOP
k := lowered.get_string(i);
-- k is the property as the node holds it; its copy is named for the user's name, $mail for $$mail.
c := '{lower_copies.PREFIX}' || CASE WHEN SUBSTR(k, 1, 2) = '$$' THEN SUBSTR(k, 2) ELSE k END;
v := NULL;
IF o.has(k) AND NOT o.get(k).is_null THEN v := LOWER(o.get_clob(k)); END IF;
-- Oracle keeps an empty text as null, so an empty property has no copy.
IF v IS NULL OR LENGTH(v) = 0 THEN o.remove('{lower_copies.PREFIX}' || k);
ELSE o.put('{lower_copies.PREFIX}' || k, v); END IF;
IF v IS NULL OR LENGTH(v) = 0 THEN o.remove(c);
ELSE o.put(c, v); END IF;
END LOOP;
-- An object type's methods are PL/SQL's: called in SQL, they are refused (ORA-40573).
held := o.to_json;
Expand Down
5 changes: 4 additions & 1 deletion drivine/backend/oracle/oracle_schema_grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
catalog_properties,
catalog_record,
)
from drivine.backend.sql.value_layout import held_key
from drivine.model import lower_copies
from drivine.schema.full_text_index_spec import FullTextIndexSpec
from drivine.schema.lower_copy_statements import LOWER_COPY_KIND, LowerCopyStatements, Recording, catalog_entries
Expand Down Expand Up @@ -165,8 +166,10 @@ def _lower_copies(graph: OracleGraph) -> LowerCopyStatements:
"""

def fill(label: str, property: str, batch: int) -> str:
# The copy is named for the user's name, and the value read where the node holds it, $$mail for $mail
# (drivine-cypher-spec#355).
path = f"'$.{drivine4j_step(lower_copies.of(property))}'"
value = f"JSON_VALUE(n.props, '$.{drivine4j_step(property)}' RETURNING CLOB)"
value = f"JSON_VALUE(n.props, '$.{drivine4j_step(held_key(property))}' RETURNING CLOB)"
copy = f"JSON_VALUE(n.props, {path} RETURNING CLOB)"
return f"""DECLARE
v_written NUMBER;
Expand Down
10 changes: 7 additions & 3 deletions drivine/backend/postgres/postgres_schema_grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
catalog_record,
)
from drivine.backend.sql.sql_graph import sql_text
from drivine.backend.sql.value_layout import held_key
from drivine.model import lower_copies
from drivine.schema.full_text_index_spec import FullTextIndexSpec
from drivine.schema.lower_copy_statements import LOWER_COPY_KIND, LowerCopyStatements, Recording, catalog_entries
Expand Down Expand Up @@ -80,18 +81,21 @@ def _lower_copies(graph: PostgresGraph) -> LowerCopyStatements:
"""

def fill(label: str, property: str, batch: int) -> str:
# The copy is named for the user's name, and the value read where the node holds it, $$mail for $mail
# (drivine-cypher-spec#355).
copy_key = sql_text(lower_copies.of(property))
held = held_key(property)
return "\n".join(
[
"WITH written AS (",
f" UPDATE {graph.nodes} n",
f" SET props = CASE WHEN n.props ->> {sql_text(property)} IS NULL THEN n.props - {copy_key}",
f" SET props = CASE WHEN n.props ->> {sql_text(held)} IS NULL THEN n.props - {copy_key}",
f" ELSE n.props || jsonb_build_object({copy_key}, lower(n.props ->> "
f"{sql_text(property)})) END",
f"{sql_text(held)})) END",
" WHERE n.nid IN (",
f" SELECT m.nid FROM {graph.nodes} m",
f" WHERE {has_labels('m', [label])} AND {text_of('m', lower_copies.of(property))} IS DISTINCT "
f"FROM lower({text_of('m', property)})",
f"FROM lower({text_of('m', held)})",
f" LIMIT {batch})",
" RETURNING 1)",
'SELECT count(*) AS "written" FROM written',
Expand Down
10 changes: 10 additions & 0 deletions drivine/backend/sql/value_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ def held_key(name: str) -> str:
return f"${name}" if name.startswith("$") else name


def user_key(held: str) -> str:
"""
The user's name of a property the store holds as `held`, undoing held_key: `$mail` for `$$mail`. A name held with a
`$` begins with `$$`; one that begins with a single `$` is no held name, and is given back as it is. The lowercased
copy of a property is named for the user's name (lower_copies.of), as each lookup and the ignore-case index read it
(liberation-data/drivine-cypher-spec#355).
"""
return held[1:] if held.startswith("$$") else held


def write(value: Any, store: SqlStore) -> Any:
"""`value` as a save writes it on `store` (see the module): as it is, or the module's text of it, `Held`."""
made = prepared(value)
Expand Down
2 changes: 1 addition & 1 deletion drivine/backend/sqlite/sqlite_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
ENTRY = "sqlite3_drivinecypher_init"
"""The extension's entry point in the module's library."""

HOST_VERSION = 2
HOST_VERSION = 3
"""The version of the host functions' forms compiled SQL expects: the module's `SqliteFunctions.HOST_VERSION`."""

PACKAGE = "drivine-cypher-compiler"
Expand Down
8 changes: 6 additions & 2 deletions drivine/backend/sqlite/sqlite_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

import apsw

from drivine.backend.sql.value_layout import held_key
from drivine.backend.sqlite import sqlite_cypher_functions, sqlite_extension, sqlite_graph
from drivine.backend.sqlite.sqlite_arguments import text as text_of_argument
from drivine.backend.sqlite.sqlite_graph import SqliteGraph, has_label, path, text_of
Expand Down Expand Up @@ -136,14 +137,17 @@ def _lower_copies(
if graph is None or label is None or property is None:
raise ValueError("drivine_lower_copies names a graph, a label and a property.")
nodes = SqliteGraph(graph).nodes
# The copy is named for the user's name, and the value read where the node holds it, $$mail for $mail
# (drivine-cypher-spec#355).
held = held_key(property)
copy = lower_copies.of(property)

def lowered(alias: str) -> str:
return f"{sqlite_graph.LOWER}({text_of(alias, property)})"
return f"{sqlite_graph.LOWER}({text_of(alias, held)})"

connection.execute(
f"UPDATE {nodes} AS n\n"
f"SET props = CASE WHEN {text_of('n', property)} IS NULL THEN json_remove(n.props, {path(copy)}) "
f"SET props = CASE WHEN {text_of('n', held)} IS NULL THEN json_remove(n.props, {path(copy)}) "
f"ELSE json_set(n.props, {path(copy)}, {lowered('n')}) END\n"
"WHERE n.nid IN (\n"
f" SELECT m.nid FROM {nodes} m\n"
Expand Down
14 changes: 9 additions & 5 deletions drivine/backend/sqlite/sqlite_plan_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import apsw

from drivine.backend.sql.value_layout import user_key
from drivine.backend.sql.write_plan import WriteReturns
from drivine.backend.sqlite import exact_json
from drivine.backend.sqlite.sqlite_graph import SqliteGraph, has_labels
Expand Down Expand Up @@ -584,20 +585,23 @@ def _set_and_unset(o: dict[str, Any], step: dict[str, Any]) -> None:

def _lowered(o: dict[str, Any], keys: Any) -> dict[str, Any]:
"""
`o` with the lowercased copy of each property `keys` names, from what `o` holds, and without the copy of one that
holds nothing: see lower_copies. It is lowercased as the lower function lowercases what a lookup compares the copy
with. `o` itself where `keys` names none.
`o` with the lowercased copy of each property `keys` names as the node holds it (see held_key), from what `o`
holds, and without the copy of one that holds nothing: see lower_copies. The copy is named for the user's name,
`__drivine.lower.$mail` for `$$mail` (see user_key). It is lowercased as the lower function lowercases what a
lookup compares the copy with. `o` itself where `keys` names none.
"""
names = _strings(keys)
if not names:
return o
copied = dict(o)
for key in names:
# Each key is the property as the node holds it; its copy is named for the user's name
# (drivine-cypher-spec#355).
value = copied.get(key)
if value is None:
copied.pop(lower_copies.of(key), None)
copied.pop(lower_copies.of(user_key(key)), None)
else:
copied[lower_copies.of(key)] = _as_text(value).lower()
copied[lower_copies.of(user_key(key))] = _as_text(value).lower()
return copied


Expand Down
6 changes: 5 additions & 1 deletion drivine/model/lower_copies.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@


def of(property: str) -> str:
"""The property the copy of `property`, a stored name, is stored under."""
"""
The property the copy of `property`, a stored name, is stored under. The name is the one after `GraphProperty`, not
as a SQL store's layout holds it: the copy of `$mail`, held as `$$mail`, is `__drivine.lower.$mail`
(drivine-cypher-spec#355).
"""
return f"{PREFIX}{property}"


Expand Down
29 changes: 24 additions & 5 deletions drivine/schema/lower_copy_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@

from drivine.drivine_error import DrivineError
from drivine.schema.full_text_index_spec import FullTextIndexSpec
from drivine.schema.lower_copy_statements import LOWER_COPY_BATCH, LowerCopyStatements, column_of
from drivine.schema.lower_copy_statements import (
CYPHER_LOWER_COPIES,
LOWER_COPY_BATCH,
LowerCopyStatements,
column_of,
)
from drivine.schema.range_index_spec import RangeIndexSpec
from drivine.schema.schema_specs import item_name, lowercased
from drivine.schema.uniqueness_constraint_spec import UniquenessConstraintSpec
Expand Down Expand Up @@ -84,7 +89,7 @@ async def fill_in(self, label: str, properties: Sequence[str], again: bool) -> N
if not properties:
return
stored: set[tuple[str, str]] = set() if again else await self._stored()
for property in [it for it in properties if again or (label, it) not in stored]:
for property in [it for it in properties if again or self._healed(it) or (label, it) not in stored]:
filled = 0
while True:
rows = await self._run(self._statements.fill(label, property, self._batch), None)
Expand All @@ -98,16 +103,30 @@ async def fill_in(self, label: str, properties: Sequence[str], again: bool) -> N
recording = self._statements.record(label, property)
await self._run(recording.statement, recording.bindings)
self._recorded.add((label, property))
logger.info(
# A $-named property is filled in again on every ensure (see _healed): one that wrote nothing is no news.
logger.log(
logging.DEBUG if filled == 0 and self._healed(property) else logging.INFO,
"Filled in the lowercased copy of %s.%s on %d node(s), and recorded that every node has it",
label,
property,
filled,
)

async def stored(self) -> set[tuple[str, str]]:
"""The lowercased copies the store records as filled in, each `(label, property)`, read now."""
return await self._stored()
"""
The lowercased copies the store records as filled in, each `(label, property)`, read now, but for those to fill
in again though recorded (see _healed): the schema planner's `ReadLowerCopies`, which fills in only what this
leaves out. A lookup reads the whole record (see filled_in).
"""
return {it for it in await self._stored() if not self._healed(it[1])}

def _healed(self, property: str) -> bool:
"""
Whether `property` is filled in again though recorded: on a SQL store, one named with a `$`. One saved before
drivine-cypher-spec#355 held its copy under the escaped name, `__drivine.lower.$$mail`, which no lookup reads,
or held none; the fill writes only the nodes whose copy is out of step. The graph engines always named it right.
"""
return self._statements is not CYPHER_LOWER_COPIES and property.startswith("$")

async def _stored(self) -> set[tuple[str, str]]:
"""What the store records, read now."""
Expand Down
29 changes: 24 additions & 5 deletions drivine/sync/schema/lower_copy_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@

from drivine.drivine_error import DrivineError
from drivine.schema.full_text_index_spec import FullTextIndexSpec
from drivine.schema.lower_copy_statements import LOWER_COPY_BATCH, LowerCopyStatements, column_of
from drivine.schema.lower_copy_statements import (
CYPHER_LOWER_COPIES,
LOWER_COPY_BATCH,
LowerCopyStatements,
column_of,
)
from drivine.schema.range_index_spec import RangeIndexSpec
from drivine.schema.schema_specs import item_name, lowercased
from drivine.schema.uniqueness_constraint_spec import UniquenessConstraintSpec
Expand Down Expand Up @@ -86,7 +91,7 @@ def fill_in(self, label: str, properties: Sequence[str], again: bool) -> None:
if not properties:
return
stored: set[tuple[str, str]] = set() if again else self._stored()
for property in [it for it in properties if again or (label, it) not in stored]:
for property in [it for it in properties if again or self._healed(it) or (label, it) not in stored]:
filled = 0
while True:
rows = self._run(self._statements.fill(label, property, self._batch), None)
Expand All @@ -100,16 +105,30 @@ def fill_in(self, label: str, properties: Sequence[str], again: bool) -> None:
recording = self._statements.record(label, property)
self._run(recording.statement, recording.bindings)
self._recorded.add((label, property))
logger.info(
# A $-named property is filled in again on every ensure (see _healed): one that wrote nothing is no news.
logger.log(
logging.DEBUG if filled == 0 and self._healed(property) else logging.INFO,
"Filled in the lowercased copy of %s.%s on %d node(s), and recorded that every node has it",
label,
property,
filled,
)

def stored(self) -> set[tuple[str, str]]:
"""The lowercased copies the store records as filled in, each `(label, property)`, read now."""
return self._stored()
"""
The lowercased copies the store records as filled in, each `(label, property)`, read now, but for those to fill
in again though recorded (see _healed): the schema planner's `ReadLowerCopies`, which fills in only what this
leaves out. A lookup reads the whole record (see filled_in).
"""
return {it for it in self._stored() if not self._healed(it[1])}

def _healed(self, property: str) -> bool:
"""
Whether `property` is filled in again though recorded: on a SQL store, one named with a `$`. One saved before
drivine-cypher-spec#355 held its copy under the escaped name, `__drivine.lower.$$mail`, which no lookup reads,
or held none; the fill writes only the nodes whose copy is out of step. The graph engines always named it right.
"""
return self._statements is not CYPHER_LOWER_COPIES and property.startswith("$")

def _stored(self) -> set[tuple[str, str]]:
"""What the store records, read now."""
Expand Down
8 changes: 4 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,25 +32,25 @@ falkordb = [
# Full-text search on a graph engine is written by the shared compiler too, which the graph engines' extras don't
# install, as it has no wheel for every platform they run on (an Intel Mac, musl Linux): `pip install
# "drivine[neo4j,compiler]"` where it has one. Pinned as the SQL stores' extras pin it.
compiler = ["drivine-cypher-compiler==0.54.4"]
compiler = ["drivine-cypher-compiler==0.56.0"]
# Each SQL store compiles Cypher with the shared compiler, drivine-cypher-compiler, a native library with a wheel for
# macOS on Apple Silicon, Linux with glibc (x86_64, aarch64) and Windows x64: in the extras, so `pip install drivine`
# installs anywhere and the graph engines work where it has no wheel (an Intel Mac, musl Linux). Pinned exactly, to the
# compiler of the Cypher spec tests/cypher is a copy of.
oracle = [
"oracledb>=3.0",
"drivine-cypher-compiler==0.54.4",
"drivine-cypher-compiler==0.56.0",
]
postgres = [
"psycopg[binary]>=3.2",
"psycopg-pool>=3.2",
"drivine-cypher-compiler==0.54.4",
"drivine-cypher-compiler==0.56.0",
]
# SQLite is apsw's, which bundles its own SQLite: 3.53.2 or later, which writes a float as text to 17 significant
# digits as compiled Cypher needs (3.53.0 and 3.53.1 still write 15), whatever SQLite Python was built with (#376).
sqlite = [
"apsw>=3.53.2",
"drivine-cypher-compiler==0.54.4",
"drivine-cypher-compiler==0.56.0",
]

[project.entry-points.pytest11]
Expand Down
Loading
Loading