Skip to content

Provider: Apache AGE

matthew edited this page May 12, 2026 · 1 revision

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.

Composition root

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.

Data-source caching: AgeDataSourceCache

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,public baked into the connection string. AGE installs its cypher() function and agtype type under the ag_catalog schema, and PostgreSQL's default search_path doesn't include it. Setting search_path via the connection string's startup-Options parameter applies before any query runs and survives across logical opens; doing the same via a SET in a physical-connection initializer doesn't always persist back to the pool. The emitter additionally schema-qualifies ag_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 age and SELECT create_graph(graph_name) if the graph doesn't already exist. AGE's shared_preload_libraries = 'age' in the upstream container image means LOAD 'age' is not needed per session.

No eviction — flagged in issue #5.

SQL-wrapped Cypher emission

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 SET is not implemented in AGE 1.6.0. Neo4j's emitter uses identical SET lists in both branches; the unconditional MERGE ... SET ... form has the same observable semantics and AGE accepts it.
  • count is a SQL reserved word. AGE rejects it as a column alias in the SQL AS (...) schema. The emitter renames the existence-count alias to cnt (matched by AgeResultMaterializer.CountAlias).

Execution: AgeRawStatementExecutor

The executor is the only place in the provider that talks to Postgres. Its responsibilities:

  1. Open a connection — the ambient AgeGraphTransaction if any, otherwise a fresh NpgsqlConnection borrowed from the cached data source.
  2. Bind parameters: if the dictionary is non-empty, JSON-encode it via AgtypeWriter and add as a single @p parameter with NpgsqlDbType.Unknown (so Postgres infers agtype on its side — Npgsql doesn't ship an agtype writer).
  3. Set command.AllResultTypesAreUnknown = true before executing. This is the single most important line in the provider: it tells Npgsql to return every column as a string at the protocol level rather than trying to map it to a CLR type. Without it, the ag_catalog.agtype columns AGE emits cannot be read at all — Npgsql doesn't ship an agtype reader, and GetValue / GetFieldValue<string> both throw.
  4. Iterate the NpgsqlDataReader row by row, projecting each cell as string?.

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).

Transactions

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.

Materialization

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 include start_id / end_id and use ::edge). The reader strips the suffix tag and parses the body as JSON via JsonDocument.
  • Scalars come back as JSON literals: strings quoted ("Alice"), numbers bare (42, 3.14), booleans / nulls bare. JsonDocument distinguishes these via JsonValueKind. Integers are detected with TryGetInt64.

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.

Conformance

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.

Full example

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}");

Clone this wiki locally