PostgreSQL language binding — 0.17.0 Developer Preview

This document describes the SDK 0.17.0 Developer Preview. The previously published 0.16.0 pool API remains available; transaction callbacks are the new capability. A source implementation, a passing adapter test and a verified downloadable SDK are separate milestones; see the versioned release report for exact artifact and platform evidence.

The first binding supports a complete single-record CRUD path with bound values, strict scalar/Optional conversion and verified TLS. It uses an internal bounded connection pool; the 0.17.0 adds an owned transaction callback. It does not expose transaction handles, pool configuration, migrations or multi-row query results. It is a Developer Preview, with no production-readiness or cross-platform claim.

Native API

CallResultContract
postgres_find(sql, RecordType)RecordType?!Query without parameters; zero rows is none, one row is some(record), more than one row is an error
postgres_find(sql, parameters, RecordType)RecordType?!Same result, with a flat record of bound values
postgres_execute(sql)Int!Execute a statement without parameters and return the affected-row count
postgres_execute(sql, parameters)Int!Execute a statement with bound values and return the affected-row count
postgres_transaction(handler [, arguments])Bool!Run a named Bool! handler with one exclusive transaction; optional record argument

postgres_execute rejects statements that return columns, including RETURNING; use postgres_find with a matching result record for a single returned row. Each call accepts one statement, not a batch.

These calls suspend cooperatively without await. They execute only in native applications. Browser Check can type-check supported source; browser Run cannot open a PostgreSQL connection and must report unsupported execution rather than simulate a successful query.

RecordType is the name of a declared record type, as with parse_json(text, RecordType). Both parameter and result records must be flat: Int, Bool, String, and Optional forms of those types. Nested records, lists, enums, decimal, timestamp and binary values are not supported by this binding.

Bind values in declaration order

type FindUser:
  id: Int

type User:
  id: Int
  name: String
  active: Bool
  bio: String?

fn load_user(id: Int) -> User?!:
  result = postgres_find("SELECT id, name, active, bio FROM threadone_users WHERE id = $1", FindUser(id: id), User) or fail "Database query failed"
  return result

The fields of the parameter record bind to $1, $2, and so on in **record declaration order**, regardless of constructor argument order. PostgreSQL determines each placeholder's database type from the statement. Use a SQL cast when the statement does not otherwise determine that type, for example $1::bigint or $1::text.

Values are sent separately from SQL. Text containing quotes or SQL-looking fragments remains a parameter value. Placeholders cannot represent table names, column names or SQL keywords; identifiers and SQL structure must come from application-controlled statements or a separately validated allowlist.

Exact conversion rules

ThreadOne fieldPostgreSQL representationRules
Int / Int?SMALLINT, INTEGER, BIGINTRead as signed 64-bit Int; parameter writes to smaller types must fit their range
Bool / Bool?BOOLEANNo numeric or text coercion
String / String?TEXT, VARCHARPreserve UTF-8 text and empty strings; no automatic conversion from other types
Optional noneSQL NULLPreserve the declared scalar kind; the placeholder must have a compatible supported database type

Result column count, order, names and supported types must match the result record. Select explicit columns and use SQL aliases when necessary. A schema mismatch remains an error even if the query returns no rows. Unsupported database types are rejected rather than silently narrowed or converted to strings.

An Optional parameter preserves its declared scalar kind even when its value is none. An Int? containing none may bind to an integer placeholder, but cannot bind to a TEXT placeholder. The same kind check applies to absent Bool? and String? values. PostgreSQL must still establish the placeholder type from the statement or an explicit cast.

A SQL NULL becomes none only for an Optional result field. NULL in a required field is an error. A present empty string is some(""), not absence. The outer Optional returned by postgres_find means that the entire row was absent; an inner Optional field represents SQL NULL in a row that exists.

Handle errors before absence

fn user_name(id: Int) -> String:
  result = load_user(id) or return "Database unavailable"
  user = result or return "User not found"
  return user.name

Use an application-specific error response rather than treating every error as a missing record. In an HTTP route the two stages can produce distinct responses:

route GET "/users/:id" (req):
  raw = req.param("id") or return 400 "Invalid user ID"
  text = raw or return 400 "Missing user ID"
  id = parse_int(text) or return 400 "Invalid user ID"
  found = load_user(id) or return 503 "Database unavailable"
  user = found or return 404 "User not found"
  return 200 user

