This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
lean-pq is a Lean 4 library providing bindings to PostgreSQL's libpq C client library via Lean's FFI. It enables Lean programs to connect to and query PostgreSQL databases.
- Lean version:
leanprover/lean4:v4.24.0(pinned inlean-toolchain) - Build system: Lake
- No external Lean package dependencies
lake build # Build library + extern static lib (default targets)
lake test # Run test suite (requires running PostgreSQL)
lake exe examples # Run examples
lake clean # Clean build artifactslibpqmust be installed (libpq-devon Ubuntu,libpqvia Homebrew on macOS)pkg-configmust be available (used to locate libpq headers and link flags)
Tests require a PostgreSQL instance on localhost:5432 with user postgres, password test:
docker compose -f Tests/docker-compose.yml up -dThe library follows a two-layer FFI pattern:
- Lean declarations (
LeanPq/Extern.lean): Opaque types and@[extern "lean_pq_<name>"]function declarations. All FFI functions returnEIO LeanPq.Error T. - C implementations (
LeanPq/extern.c): CorrespondingLEAN_EXPORT lean_obj_res lean_pq_<name>(...)functions wrapping libpq calls.
Key conventions:
- Opaque
HandlewrapsPGconn*with a Lean external class and finalizer (PQfinish) - Opaque
PGresultwrapsPGresult*with finalizer (PQclear) - Lean inductive types for enums (
ConnStatus,ExecStatus,PGTransactionStatus) must have constructors ordered to match C enum ordinals exactly — the C side returns raw integers - Error handling uses
LeanPq.Error(defined inLeanPq/Error.lean) withlean_io_result_mk_ok/lean_io_result_mk_error
LeanPq.lean— Root module, re-exportsDataTypeandExternLeanPq/DataType.lean— Pure Lean inductive type modeling all PostgreSQL data types (Chapter 8 of PG docs)LeanPq/Extern.lean— All@[extern]opaque declarations + status enum typesLeanPq/Error.lean—LeanPq.Errorinductive typeLeanPq/extern.c— C FFI implementations (~700 lines)LeanPq/Table.lean— Placeholder for future higher-level table abstraction (currently empty)
Platform-aware linking: macOS uses pkg-config --libs libpq, Linux uses ldconfig to locate libpq.so. The C file is compiled into libextern.a via a custom extern_lib target with pkg-config --cflags libpq for include paths.