moonbit-pg-bridge

    Experimental community PostgreSQL adapter for moondb

    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    16 hours ago
    Downloads
    13

    #MoonBit PostgreSQL Bridge

    An experimental MoonBit adapter that lets code written against moonbitstack/moondb.AsyncDriver use the moonbit-community/postgres/client PostgreSQL driver. The bridge maps parameters, rows, and errors to moondb types, manages PostgreSQL transactions and savepoints, and streams result rows through the moondb cursor interface.

    #Installation

    Use the MoonBit toolchain with moonc 1.0.0-rc1 or later. The native and classic Wasm checks use moonc v1.0.0-rc1+3c0520448.

    Build from a fresh checkout.

    git clone https://github.com/kaigeliang/moonbit-pg-bridge.git cd moonbit-pg-bridge moon update moon build --target native

    After version 0.1.0 is released on Mooncakes, add it from your MoonBit module.

    moon add kaigeliang/moonbit-pg-bridge@0.1.0

    #Quick demo

    With PostgreSQL's initdb, pg_ctl, and pg_isready on PATH, run either target from the repository root. Both targets were verified on macOS with PostgreSQL 17.10.

    scripts/integration.sh --demo PG_BRIDGE_TARGET=wasm scripts/integration.sh --demo

    The demo opens a temporary PostgreSQL cluster and imports the bridge from a separate consumer module. A duplicate order raises SQLSTATE 23505, rolling back the savepoint. The outer transaction commits, and the demo reads its result through AsyncDriver::query_stream.

    Duplicate order rejected (23505). Savepoint rolled back. Streamed committed orders: 1, 3

    See the runnable MoonBit example for the full flow.

    #Usage and ownership

    Create the community client, spawn its executor, wait for ready(), and pass the client to Bridge::new. Keep the executor running until the bridge closes and use the bridge as the exclusive owner of that client. The independent consumer shows setup and calls through &@db.AsyncDriver.

    #Scoped transactions and savepoints

    Use Bridge::with_transaction for a callback that owns the connection until it returns. Call execute and query on the supplied TransactionScope. The bridge commits on normal return and forwards the callback result. On failure it rolls back and propagates the callback error.

    TransactionScope::with_savepoint gives a nested callback its own handle. On success it releases the savepoint. On failure it rolls back and releases the savepoint. If the outer callback catches the error, it can continue and commit its other work. The same name can be reused at different nesting levels. Names are quoted PostgreSQL identifiers of 1–63 UTF-8 bytes and may contain spaces or quotes. NUL is rejected.

    ///|
    let rows = bridge.with_transaction(tx => {
    tx.execute("CREATE TEMP TABLE demo_items (id int) ON COMMIT DROP", [])
    |> ignore
    tx.with_savepoint("add item", child => {
    child.execute("INSERT INTO demo_items VALUES ($1)", [Int(7)]) |> ignore
    })
    tx.query("SELECT id FROM demo_items", [])
    })

    Pass options=@pg.TransactionOptions(isolation_level=RepeatableRead, read_only=true) when the operation needs explicit transaction settings. While a scope runs, use only the innermost active handle. The bridge rejects calls through the base driver, suspended parent handles, expired handles, and overlapping SQL operations. Transaction control in a scope goes through the callback API.

    If PostgreSQL rejects a statement, the bridge marks that scope failed. Even if the callback catches the statement error and returns successfully, the bridge rolls back the failed scope and reports a QueryError. A cancellation between database operations rolls back the scope. Cancellation during an active database operation discards the connection. Keep any tasks using a scope within its callback lifetime. If active work outlives that callback, the bridge aborts the connection. A failure during commit can leave the outcome unknown.

    #Streaming rows

    Use AsyncDriver::query_stream(sql, params) to receive a cursor, then call next() until it returns None. The PostgreSQL client applies backpressure through bounded response queues, and the bridge converts each row as the caller requests it. query returns an array when the caller needs all rows.

    The cursor owns the bridge connection until end of stream or close(). On early close, the bridge drains unread responses and releases the connection. Drain time depends on the underlying query. Cancelling a read in progress discards the connection. Read to the end to observe server errors that are reported after earlier rows.

    Inside a managed transaction, use TransactionScope::with_stream(sql, params, f). It closes the cursor on callback exit. If the callback returns normally and PostgreSQL reports an error while the remaining results drain, the error is returned to the caller and the transaction or savepoint can roll back.

    #Explicit transactions

    The moondb AsyncDriver methods begin, commit, and rollback are available for callers that manage the transaction lifecycle. Within an explicit transaction, Bridge::with_savepoint runs a bounded callback and then returns control to the caller. The bridge also supports savepoint recovery through moondb's nested AsyncTxn::run. Callers using explicit transactions are responsible for coordinating access between begin and completion.

    An unrecovered PostgreSQL error in an explicit transaction makes a later commit roll back and return a QueryError. Server errors retain SQLSTATE, severity, detail, and hint. Errors establishing or completing a transaction discard the connection. close is idempotent and aborts a connection with active work or an open transaction.

    #Type and operation support

    Inputs are Null, Bool, Int, Int64, Double, Text, Blob, and Json. The upstream client checks each parameter against the PostgreSQL type. Outputs include BOOL, INT2, INT4, INT8, FLOAT4, FLOAT8, TEXT, VARCHAR, BYTEA, JSON and JSONB with SQL NULL. Other types, including NUMERIC, dates, UUID and arrays, return a type error. JSON binding preserves number representations. JSONB may normalize whitespace and key order. Columns keep their order and names.

    SQL uses PostgreSQL $1, $2, … placeholders. Use INSERT ... RETURNING to get an inserted key. last_insert_id is zero. The bridge reports support for transactions, savepoints, and RETURNING.

    #Reproduce the checks and PostgreSQL tests

    With the PostgreSQL tools on PATH, run the same checks as CI.

    for target in native wasm; do moon check --target "$target" --deny-warn moon build --target "$target" moon test --target "$target" PG_BRIDGE_TARGET="$target" scripts/integration.sh done

    Each script run starts a temporary PostgreSQL cluster on loopback port 55438, runs seven database scenarios, an independent consumer test, and the demo on the requested target, and stops the server on exit. Set PG_BRIDGE_PORT to use another port. The consumer imports the bridge from a temporary workspace populated from the checkout. Direct moon test runs the database scenarios only when PG_BRIDGE_INTEGRATION=1 is set.

    The database scenarios cover parameter and row conversions, transaction commit and rollback, nested savepoint release, recovery from SQL errors, SQLSTATE propagation, access from expired or suspended handles, and cancellation both between and during SQL operations. Streaming cases also check early close, connection reuse, type-conversion errors, and a savepoint recovering from an error detected while draining the response.

    The adapter uses moondb for the consumer interface and the community PostgreSQL client for the wire protocol. The bridge is licensed under Apache 2.0.

    #MoonBit implementation size

    The table covers the bridge library and excludes blank lines, whole-line comments, tests, the demo, generated interfaces, and dependencies.

    FileImplementation lines
    bridge.mbt274
    transaction.mbt204
    scope_sql.mbt91
    stream.mbt128
    Total697

    awk 'NF && $1 !~ /^\/\// { ++lines[FILENAME]; ++total } END { for (i = 1; i < ARGC; ++i) print ARGV[i], lines[ARGV[i]] print "total", total }' bridge.mbt transaction.mbt scope_sql.mbt stream.mbt

    Bridge

    pub struct Bridge {
    client :
    Client

    closed : Bool
    busy : Bool
    // private fields
    }

    A bridge owns an already-running community PostgreSQL client. Callers must keep its executor alive and serialize access to this bridge.

    Bridge::with_savepoint

    async fn[T] Bridge::with_savepoint(self : Bridge, name : String, f : async (TransactionScope) -> T) -> T

    Run a savepoint callback within a transaction opened through AsyncDriver::begin. Finishing the savepoint leaves that transaction open.

    Bridge::with_transaction

    async fn[T] Bridge::with_transaction(self : Bridge, f : async (TransactionScope) -> T, options? :
    TransactionOptions
    ) -> T

    Run a callback in a new transaction. The bridge commits on success and rolls back on callback failure. Use the supplied handle for all SQL in the transaction. The callback's return value or error is propagated.

    TransactionScope

    pub struct TransactionScope {
    // private fields
    }

    A transaction handle valid while its callback is running and no child savepoint owns the connection.

    TransactionScope::execute

    Execute a statement using this scope's connection and bound parameters.

    TransactionScope::query

    Read and materialize all rows using this scope's connection.

    TransactionScope::with_savepoint

    async fn[T] TransactionScope::with_savepoint(self : TransactionScope, name : String, f : async (TransactionScope) -> T) -> T

    Run a nested callback under a PostgreSQL savepoint. The parent handle is suspended until the callback finishes and the savepoint is resolved.

    TransactionScope::with_stream

    async fn[T] TransactionScope::with_stream(self : TransactionScope, sql : String, params : Array[
    Value
    ], f : async (&
    AsyncCursor
    ) -> T) -> T

    Consume rows within a transaction callback. Unread rows are drained before the transaction scope resumes, including when the callback raises.