Skip to content

Database type mappings ​

The inferred row type describes values returned by the typed-sql adapter under the selected typePolicy. Generation and runtime execution must use the same policy object.

PostgreSQL ​

PostgreSQL typeDefault TypeScript typeRuntime value
smallint, integernumberFinite JavaScript number
bigintbigintNative bigint
numeric, decimalstringExact decimal text
real, double precisionnumberJavaScript number
booleanbooleanJavaScript boolean
text, character, uuidstringJavaScript string
date, timestamp, timestamptzDateJavaScript Date
json, jsonbunknownParsed JSON value
byteaUint8ArrayUint8Array
enumLiteral string unionJavaScript string
supported T[]readonly T[]Recursively decoded array
nullable column`Tnull`

The PostgreSQL adapter installs parsers per query and does not mutate global pg.types.

PostgreSQL built-in semantics use the versioned offline catalog. Unknown signatures and unproven result types remain conservative. Native query contracts provide additional evidence for qualified queries during explicit generation or configured live analysis. Policy-controlled scalar and array OIDs use typed-sql codecs. Active extension manifests may add connection-local OID decoders; other OIDs delegate to the installed driver parser table.

Policy alternatives:

Policy fieldValuesGuarantee
bigintbigint, string, numbernumber rejects values outside the safe integer range.
numericstring, number, Decimalnumber rejects non-finite values; Decimal requires a converter.
dateDate, stringstring preserves driver text and database precision.
jsonunknown, JsonValue, stringObject modes parse JSON; string preserves text.
enumsstring-union, stringBoth decode strings; only inference changes.

timestamp without time zone follows the Node.js process timezone when represented as Date. JavaScript dates lose PostgreSQL sub-millisecond precision. Choose string when those semantics are not acceptable.

Constructed PostgreSQL JSON ​

With parsed JSON policies (json: "unknown" or json: "JsonValue"), literal-key json_build_object and jsonb_build_object calls infer nested object properties. Repeated literal keys use the last value, matching the parsed result. json_build_array and jsonb_build_array retain ordered element shapes. json_agg/jsonb_agg infer arrays; object aggregates retain their value type with open keys. Aggregates remain SQL-nullable on empty input, while their JSON values can contain independent JSON nulls.

to_json, to_jsonb, row_to_json and array_to_json preserve known scalar, row and array conversions. Integers, including bigint, become JavaScript numbers after JSON parsing and can lose precision. numeric, real and double precision use number | string because PostgreSQL emits non-finite values as JSON strings. Dates, timestamps, oid and bytea become strings. Scalar decoding policies do not change those nested representations. The json: "string" policy preserves complete JSON text.

Known structure survives CTEs, derived-table projections and scalar subqueries. Literal paths with ->, ->>, #> and #>> distinguish absent paths from present JSON nulls; text extraction converts JSON null to SQL null. Literal JSONB updates with jsonb_set, jsonb_insert, concatenation and removal retain the resulting structure. Dynamic paths, unsupported transformations and arbitrary JSON columns retain conservative unknown shapes. COALESCE(jsonb_agg(...), '[]'::jsonb) removes SQL-null aggregate results while preserving known array elements.

Shapes use shared bounds on depth, expanded nodes and emitted type length. Crossing a bound produces unknown, including in persisted metadata. Catalog-backed PostgreSQL arrays include nullable elements independently of the array column's SQL nullability; literal array constructors can retain more precise evidence. A driver transport must support and validate the array rank it returns.

MySQL ​

MySQL typeDefault TypeScript typeRuntime value
tinyint(1), boolean, boolbooleanStrict 0 or 1 conversion
other integer typesnumberJavaScript number
bigintbigintNative bigint
decimal, numericstringExact decimal text
float, double, realnumberJavaScript number
bitUint8ArrayNode.js Buffer
character, text, time, setstringJavaScript string
binary and blob typesUint8ArrayNode.js Buffer
spatial typesUint8ArrayOpaque MySQL geometry bytes in a Node.js Buffer
date, datetime, timestampDateDate converted from lossless text
yearnumberJavaScript number
jsonunknownParsed JSON value
vector on MySQL 9.7 or laterUint8ArrayNode.js Buffer
enumLiteral string unionJavaScript string
nullable column`Tnull`

The adapter owns mysql2 settings that affect row shape and decoding. Supplying conflicting options through poolConfig fails before a pool is created.

Expression inference also uses the selected server catalog. Exact integer arithmetic uses the bigint policy when MySQL produces a 64-bit result; decimal arithmetic uses the decimal policy; and any approximate operand produces number. Unsigned arithmetic remains unsigned except for subtraction under NO_UNSIGNED_SUBTRACTION. String results carry charset, collation, and coercibility evidence internally so comparisons, CONCAT, character-set introducers, and explicit COLLATE clauses can reject incompatible combinations.

Policy alternatives:

Policy fieldValuesGuarantee
bigintbigint, string, numbernumber rejects values outside the safe integer range.
decimalstring, number, Decimalnumber may approximate fractions; Decimal requires a converter.
dateDate, stringConversion occurs after mysql2 returns text.
jsonunknown, JsonValue, stringObject modes use parsed JSON; string serializes it.
tinyint1boolean, numberConversion follows field type and length metadata.