Database diagnostics are redacted and the language does not yet expose structured SQLSTATE errors. A generic failure must not be interpreted as proof that a write did not happen.

Connection configuration and lifecycle

Set THREADONE_POSTGRES_URL outside source code. It accepts the PostgreSQL connection configuration used by the native adapter. TLS is required and verifies both the certificate chain and hostname. Unix-socket and host-address-only configurations are rejected because they do not provide the required TLS hostname verification path.

For a private certificate authority, set optional THREADONE_POSTGRES_CA_PEM to the PEM certificate text. This adds a trusted root while retaining hostname and chain verification; it is not a trust-all or plaintext switch. The URL is limited to 16 KiB and CA text to 64 KiB. Do not put credentials in source files, shared logs, documentation or Playground inputs.

Outside a transaction callback, each binding call leases a session from a bounded process pool. Successful calls reset it with ROLLBACK followed by DISCARD ALL before reuse. Reset failure discards the session while retaining a known-successful statement result. Separate calls outside a callback do not share temporary tables, session settings or a transaction. In particular, sending BEGIN, then another binding call, then COMMIT does not create a multi-call transaction. Use a permanent table in a dedicated disposable test database for the CRUD example. Use postgres_transaction to share an owned transaction across the callback’s database calls; manual BEGIN/COMMIT across independent binding calls is not a substitute.

Failed, timed-out or cancelled operations discard their session. There is no automatic statement retry. Disconnecting a client does not prove that PostgreSQL cancelled server work or rolled back a write already received. This also applies to a write with RETURNING executed through postgres_find: a result-limit or decoding error does not undo the write. A lost response can leave an unknown write outcome; reconcile it using application data and an explicit idempotency design before retrying.

Transaction callback — 0.17.0

postgres_transaction(handler) and postgres_transaction(handler, arguments) return Bool!. The handler must be a named function declared as fn handler() -> Bool! or fn handler(arguments: SomeRecord) -> Bool!, respectively. The optional argument must match that record type. It is evaluated once and its arena-backed values remain valid across cooperative suspension. It is an ordinary record passed to the handler, not automatically an SQL parameter list; only a record passed to postgres_find or postgres_execute is bound as SQL values. Anonymous callbacks, first-class function values, transaction handles and .one transaction options are not exposed.

The callback owns one exclusive pooled session. postgres_find and postgres_execute called from the callback, including from functions it calls, use that session. The context belongs to the current asynchronous task, so concurrent HTTP requests do not share a transaction merely because they execute on one application thread.

Callback outcomeTransaction behavior
return trueCommit, then return true if commit succeeds
return falseCommit, then return false if commit succeeds; false does **not** request rollback
fail "message" or an uncaught fallible errorRequest rollback and return an error; failed rollback causes session disposal
Database-operation failure, even when handled with orMark the transaction unusable and prevent commit
Nested postgres_transaction call, even when its error is handledReject nesting and prevent the outer transaction from committing
Cancellation or timeoutDispose the owned connection; no automatic statement or transaction retry

To roll back for an application rule, use fail; do not return false. A caught error from an ordinary application calculation does not by itself invalidate the transaction. Database errors and a nested transaction attempt do, including binding/schema/boundary failures before a statement completes. After that failure, later calls cannot rescue the transaction by returning true.

Inside the callback the supported SQL statement prefixes are SELECT, INSERT, UPDATE, DELETE and WITH. Statements are prepared singly; multiple-statement batches are rejected. Explicit BEGIN/COMMIT/ROLLBACK/SAVEPOINT, DDL such as CREATE/DROP, session commands, CALL and DO are rejected. Create the disposable example's table before entering the callback and drop it afterward. This restriction protects transaction ownership; it is not a SQL security sandbox or a guarantee that invoked SQL functions have no side effects. Keep SQL application-controlled and bind values.

The language uses PostgreSQL READ COMMITTED, READ WRITE. Isolation-level and read-only options available in the Rust adapter are not exposed through .one. READ COMMITTED does not give one unchanging snapshot across all statements; use appropriate database constraints, locking and application rules for your workload. Nested transactions and savepoints are not provided.

