Repository navigation
Provider: Apache AGE
The portability proof. Apache AGE is a PostgreSQL extension that adds an openCypher-compatible graph engine to a relational database; queries are issued as SQL that wraps Cypher inside a cypher(graph, $$...$$, params) table function. Where Neo4j is "Cypher over Bolt", AGE is Cypher-wrapped-in-SQL over Npgsql + agtype — sharing no driver code with Neo4j and exercising the framework's seam against a fundamentally different wire format.
Eager form (connection string known at registration):
using Microsoft.Extensions.DependencyInjection;
using OnixLabs.ElementFramework;
services.AddGraphContext<BlogGraphContext>(builder =>
builder.UseAge(
connectionString: "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=postgres",
graphName: "blog"));Lazy form (connection string resolved on first use — Testcontainers, secret-rotation, etc.):
services.AddGraphContext<BlogGraphContext>(builder =>
builder.UseAge(
connectionStringFactory: () => Environment.GetEnvironmentVariable("AGE_CONN_STRING")!,
graphName: "blog"));With logger factory:
services.AddGraphContext<BlogGraphContext>((sp, builder) =>
builder
.UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
.UseAge("Host=localhost;...", "blog"));The graphName is the AGE graph that nodes and edges live in. Created on first use if it doesn't already exist.
A process-wide ConcurrentDictionary<(connectionString, graphName), NpgsqlDataSource>. Npgsql's NpgsqlDataSource owns the connection pool — caching it per (connection-string, graph-name) pair means every AddGraphContext against the same endpoint and graph shares one pool.
Each cached data source is built with two crucial pieces of configuration:
-
Options=-c search_path=ag_catalog,publicbaked into the connection string. AGE installs itscypher()function andagtypetype under theag_catalogschema, and PostgreSQL's defaultsearch_pathdoesn't include it. Settingsearch_pathvia the connection string's startup-Optionsparameter applies before any query runs and survives across logical opens; doing the same via aSETin a physical-connection initializer doesn't always persist back to the pool. The emitter additionally schema-qualifiesag_catalog.cypher(...)so the SQL form is robust even when callers run with a different search path. -
A physical-connection initializer that runs
CREATE EXTENSION IF NOT EXISTS ageandSELECT create_graph(graph_name)if the graph doesn't already exist. AGE'sshared_preload_libraries = 'age'in the upstream container image meansLOAD 'age'is not needed per session.
No eviction — flagged in issue #5.
AgeCypherEmitter produces SQL-wrapped Cypher — the same Cypher body Neo4j would receive, wrapped in ag_catalog.cypher(...):
-- EmitAdd<Author>
SELECT * FROM ag_catalog.cypher('blog', $$
CREATE (n:Author { id: $id, name: $name, joinedAt: $joinedAt })
$$, @p) AS (n agtype)
-- EmitFindById<Author>
SELECT * FROM ag_catalog.cypher('blog', $$
MATCH (n:Author { id: $id }) RETURN n
$$, @p) AS (n agtype)The wrapped form takes parameters as a single agtype payload bound to SQL parameter @p (with NpgsqlDbType.Unknown — see below). The executor JSON-serializes the binder's parameter dictionary via AgtypeWriter and sends the whole bag as one parameter.
Two dialect deltas the emitter handles internally:
-
MERGE ... ON CREATE SET / ON MATCH SETis not implemented in AGE 1.6.0. Neo4j's emitter uses identical SET lists in both branches; the unconditionalMERGE ... SET ...form has the same observable semantics and AGE accepts it. -
countis a SQL reserved word. AGE rejects it as a column alias in the SQLAS (...)schema. The emitter renames the existence-count alias tocnt(matched byAgeResultMaterializer.CountAlias).
The executor is the only place in the provider that talks to Postgres. Its responsibilities:
- Open a connection — the ambient
AgeGraphTransactionif any, otherwise a freshNpgsqlConnectionborrowed from the cached data source. - Bind parameters: if the dictionary is non-empty, JSON-encode it via
AgtypeWriterand add as a single@pparameter withNpgsqlDbType.Unknown(so Postgres infersagtypeon its side — Npgsql doesn't ship anagtypewriter). -
Set
command.AllResultTypesAreUnknown = truebefore executing. This is the single most important line in the provider: it tells Npgsql to return every column as astringat the protocol level rather than trying to map it to a CLR type. Without it, theag_catalog.agtypecolumns AGE emits cannot be read at all — Npgsql doesn't ship anagtypereader, andGetValue/GetFieldValue<string>both throw. - Iterate the
NpgsqlDataReaderrow by row, projecting each cell asstring?.
Lazy async streaming follows the same pattern as Neo4j — await using holds the connection / command / reader for the lifetime of the enumerator and returns the connection to the pool on dispose. The sync path drains the same stream eagerly via GetAwaiter().GetResult(). Same deadlock caveat applies under captured sync contexts (issue #3).
AgeGraphTransactionOpener.Open() borrows an NpgsqlConnection from the cached data source, begins an NpgsqlTransaction on it, wraps both in AgeGraphTransaction, and stores the wrapper as the ambient transaction. The transaction wrapper drives NpgsqlTransaction.CommitAsync / RollbackAsync on the terminal call, then disposes the transaction and returns the connection to the pool.
Same one-ambient-at-a-time invariant and same dispose-path logging as Neo4j.
Rows reach the materializer as IReadOnlyDictionary<string, string?> (Npgsql in text mode). AgeResultMaterializer parses each agtype value via AgtypeReader:
-
Vertex and edge literals look like
{"id": 844424930131969, "label": "Author", "properties": {...}}::vertex(edges includestart_id/end_idand use::edge). The reader strips the suffix tag and parses the body as JSON viaJsonDocument. -
Scalars come back as JSON literals: strings quoted (
"Alice"), numbers bare (42,3.14), booleans / nulls bare.JsonDocumentdistinguishes these viaJsonValueKind. Integers are detected withTryGetInt64.
CLR conversion is the inverse of AgePropertySerializer: ISO-8601 string → DateTimeOffset / DateTime, hyphenated string → Guid, member-name string → enum, primitive coercion via Convert.ChangeType under invariant culture.
AgtypeWriter is the symmetric send-side: it takes the binder's parameter dictionary and produces an agtype JSON object suitable for the @p parameter. Values are expected to have already been flattened by AgePropertySerializer so the writer only sees JSON-friendly primitives.
The four raw-statement conformance tests are skipped against AGE — they send bare openCypher into RawStatement.Execute, and AGE's raw surface is SQL-wrapped Cypher. Every other conformance test passes against apache/age:release_PG16_1.6.0 via Testcontainers.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OnixLabs.ElementFramework;
ServiceCollection services = new();
services.AddLogging(builder => builder.AddConsole());
services.AddGraphContext<BlogGraphContext>((sp, builder) =>
builder
.UseLoggerFactory(sp.GetRequiredService<ILoggerFactory>())
.UseAge(
"Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=postgres",
"blog"));
await using ServiceProvider provider = services.BuildServiceProvider();
using IServiceScope scope = provider.CreateScope();
BlogGraphContext context = scope.ServiceProvider.GetRequiredService<BlogGraphContext>();
Author ada = new() { Id = Guid.NewGuid(), Name = "Ada", JoinedAt = DateTimeOffset.UtcNow };
context.Nodes<Author>().Add(ada);
await context.SaveChangesAsync();
Author? loaded = context.Nodes<Author>().FindById(ada.Id);
Console.WriteLine($"Loaded: {loaded?.Name}");