The adapter requests date, datetime, and timestamp values from mysql2 as text before applying the selected policy. string preserves fractional precision, zero components, and the server text. Date uses JavaScript date parsing, loses precision below milliseconds, and represents a MySQL zero-date value as an invalid Date; applications that permit zero dates or require lossless temporal values should select string. Snapshot compatibility checks the session and system time zones before dispatch when compatibilitySnapshot is enabled.

SQLite ​

SQLite mappings depend on whether the table is STRICT. Ordinary tables use a declared affinity but can store values from another storage class, so a narrower declared-type mapping would be unsound.

SQLite catalog evidenceDefault TypeScript typenode:sqlite runtime value
non-STRICT columnbigint | number | string | Uint8ArrayNative SQLite storage-class value
rowid or exact INTEGER PRIMARY KEY aliasbigintNative bigint through setReadBigInts(true)
STRICT INT, INTEGERbigintNative bigint through setReadBigInts(true)
STRICT REALnumberJavaScript number
STRICT TEXTstringJavaScript string
STRICT BLOBUint8ArrayNode.js Buffer
STRICT ANYFlexible storage unionNative SQLite storage-class value
nullable columnT | nullnull

SQLite JSON functions return string for JSON text and Uint8Array for JSONB. A single-path json_extract/jsonb_extract can instead produce any SQLite storage class, so it uses the flexible storage union; multiple paths return JSON text or JSONB respectively. json_each and json_tree use the same flexible union for value and atom.

SQLite date/time text functions return string | null, julianday returns number | null, and unixepoch returns the configured integer type unless a literal subsec/subsecond modifier makes the result number | null. Optional math and percentile functions return number | null after their compile-option evidence has been established.

The integer policy can select number; use it only when the application accepts JavaScript's safe-integer limit. The flexible policy can select unknown instead of the storage union. The same policy must be passed to the dialect, provider, and adapter.

SQLite's historical primary-key nullability exception is preserved: an ordinary non-STRICT rowid table can report nullable non-rowid primary-key columns. Exact rowid aliases, STRICT primary keys, and WITHOUT ROWID primary keys remain non-null.

SQL Server ​

Native typeDefault TypeScript typeRuntime value
tinyint, smallint, int, real, floatnumberFinite JavaScript number under the shared safe-integral policy
bigintbigintExact signed 64-bit integer
decimal, numeric, money, smallmoneystringExact decimal text
bitbooleanJavaScript boolean
Character types and XMLstringCounted text, including embedded and trailing NUL
binary, varbinary, rowversionUint8ArrayIndependently owned bytes; empty remains distinct from SQL NULL
Date and time typesstringNative precision, including seven fractional digits where supported
JSONstringJSON text; explicit parsed policy uses the proven JSON shape
CLR, spatial, sql_variant, unqualified typesunknownUnsupported typed transports fail before execution

Scalar money and decimal policies do not dictate JSON serialization: JSON_OBJECT and JSON_ARRAY emit native numeric values as JSON numbers, including money. Stored character JSON remains escaped text inside a constructor unless promoted by JSON_QUERY; a directly nested constructor retains its object or array shape. Unknown conditional fragment provenance remains conservative. See SQL Server policies and transport limits.

DuckDB ​

Native typeDefault TypeScript typeRuntime value
Small signed/unsigned integers, FLOAT, DOUBLEnumberFinite JavaScript number under the shared safe-integral policy
BIGINT, UBIGINT, HUGEINT, UHUGEINT, BIGNUMbigintExact signed or unsigned integer
DECIMALstringPrecision and scale preserved
BOOLEANbooleanJavaScript boolean
VARCHAR, UUID, BITstringNative text
BLOBUint8ArrayIndependently owned bytes
Date, time and timestamp typesstringPrecision and infinity values retained where supported
INTERVAL{ readonly months: number; readonly days: number; readonly micros: bigint }Separate calendar and microsecond components
JSONstringJSON text; parsed modes are explicit
ENUMLiteral string unionValidated catalog label
LISTReadonly arrayRecursive element decoding
ARRAYReadonly tupleFixed length and recursive element decoding
STRUCT, TUPLEObject or readonly tupleNative field names and positions retained
MAPReadonly array of key/value tuplesStructural keys retained without JavaScript object-key coercion
UNIONTagged unionActive member retained even when its payload is NULL

Nested SQL NULL values remain separate from an outer NULL container. MAP keys reject NULL and structural duplicates. The shared number policy rejects integer-valued numbers outside the safe integer range, even when the database type is floating point. See DuckDB native types and exact version pairs.

Nullability, aggregates, and drift ​

Nullability is applied after scalar mapping. Outer joins add null to columns from the nullable relation. COUNT follows the dialect's bigint policy, while decimal-producing aggregates follow the numeric or decimal policy.

Generated snapshots include a typePolicyHash. typed-sql drift detects policy changes even when the database catalog remains unchanged.

PostgreSQL 16 SQL-standard JSON_OBJECT, JSON_ARRAY, JSON_OBJECTAGG and JSON_ARRAYAGG retain structure with literal keys and supported value expressions. ABSENT ON NULL omits SQL-null values; it preserves an existing JSON null payload. Nullable object values become optional properties, and nullable array values can produce arrays of varying length. FORMAT JSON parses a literal document instead of quoting it. RETURNING text and RETURNING bytea keep their SQL scalar result types.

Native PostgreSQL arrays of JSON values keep an element validation contract in compiled queries. Application-declared shapes propagate through array constructors, projections, conditional expressions and array aggregates. SQL-null array elements remain separate from a JSON null document; nullable source values add null to the inferred element type.

Released under the MIT License.