A transaction has a 30-second total cooperative deadline, including acquisition, callback and completion. Acquisition retains the pool's 5-second budget. Each database operation and transaction completion is bounded by five seconds or the remaining transaction lifetime, whichever is shorter. The existing statement/result/parameter limits still apply. Pool reset occurs after completion within the remaining lifetime; a known successful commit is not turned into an error just because subsequent session reset failed.

Before each callback database statement, the runtime sets local PostgreSQL statement_timeout to at most five seconds or the remaining lifetime and idle_in_transaction_session_timeout to the remaining lifetime. These server limits help bound work after disconnect; trusted SQL functions or SQL that changes session settings can affect them, so this remains outside a SQL security sandbox.

The client timers depend on the cooperative executor. They cannot preempt a CPU loop that never yields or a blocking operation. An HTTP handler may impose an earlier deadline. Cancellation/disposal aborts the local connection task; it does not prove when the server noticed the disconnect. An uncommitted transaction is rolled back by PostgreSQL when its session ends, but a cancellation or connection failure while awaiting COMMIT can leave an **unknown commit outcome**. Reconcile application state before retrying, and do not repeat external effects such as messages merely because a response was lost. Non-database effects are not undone by SQL rollback.

The runnable example [postgres-transaction.one](../sdk/examples/postgres-transaction.one) demonstrates successful false committing and explicit failure rolling back. It uses only a dedicated test table. Source checks, native fixtures and exact SDK release evidence must be recorded separately before publication.

Bounds and ownership

ResourceBinding limitScope
Active calls8Shared process admission
Waiting calls32Further calls fail admission
Acquisition5 secondsQueue, health probe and TLS connect; failure means the application statement did not start
Statement5 secondsExpiry may leave an unknown write outcome
Session reset5 secondsAdditional bounded cleanup after a successful statement
SQL text64 KiBUTF-8 bytes
Parameter count64Declaration-order values
Parameter text1 MiB aggregateBefore dispatch
Result columns1–64Unique nonempty names, each at most 256 UTF-8 bytes
postgres_find rows1A second row is an error, not silently ignored
Decoded result1 MiBChecked after driver decoding, before copying text into the application arena

The decoded-result budget counts UTF-8 string bytes, eight bytes per Int, and one byte per Bool or NULL; it does not measure actual allocation overhead. Result limits do not cap network-frame allocation, TLS buffers, driver metadata or total process RSS. Use a trusted server and bounded application queries. A row may have been buffered by the driver before the binding rejects it. Text returned into a ThreadOne record belongs to the current application/request arena and remains valid across cooperative suspension within that arena's lifetime.

For independent calls, the acquisition and statement deadlines are separate; a call can spend time waiting and then performing its operation. An HTTP handler may impose an earlier deadline. Cancellation releases local capacity and disposes the session, but cannot establish the final state of a potentially applied write.

Example and verification boundary

See [the native CRUD example](../sdk/examples/postgres.one) and [its setup notes](../sdk/examples/postgres-README.md). Run only against an explicitly selected disposable database; the example creates and deletes test data.

The release must separately record compiler checks, actual generated-program execution, verified-TLS/authentication rejection, NULL/type/boundary failures, cancellation and the exact packaged artifact checks. No test is claimed passed by this document. The fixture and validation report are the evidence, and ignored tests are not live-server passes.

PostgreSQL evidence does not establish MySQL, MariaDB, MongoDB, SQL Server, Redis or Dragonfly compatibility. Current Linux execution, if recorded, does not imply current Windows, macOS, ARM64 or clean-OS installation validation.

สรุปการใช้งานภาษาไทย

SDK 0.15.0 เพิ่ม postgres_find สำหรับค้นหา record หนึ่งรายการ และ postgres_execute สำหรับเพิ่ม แก้ไข หรือลบข้อมูล โดยส่งค่าผ่าน $1, $2 ตามลำดับฟิลด์ในชนิด record ของพารามิเตอร์ ห้ามต่อข้อความจากผู้ใช้ลง SQL โดยตรง รองรับ Int, Bool, String และ Optional ของทั้งสามชนิด ค่า none ยังคงชนิดที่ประกาศไว้

