[{"data":1,"prerenderedAt":4},["ShallowReactive",2],{"7tn7AxFe9q":3},"# ladybug-lean\n\n**Website: [volland.github.io/ladybug-lean](https://volland.github.io/ladybug-lean/)** · [Guide](https://volland.github.io/ladybug-lean/guide.html) · [Mini book](https://volland.github.io/ladybug-lean/book.html) · [Example](examples/agent-memory)\n\nA Lean 4 library for [LadybugDB](https://github.com/LadybugDB/ladybug), the embedded graph database, with:\n\n- **typed Cypher**: queries are checked against your schema when you compile, written either with a monadic builder or as Cypher text (`cypher%`);\n- **a repository layer**: insert, upsert, get, update, delete, link, traverse and bulk-load the Lean structures you declare as tables;\n- **two backends behind one interface**: the native Ladybug database, and a pure in-memory graph that runs the same programs in `#eval` and in unit tests;\n- **vector and full-text search**, variable-length and shortest paths, subqueries and unions.\n\n```lean\nimport Ladybug\nimport LadybugNative\nopen Ladybug\n\nstructure Person where\n  id : Int64\n  name : String\n  age : Option Int64\n\nstructure Company where\n  name : String\n\nstructure WorksAt where\n  since : Int64\n\nnode_table Person\nnode_table Company (key := name)\nrel_table WorksAt (from := Person) (to := Company)\n\ndef schema : Schema := [.ofNode Person, .ofNode Company, .ofRel WorksAt]\n\n-- Written once, runs on any backend.\ndef demo {m : Type → Type} [MonadGraph m] : m (Array (String × Option String)) := do\n  applySchema schema\n  Repo.insert (Person.mk 1 \"Ann\" (some 41))\n  Repo.insert (Person.mk 2 \"Bob\" none)\n  Repo.insert (Company.mk \"ACME\")\n  Repo.link (1 : Int64) (WorksAt.mk 2020) \"ACME\"\n  runQuery (cypher% MATCH (p:Person) OPTIONAL MATCH (p)-[:WorksAt]->(c:Company)\n                    RETURN p.name, c.name ORDER BY p.name)\n\n#eval (demo : MemM _).run' {}          -- in memory, no native library needed\n\ndef main : IO Unit := Ladybug.withDatabase \"./company.lbug\" fun db => db.withConnection do\n  IO.println (← demo)                   -- on the Ladybug database\n```\n\n## Installing\n\nAdd the package to your `lakefile.lean`:\n\n```lean\nrequire ladybug from git \"https://github.com/Volland/ladybug-lean\" @ \"main\"\n```\n\nThe first build downloads the official Ladybug library for your platform (macOS, Linux and Windows on x86_64 and arm64) at the version in `lbug.lock`, into `.lake/lbug/`. The library is loaded at runtime from that path, so you don't need to set an rpath or a library search path.\n\n- `lake run lbug-update` moves `lbug.lock` to the latest Ladybug release.\n- `LBUG_LIB_DIR=/path/to/dir` builds against a local Ladybug build instead of downloading one; the directory needs `lbug.h` and the shared library.\n- `LBUG_LIBRARY=/path/to/liblbug.so` overrides the library file at runtime.\n\nToolchain: Lean `v4.35.0`. Building the C shim needs a C compiler: the system `cc` on macOS and Linux, MinGW-w64 `gcc` on Windows (for example from MSYS2's UCRT64 environment); `CC` overrides it.\n\n## Libraries\n\n| Import | What it contains | Native library |\n|---|---|---|\n| `Ladybug` | values and decoding, schema commands, the typed Cypher language, `cypher%`, the repository, search, `MonadGraph`, the in-memory backend `MemM` | no |\n| `LadybugNative` | the native backend: `Database`, `Connection`, `LbugM`, raw Cypher text, timeouts, file import | yes |\n\n## Declaring tables\n\n`node_table T` makes a structure a node table. The label defaults to the structure's name and the key to a field called `id`; use `(key := field)` and `(label := \"Name\")` in any order to change them. `rel_table R (from := A) (to := B)` declares a relationship table, and a structure with no fields is a relationship without properties.\n\nThe commands check every field's type at compile time and generate:\n\n- decoders and encoders;\n- `T.Var`, the query variable of the table, whose fields are typed property expressions (`p.age : Expr (Option Int64)`);\n- `T.OptVar`, the same with every property nullable, for OPTIONAL MATCH.\n\nColumn types: `Bool`, all signed and unsigned integer widths, `Int` (INT128), `Float`, `Float32`, `String`, `ByteArray`, `Uuid`, `Date`, `Timestamp`, `Interval`, `Option α`, `Array α`, `Embedding n` (`FLOAT[n]`), and structures that derive `Ladybug.CypherType`.\n\n## Writing queries\n\nThe builder and `cypher%` produce the same query:\n\n```lean\ndef employees : Query (String × String) := query do\n  let p ← match_ (node Person)\n  let (_, c) ← match_ (out p WorksAt (node Company))\n  where_ (p.age >. 30)\n  return_ (p.name, c.name)\n\ndef employees' := cypher% MATCH (p:Person)-[:WorksAt]->(c:Company) WHERE p.age > 30 RETURN p.name, c.name\n```\n\n- **NULL is in the types.** Comparisons and connectives have type `Expr (Option Bool)`, and WHERE keeps only rows that are true. Use `coalesce`, `isNull`, `isTrue` to leave three-valued logic.\n- **Lean values are always parameters.** `lit x`, numerals, and `$x` / `$(e)` inside `cypher%` are sent as query parameters, never spliced into the text.\n- **Mistakes are compile errors**, reported at the Cypher token: an unknown label or property (with a \"did you mean\"), a comparison of a string with a number, or a relationship pattern whose endpoints don't match its table.\n- Operators end in a dot: `==.` `!=.` `\u003C.` `\u003C=.` `>.` `>=.` `&&.` `||.` `+.` `-.` `*.` `/.` `%.` `++.`.\n- Patterns: `out p R (node T)`, `inc …`, `both …`, `matchPaths p Knows (node Person) (max := 3)`, `shortestPath`, `allShortestPaths`.\n- Subqueries and unions: `exists_ do …`, `countSub do …`, `q₁.union q₂`, `q₁.unionAll q₂`.\n- Search: `createVectorIndex`, `vectorSearch`, `createFtsIndex`, `ftsSearch`. The native backend installs and loads the `vector` and `fts` extensions on first use.\n\nIn `cypher%`, keywords may be upper, lower or capitalized case, strings are Lean string literals (`\"Ann\"`), and the clauses after the first must start at or right of the first clause's column.\n\n## Running\n\n- `runQuery q`, `runStmt s`, `withTx`, `withReadTx`, `applySchema`, `verifySchema` work on every `MonadGraph`.\n- On the native backend, `queryRaw`, `queryAs` and `exec` run Cypher text, `withTimeout ms` limits a query, `Connection.interrupt` stops one from another task, and `Repo.copyNodes`/`copyRels` load CSV or Parquet files.\n- Errors are a structured `Ladybug.Error`: `.query`, `.constraint`, `.notFound`, `.decode`, `.transaction`, `.timeout`, `.storageMismatch` and others.\n\n## Behaviour to know\n\n- The in-memory backend follows Ladybug's semantics where openCypher leaves a choice: NULL sorts as the largest value, `x IN [.., NULL]` is false rather than unknown, integer `/` and `%` truncate toward zero, variable-length patterns repeat relationships (walk semantics), and shortest paths never return to their start. A differential test suite checks this against Ladybug on generated graphs and queries.\n- Its full-text search uses BM25 and a Porter stemmer: it matches the same documents as Ladybug for ordinary queries, but scores are not identical.\n- Ladybug has no `CALL { … }` subqueries, so neither does the typed language.\n- A union value's member name is empty when the union has more than one member, because the C API does not report it.\n- Timeouts and interrupts take effect between Ladybug's units of work, so a query can overrun its timeout.\n\n## Example\n\n[`examples/agent-memory`](examples/agent-memory) is a small project that stores an AI agent's memory as a typed property graph: a schema of five tables, recall functions written once for both backends, checks that run while it compiles, and a native run on a LadybugDB file.\n\n## Development\n\n```sh\nlake build tests && .lake/build/bin/tests   # the full suite\nDIFF_CASES=3000 TEST_FILTER=differential .lake/build/bin/tests\nscripts/check-native-library.sh             # download caching, lbug-update, LBUG_LIB_DIR\n(cd examples/agent-memory && lake build AgentMemory && lake exe agent-memory)\n```\n\nThe website lives in `site/` (static HTML, deployed to GitHub Pages by `.github/workflows/pages.yml`); its Lean snippets are compiled and checked by `Tests/SiteSnippets.lean`.\n\nIntent lives in `tg.md/` (decisions, constraints and architecture, as a typed graph checked with `tg check`) and requirements in `openspec/specs/`; the milestones' changes are archived under `openspec/changes/archive/`.\n\n## License\n\nMIT; see [LICENSE](LICENSE). LadybugDB itself is distributed under its own license by the LadybugDB project.\n",1795286047152]