dalgo2sql
SQL adapter for DALgo - a Database Abstraction Layer in Go.
Our approach to development
We build with our own tooling:
- SpecScore — specify requirements as
SpecScore.md artifacts
- SpecStudio — author & manage specs across their lifecycle
- inGitDB — store structured data in Git where applicable
- DALgo — data access layer for Go
- cover100.dev — drive toward 100% test coverage
- DataTug — query & explore data
Status

Usage
go get github.com/dal-go/dalgo2sql
SQLite structured aggregation
With DbOptions.StructuredQueryDialect set to sqlite, structured DALgo queries
render GROUP BY, COUNT, SUM, AVG, MIN, MAX, DISTINCT aggregates, HAVING, alias
rewrites, result ordering and pagination natively. SUM/AVG normalize numeric
inputs to REAL for parity with DALgo's generic float64 fallback. FIRST/LAST
are deliberately not advertised until DALgo models aggregate-local ordering;
using unspecified SQLite row order would not be deterministic. DALgo's planner
therefore refuses a query that uses them for this adapter (see the PostgreSQL
section), and nothing runs it.
Exact SQLite decimal SQL functions
Applications that issue SQLite SQL directly can opt in to exact decimal arithmetic
on the modernc.org/sqlite driver. Register the functions before opening the first
connection:
if err := dalgo2sql.RegisterSQLiteDecimalFunctions(); err != nil {
return err
}
db, err := sql.Open("sqlite", "app.sqlite")
Store decimal input in a TEXT-affinity column such as DECIMAL_TEXT(38, 6). The
functions accept decimal strings, bytes, and exact integers; they reject floats,
exponent notation, malformed input, and inputs or results over 38 significant
digits or scale 38. Arithmetic returns canonical decimal text. Addition and
multiplication never round: an over-precision result is an error. Division,
decimal_round, and decimal_avg use round-half-to-even, with scales from 0
through 38.
SELECT decimal_add('0.1', '0.2'); -- '0.3'
SELECT decimal_mul(quantity, unit_price); -- exact decimal text
SELECT decimal_div('1', '6', 4); -- '0.1667'
SELECT decimal_sum(amount), decimal_avg(amount, 2)
FROM invoice_lines;
SELECT amount FROM invoice_lines ORDER BY amount COLLATE DECIMAL;
Scalar functions return NULL if any argument is NULL; decimal_cmp otherwise
returns -1, 0, or 1. Aggregates ignore NULL and return NULL when every input is
NULL or no input rows exist. The DECIMAL collation orders valid decimal text
numerically; malformed text is placed after valid numbers and ordered
lexically. Constrain a decimal column to valid decimal text when relying on
numeric ordering. These opt-in functions do not change ordinary SQLite NUMERIC
or DALgo aggregate normalization.
Which path compiles a structured query
A structured DALgo query reaches SQL by one of four paths. They are tried in this
order, and which one runs is decided by how the source was opened, not by the query.
- A native compiler (
DbOptions.NativeStructuredQueryCompiler). When one is
set it writes the whole statement, and StructuredQueryDialect is not
consulted. It is for trusted adapter dialects that bring their own compiler.
- SQLite (
DbOptions.StructuredQueryDialect: "sqlite") uses the SQLite
structured emitter, compileStructuredSQL, described above. It is built around
SQLite's dynamic typing and has its own path; the typed compiler does not touch
it.
- PostgreSQL, MySQL, Oracle and SQL Server (
DbOptions.StructuredQueryDialect: "postgres", "mysql", "oracle" or "sqlserver") use the typed SQL compiler, not the legacy emitter. They
are described in the next sections.
- No dialect, no native compiler uses the legacy text emitter, described after
that. A PostgreSQL, MySQL, Oracle or SQL Server source should not stay on it; open it with
its dialect.
Any other non-empty dialect is refused with an error when a structured query is
read.
PostgreSQL
With StructuredQueryDialect: "postgres" a structured read runs in two steps on
one connection: one catalog query that reads every column of each source the query
names (their types, NOT NULL flags and collations), then the one SELECT the typed
compiler writes from that answer. compileTypedSQL(query, dialect, facts) is the
compiler and newPostgresDialect(mode) is PostgreSQL's spelling; the exact SQL and
arguments of every supported shape are in testdata/postgres.
- No value is written into the statement. Every constant is a bound argument and
every name goes through the dialect's quoting (
" doubled, NUL and names over 63
bytes refused). Pass Go integers for whole numbers: a whole number that arrives as
a float64 binds as numeric, which is correct but cannot use an index on an
integer column. A constant that does not match its column (a number against text)
is a server error, not an empty result. A float32 or float64 compared with a column
the catalog types as real (float4), in a comparison or in an IN list, is bound as
?::real from its decimal text, so the comparison runs in the column's own type and a
stored 0.1 is found by 0.1; as a numeric it is not the same number as the float4
nearest to 0.1, and an equality finds nothing. double precision and numeric columns
keep the numeric binding, and so does a float a real cannot hold (past about 3.4e38 or
below the smallest normal real, about 1.2e-38), which the server would refuse as out of
range, a column whose type the catalog gives by the name of a domain over real, and a
float that is not compared with a column (arithmetic, HAVING on an aggregate).
- Identifier case is
DbOptions.IdentifierCase: IdentifierCaseExact (the
default) writes names as the query spells them, for databases created with quoted
mixed-case names; IdentifierCaseFoldLower writes them lower-cased, for databases
created by dalgo2postgres. The result keeps the names the query asked for in both
modes (Total comes back as Total, an unaliased COUNT(*) as COUNT(*)). A select list
whose names differ only in case is refused under IdentifierCaseFoldLower. Do not
put a field mask or access check on such a mount unless the names it compares are
folded first. A configured primary key is matched to the result's column by the same
fold, so a key configured as ID keys the records of a column the server returns as
id.
A query that runs in DALgo's own engine instead of the compiler (a subquery, a join the
adapter declines) does not fold: under IdentifierCaseFoldLower it must spell table and
column names as the catalog stores them, in lower case, until DALgo's engine folds names
itself. The compiled path accepts any case.
- A table that is not there fails with
*TableNotFoundError (it matches
ErrTableNotFound), which names the table and the nearest name that exists
(SuggestedSchema and SuggestedName; both empty when none is near):
table "album" not found; did you mean "Album"? Table names are case-sensitive.
Under IdentifierCaseFoldLower only a name the mount can write is suggested.
A sequence, a name that resolves to nothing and a relation with no readable column
are all "not found"; a source is never compiled without its catalog facts.
- Native aggregation and joins. The adapter reports GROUP BY, HAVING, ORDER BY,
COUNT, SUM and AVG with their DISTINCT forms, MIN and MAX as native
(
QueryCapabilities), so DALgo runs them on the server. A query with a subquery
stays in DALgo's generic engine. FIRST and LAST are refused by DALgo's planner for this
adapter: they need a provider-declared stable input order, which the adapter does not
declare (neither dialect promises a group-key order or a stable row order), so a query
that uses one fails with the planner's error and runs nowhere, in the generic engine
included. A join is accepted
(CanExecuteJoin) when each ON pair has the same type category (numbers with
numbers, text with text) or the same type, on the database handle as in a
transaction; it is declined when the types differ or a key's type has no usable
equality (json, xml, geometric types, oid and the reg* types), when two text keys
have different collations of their own (PostgreSQL cannot choose between them and
refuses the comparison, SQLSTATE 42P22; a collation of its own against the database's
default, or the same collation, is accepted), when the
catalog does not hold a key, or when the compiler cannot write the query.
JoinFields lists a table's columns from the catalog, under the names the catalog
has, whatever the identifier case.
- Arithmetic is on double precision:
+, -, * and / read both operands as
double precision, as DALgo's generic engine does, so an integer overflow cannot
differ between engines; division by zero is NULL. SUM and AVG are cast to double
precision. NULLs sort first ascending and last descending, as in DALgo, and the
NULLS clause is left out for a NOT NULL column.
- A query the compiler cannot run faithfully in one statement is refused with an
error matching
dal.ErrNotSupported, among them a result column whose alias, or whose
expression text, is over 63 bytes. DALgo falls back to its generic engine only where
it has a fallback: a join, which it asks the adapter to accept first (CanExecuteJoin
compiles the whole query, and DALgo runs the generic join when it declines), and a
query with a subquery. For a query over one source the refusal is the read's error:
a 64-byte alias fails the read, and the remedy is a shorter alias. It is never handed
to the legacy emitter.
- A join keys each record by the base row (the first source of
FROM), as DALgo's
generic join does, whichever columns the select list names. The records reader adds
the base's configured primary key to the statement as a column of its own, qualified
by the base's alias, and reads the key from it by position, so a column of a joined
table that carries the key's name never keys a record. A select-all over joins, which
no column can be added to, is keyed from the base's own column of that name (the
catalog's list of the base's columns, a statement of its own on SQLite); a key the
base has no column for leaves the records with the placeholder key, as a select-all
over one source does. The same holds for the SQLite dialect. A select list that gives
two expressions of a join one output name (a.id and r.id) is refused with
join_field: duplicate output name, the error DALgo's generic engine gives for the
same query, with the SQLite dialect too.
- A record is keyed by the position of its key column, never by a name two columns
share. Where the reader knows the column it takes that position: the catalog's key of a
select-all (its position among the source's columns, which a select-all returns in table
order), and the first item of a select list that is the key's own field of the base source
(a field of a joined source that has the key's name is not). The catalog is asked in a
statement before the one that reads the rows, so a result that does not hold the key's
column at that position, because the source's columns changed between the two, fails the
read (
the columns of the source changed during the read) instead of keying the records
from another column. Where only a name says which column is the key (a declared key on a
select-all, a select-all over joins) the column stored under the name the statement writes
is taken (on a fold-lower mount, the key's name folded), else a column that spells the name
as it was declared, else the first column that is the name folded. A select list over one
source that gives one output name to two different expressions (a and b AS a) is
refused before any statement, as it is for a join, with every dialect and compiler
(columns[1]: duplicate output name "a"); one expression written twice is one column asked
twice and is left alone. The names a wildcard lists are not known before the statement, so
they are not compared.
- Records are keyed by the source's primary key. The records reader keys each record
by the primary key column of the recordset declared for the source in
DbOptions.Recordsets (else DbOptions.PrimaryKey). With no key configured, the key is
the source's primary key as the catalog reports it, when that is exactly one column. The
one catalog query that serves the compiler serves the key, so a read still sends one. A
source with no primary key, with a composite one, a view, a materialized view and a foreign
table (the catalog reports none for these), and a grouped or aggregated query, key their
rows by ordinal: the position of the row in the result, from 0, as decimal text. A recordset
that is declared with no single-column primary key keeps the literal ID
__dalgo_record_id, as does a read with the SQLite dialect, the legacy emitter or a native
compiler of the caller's and no key configured: they have no catalog to ask. On a fold-lower
mount a declared recordset is looked up by the query's spelling of the source, then by that
spelling folded as the catalog lookup folds it, so a recordset declared as album is found
by a query that says Album or ALBUM.
- A stream error is never the end of a result. Both readers return the error the
server raised in the middle of a result (a timeout, an overflow at one row) from
Next, instead of ErrNoMoreRecords; a read whose context ended returns the
context's error, wherever in the read it ended (errors.Is(err, context.Canceled)