dalgo2postgres
PostgreSQL-specific DALgo driver. Wraps github.com/dal-go/dalgo2sql to provide the dal.DB surface, and adds PostgreSQL-native implementations of:
- structured queries — compiled by dalgo2sql's typed PostgreSQL compiler with every value
bound and every name quoted, with filtering, ordering, grouping, aggregation and joins run
on the server (see "Structured queries")
dbschema.SchemaReader — schema introspection via information_schema, pg_catalog and pg_indexes: every non-system schema, views told from tables, column defaults
dbschema.SourceViewReader — ordered view columns and normalized view-definition metadata for the configured schema
dbschema.NativeAccessReader — the roles that can reach a table natively, with privileges, sources and coverage (see "Native access")
ddl.SchemaModifier and ddl.Applier — PostgreSQL-flavored CREATE TABLE / CREATE INDEX / DROP TABLE / ALTER TABLE
dal.ConcurrencyAware — advertises SupportsConcurrentConnections() = true
(PostgreSQL supports concurrent connections from multiple goroutines and processes,
unlike SQLite which serializes writers)
Constructor usage
import (
"github.com/dal-go/dalgo/dal"
"github.com/dal-go/dalgo2postgres"
"github.com/dal-go/dalgo2sql"
)
// Minimal — no per-collection primary-key configuration.
db, err := dalgo2postgres.NewDatabase("postgres://user:pass@localhost:5432/mydb?sslmode=disable")
// With per-collection recordset options (required for Insert/Get/Delete with map[string]any data):
db, err := dalgo2postgres.NewDatabaseWithOptions(dsn, dal.NewSchema(nil, nil),
dalgo2sql.DbOptions{
Recordsets: map[string]*dalgo2sql.Recordset{
"widgets": dalgo2sql.NewRecordset("widgets", dalgo2sql.Table,
[]dal.FieldRef{dal.Field("id")}),
},
})
if err != nil {
return err
}
defer db.Close()
Structured queries
A structured DALgo query (dal.From(...).NewQuery()...) reaches PostgreSQL through
dalgo2sql's typed PostgreSQL compiler. NewDatabase and NewDatabaseWithOptions force
dalgo2sql.DbOptions.StructuredQueryDialect to "postgres" whatever the caller passes
(the empty string, "sqlite" and "mysql" are replaced), so no structured query can reach
dalgo2sql's legacy text emitter, which writes values into the statement. The three fields
of DbOptions that replace the compiler (NativeStructuredQueryCompiler,
NativeJoinEligibility and NativeJoinHintTranslator) are refused: a constructor that is
given one returns an error before it connects, because the database would declare the
dialect's capabilities and accept joins by its check and then send them to a compiler that
promised neither.
*Database declares what the dialect runs on the server (dal.QueryCapabilitiesProvider,
dal.NativeJoinProvider and dal.JoinFieldsProvider), so dal.As[...] on a *Database
answers as it does on the dal.DB under it.
A read takes two statements on one connection: one catalog query that lists the columns of
every table the query names (type, NOT NULL, collation), then the one SELECT compiled from
the answer. No value is written into a statement: every constant is a bound argument,
and every name is double-quoted. An injection string is compared as text.
What runs on the server
- Filters: constants of each Go type (a whole number is
$n::bigint, an unsigned
integer or a float $n::numeric, except a float against a real column, which is
$n::real; a bool $n::boolean, a time.Time $n::timestamptz,
bytes $n::bytea, a string is untyped so the server reads it as a date, a UUID or an
enum where the column says so); == nil, isNull and isNotNull; IN and NOT IN,
an empty list included. A constant that does not match its column (a number against
text) is a server error, not an empty result.
- ORDER BY, LIMIT and OFFSET: NULLs sort first ascending and last descending, as in
DALgo, and the
NULLS clause is left out for a NOT NULL column. A column whose not-null
constraint is NOT VALID (PostgreSQL 18) may hold NULL and is not one: the clause is written
for it (dalgo2sql v0.26.7, dal-go/dalgo2sql#220). LIMIT and OFFSET are bound.
- GROUP BY and HAVING with
COUNT, SUM, AVG, MIN and MAX, and COUNT DISTINCT
and SUM DISTINCT, as one statement. SUM and AVG come back as float64, as in
DALgo's own engine. dalgo2sql declares AVG DISTINCT too; this repository's tests do not
run it.
- Arithmetic (
+, -, *, /) on double precision: 3 / 2 is 1.5, and a division
by zero is NULL.
- Select-all with exclusions: the columns of the table, in table order, minus the
excluded ones in any case (in the mode that folds names).
- Joins, when each
ON pair has the same type category (numbers with numbers, text with
text) or the same type: one statement with the JOIN.
- Tables, views, materialized views and partitioned tables, and columns of a domain over a
domain.
What falls back to DALgo's engine
DALgo's own engine is bounded, in memory: it stops at 10,000 rows of a join and 100,000
groups of an aggregation (dalgo v0.89.6), and past them returns an error, not a partial
result.
- A query with a subquery (
IN, EXISTS, a scalar subquery): DALgo reads each source with
plain statements and combines them itself. A correlated subquery reads the whole inner
table, every column and no filter, once for each row of the outer table, after one read of the
outer table: 1 + 7 statements for 7 outer rows, and the server cannot shorten it. Where the
tables are large, a correlated subquery costs what they hold (the statement count of each
fixture case is asserted: TestFixturesIntegration_SubqueriesRunInDALgoOverLeafReads).
This is a known limit of dal-go/dalgo's engine, described here: a correlated subquery could be
read with the outer value as a filter. A query with a derived source is not answered at
all: it is refused (see the known limits).
- A join the database declines: the
ON types differ (text with an integer, a boolean
with an integer), or two text keys have different collations of their own, neither the
database's default (the server cannot choose between them and refuses the comparison,
42P22, so DALgo compares the texts itself). dalgo2sql also declines a key whose type has
no usable equality (json, xml, geometric types, oid, the reg* types), which this
repository's tests do not exercise, and a query its compiler cannot write, which they do: the
join fixture chinook-wildcard (listed in testdata/postgres-divergences.json) is declined
to DALgo's engine, which answers it with three plain reads.
FIRST and LAST are refused with an error, not run anywhere: PostgreSQL promises
no row order for them, and this database declares no stable row order.
DALgo's engine reads each source as the catalog names its columns and matches the names a
query spells against them exactly. So in IdentifierFoldLower a query that runs there must
spell its names as the catalog stores them (lower case, for a database this package
created): a subquery that reads Title from a column stored as title is answered with
field "Title" is unavailable in "a". The native path accepts any case. A join that DALgo
runs itself is read by the same engine.
Identifier modes
IdentifierFoldLower, the default, lower-cases every name before it quotes it, which is
what this package's DDL stores: a database this package created is read back with any
spelling (Album, album and ALBUM are one table). IdentifierExact writes every name
as the query spells it, inside quotes, so Album and album are two tables; choose it to
read a database whose tables were created with mixed-case names (DataTug does). Either mode
keeps the names the query asked for in the result (Title comes back as Title); a
select-all returns the names the catalog has.
db, err := dalgo2postgres.NewDatabase(dsn, dalgo2postgres.WithIdentifierMode(dalgo2postgres.IdentifierExact))
The mode is one setting with two spellings: WithIdentifierMode, and dalgo2sql's
DbOptions.IdentifierCase (IdentifierCaseExact, IdentifierCaseFoldLower) for
NewDatabaseWithOptions. Either one decides it, and it decides how the schema reader
matches names too. Giving both with different modes is an error, and so is a value this
package does not define: the constructor returns it before it connects, so a mount that
meant to fold names never runs in the exact mode. Do not put a field mask or an access check
on a database that folds names unless the names it compares are folded first, or Total
passes a mask that names total.
A structured query reads the schema its collection reference names
(dal.NewQualifiedRootCollectionRef("sales", "Album", "")), else the schemas the
connection's search_path resolves. WithSchema affects only the schema reader.
Results and errors
- A NULL is
nil in the rows of both readers, the records reader and the recordset reader
(ExecuteQueryToRecordsetReader, the path DataTug reads), so a caller can tell it from a
stored 0, false, "" or zero time. (Up to dalgo2sql v0.26.4 the recordset reader put
the zero value of the column's type there.)
- A
NUMERIC column is read as float64 (pgx delivers it as text), NaN included. A
float64 holds about 15 significant digits exactly, so a longer NUMERIC is
rounded. Dates and times are time.Time.
- A copy or export caller can set
dalgo2sql.DbOptions.ExactNumericValues to keep
PostgreSQL NUMERIC text exact in DALgo records and recordsets. This is opt-in;
default reads keep their existing float64 behavior. The adapter's schema-reader
can target a non-public schema with WithSchema.
- A table the database does not have is a
*dalgo2sql.TableNotFoundError (it matches
dalgo2sql.ErrTableNotFound) that names the table and the nearest one that exists:
failed to get SQL reader: table "album" not found; did you mean "Album"? Table names are case-sensitive. (the last sentence is there in IdentifierExact only). No statement
is sent for it.
- A read inside a transaction (
RunReadonlyTransaction) compiles the same way, and its
catalog query runs on the transaction.
- A run-time error in the middle of the rows (a text that is no number, under the cast of
arithmetic, at row 4 of 5) reaches the caller as the server's error from both readers, after
the three rows before it: row by row, through the read-all helpers, and out of a read
transaction (
TestServerPinsIntegration_RuntimeErrorAtRowN). With dalgo2sql v0.26.0 the
recordset reader ended the rows quietly instead; since v0.26.1 it does not.
- How records are keyed. A record carries the collection of the query's base source,
spelled as the query spells it, and an ID taken from the first of these that applies:
the one-field primary key of the recordset declared for the source
(
DbOptions.Recordsets); else DbOptions.PrimaryKey, when it is one field; else the primary
key the catalog reports for the source, when it is exactly one column (a key with an
INCLUDE list counts: only its key column is the key); else the ordinal of the row in
the result ("0", "1", ...), which is no identity of the row. The ordinal is what a
table with no primary key, a composite key, a view, a materialized view and a grouped
query get. A query that does not select the key gets it through a hidden column the
statement adds ("id" AS "__dalgo_record_id"), which is not in the record's data;
__dalgo_record_id is only the name of that column, never an ID. A query that reads into a
record of its own (SelectIntoRecord) fills that record.
TestStructuredQueryIntegration_RecordKeysFromTheCatalog runs every case on the server.
- How a recordset is found follows two rules. For a query, the recordset is looked up
under the source name as the query spells it and, in
IdentifierFoldLower, under that name in
lower case, so a recordset registered as album is found for album, Album and ALBUM (the
record's collection is the spelling the query used); a recordset registered under a name with
capitals is found only by a query that spells it exactly so (see the known limits). For a
key read or write (Get, Exists, Set and the rest) the recordset is found only under
the collection of the key exactly as the key spells it, with no folding: a key spelled Album
does not find a recordset registered as album, and Exists and Get answer an error that
matches ErrRecordNotFound (the primary key is not defined for the recordset), with no
statement sent, for a row that exists
(TestStructuredQueryIntegration_KeyReadFindsItsRecordsetOnlyUnderTheCollectionAsSpelled).
So register each recordset under the one spelling the keys use, and in IdentifierFoldLower
spell the collection of every key in lower case when queries may spell it in another case.
- The rows of a grouped query (one with
GroupBy or an aggregate) are keyed by their
ordinal in the result, whether a primary key is configured or not: a group is not a row of
the table, so no key is read and no hidden column is added.
Constants and column types
A constant is typed by its Go type, never by its value, and the server compares it with the
column. TestTypeMatrixIntegration_FilterByColumnTypeAndConstantType runs every Go type
against a column of each of smallint, integer, bigint, numeric, real,
double precision, boolean, date, timestamp, timestamptz, uuid, jsonb and text