postgres_find คืนผลแบบ Record?!: ต้องจัดการข้อผิดพลาดชั้นแรก แล้วจึงจัดการกรณีไม่พบข้อมูล ถ้ามีมากกว่าหนึ่งแถวจะเป็นข้อผิดพลาด ชื่อและลำดับคอลัมน์ต้องตรงกับ record ที่ระบุ แม้ผลลัพธ์ไม่มีแถว

ตั้งค่า THREADONE_POSTGRES_URL และใช้ TLS ที่ตรวจใบรับรองและชื่อโฮสต์เสมอ หากเป็น CA ภายในให้ใส่เนื้อหา PEM ใน THREADONE_POSTGRES_CA_PEM คำสั่งที่อยู่นอก callback ยืม session แบบ exclusive จาก pool และล้าง state ก่อนคืน จึงไม่เก็บ transaction หรือ temporary table ข้ามคำสั่งแยกกัน ไม่มีการ retry คำสั่งเขียนอัตโนมัติ หาก timeout หรือขาดการเชื่อมต่อ การเขียนอาจสำเร็จบน server แล้ว ต้องตรวจสถานะก่อนลองใหม่

ขอบเขตหลัก: 8 คำสั่งพร้อมกัน, 32 คำสั่งรอ, รอ admission สูงสุด 5 วินาที แล้วทำงานสูงสุดอีก 5 วินาที และล้าง session สูงสุดอีก 5 วินาที, SQL 64 KiB, พารามิเตอร์ข้อความรวม 1 MiB และผลลัพธ์ 1 MiB หลัง driver ถอดรหัส โปรแกรมฐานข้อมูลต้องรันด้วย native SDK; Playground ใช้ตรวจชนิดได้แต่ไม่เชื่อมฐานข้อมูล pool รองรับ8 sessions และ32คำสั่งรอ ตรวจอายุ idle60วินาที/connection300วินาทีเมื่อยืมหรือคืน ค่า URL/CA คงเดิมหลังเริ่ม pool; เปลี่ยนแล้วต้อง restart รุ่นนี้ยังเป็น Developer Preview

รุ่น 0.17.0 เพิ่ม postgres_transaction(handler[, arguments]) โดย handler ต้องเป็นฟังก์ชันชื่อที่คืน Bool! และรับ record ได้หนึ่งตัวตามที่ประกาศ คำสั่งฐานข้อมูลใน callback ใช้ transaction เดียวกัน return false ก็ commit เช่นเดียวกับ return true; หากต้องการ rollback ให้ใช้ fail ข้อผิดพลาดฐานข้อมูลหรือการเรียก transaction ซ้อนทำให้ commit ไม่ได้ แม้จับ error แล้วก็ตาม จำกัดรวม 30 วินาทีแบบ cooperative และแต่ละคำสั่งไม่เกิน 5 วินาที ไม่รองรับ DDL/control statements ภายใน callback และไม่ retry อัตโนมัติ หากขาดการเชื่อมต่อช่วง COMMIT ผลอาจไม่ทราบ ต้องตรวจข้อมูลก่อนลองใหม่

Pool lifecycle in 0.16.0

One lazy process pool caches validated URL/CA configuration; restart the program to change credentials or trust roots. At most 8 sessions are held across leases and idle storage. Up to 32 acquisitions may wait. A single 5-second acquisition budget includes queueing, a health check and replacement/TLS connection establishment. Statement work has 5 seconds. Successful recycling runs ROLLBACK then DISCARD ALL in a separate bounded 5-second cleanup budget, so caller latency may include all three phases. A completed statement is not reported failed solely because reset failed; that connection is discarded.

Idle 60-second and maximum 300-second ages are enforced lazily at checkout/return. There is no maintenance timer or promise to close a quiet idle socket exactly at expiry. An unhealthy idle connection may be replaced before statement dispatch; application statements are never retried. Cancellation aborts/discards the leased local connection; server write outcome may remain unknown.

The Rust adapter provides close(): admissions and idle sessions close immediately, active leases receive a default 1-second grace, then held sessions are synchronously marked unusable and their tasks aborted. Cancelling close also aborts active work. Idle sessions otherwise disappear once all pool handles and outstanding leases are dropped. The language does not expose pool-close/configuration or transaction handles; process/runtime shutdown owns its tasks.