From c490e92b08e50aaf5760ffdb51b4fd9dfa9bd44b Mon Sep 17 00:00:00 2001 From: Jaremy Creechley Date: Sat, 14 Nov 2026 02:17:41 +0200 Subject: [PATCH 1/5] Add PostgreSQL casts, array comparisons, and JSON expressions --- README.md | 53 +++++ config.nims | 6 +- ormin/db_types.nim | 5 +- ormin/importer_core.nim | 7 +- ormin/parsesql_tmp.nim | 19 ++ ormin/queries.nim | 160 ++++++++++++++- tests/postgres_expressions_model.sql | 9 + tests/tpostgres_expressions.nim | 257 +++++++++++++++++++++++++ tests/tpostgres_type_syntax.nim | 43 +++++ tests/tsqlite_postgres_expressions.nim | 24 +++ 10 files changed, 569 insertions(+), 14 deletions(-) create mode 100644 tests/postgres_expressions_model.sql create mode 100644 tests/tpostgres_expressions.nim create mode 100644 tests/tpostgres_type_syntax.nim create mode 100644 tests/tsqlite_postgres_expressions.nim diff --git a/README.md b/README.md index f8c649f..afbf7cf 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,59 @@ Joins use the syntax `join Person(name, city) on author == id` where `Person` is The join syntax differs from SQL but simplifies selecting fields from multiple tables by making them more explicit while still maintaing SQL's full query capabilities. +### PostgreSQL expressions + +Use `sqlCast(value, "type")` when PostgreSQL needs an explicit type. For example, +`sqlCast(?value, "text")` generates `($1)::text`: the value stays a bound +parameter, and PostgreSQL performs the conversion. This works with columns, +expressions, `?` Nim parameters, and `%` JSON parameters. + +```nim +let ids = "{1,3,5}" # PostgreSQL array text +let required = %*{"enabled": true} +let rows = query: + select records(id, (payload ->> "name") as name) + where id == any(sqlCast(?ids, "bigint[]")) and + payload @> sqlCast(?required, "jsonb") + orderby id +``` + +These forms work in inline queries and generated `createProc`/`createIter` +routines: + +| DSL expression | PostgreSQL expression | +| --- | --- | +| `sqlCast(?value, "uuid")` | `($1)::uuid` | +| `id == any(sqlCast(?ids, "bigint[]"))` | `id = ANY(($1)::bigint[])` | +| `id != all(sqlCast(?ids, "bigint[]"))` | `id <> ALL(($1)::bigint[])` | +| `payload -> "items"` | JSON extraction with `->` | +| `payload ->> "name"` | Text extraction with `->>` | +| `jsonPath(payload, ?path)` | JSON path extraction with `#>` | +| `jsonPathText(payload, ?path)` | Text path extraction with `#>>` | +| `payload @> sqlCast(?filter, "jsonb")` | JSONB containment | +| `tags && sqlCast(?tags, "text[]")` | Array overlap | +| `isDistinctFrom(note, ?value)` | `note IS DISTINCT FROM $1` | +| `isNotDistinctFrom(note, ?value)` | `note IS NOT DISTINCT FROM $1` | + +`<@` also supports contained-by comparisons for JSONB and arrays; `@>` supports +array containment. JSON extraction accepts text keys or integer indexes. For a +bound numeric index, use `sqlCast(?index, "integer")`. Pass JSON paths as text +arrays, such as `"{settings,enabled}"`. Missing JSON paths can be mapped to +`Option` fields with `query(T)`. + +Cast type names must be supported built-in PostgreSQL types written as string +literals. Supported types include text/varchar, UUID, JSON/JSONB, booleans, +integers, real/float4/float8/double precision, numeric/decimal, date/time/timestamp, +interval, regclass, and their array forms. Arbitrary SQL fragments and runtime +type names are rejected. Cast parameters use their Nim input types, so an integer +can be cast to text and a numeric string can be cast to a database number. +`none(T)` becomes SQL NULL. + +Model imports accept `double precision` and array columns such as `text[]` and +`uuid[]`. PostgreSQL UUID, array, and exact decimal results use Nim strings; +arrays retain PostgreSQL's array text format and decimals retain their precision. +These PostgreSQL expression forms are rejected when using the SQLite backend. + ### Return Types The core return type for queries is a sequence of tuples where the tuples fields are the types of the columns. Some queries with `returning` or `limit` clauses will return singular values or raise a DbError. diff --git a/config.nims b/config.nims index 5240e63..482d2b2 100644 --- a/config.nims +++ b/config.nims @@ -18,7 +18,8 @@ task test, "Run all test suite": exec("atlas-run tests --jobs:1 tests/tfeature.nim tests/tcommon.nim " & "tests/tsqlite.nim tests/tdb_utils.nim tests/timportstatic.nim " & "tests/ttransactions.nim tests/tpostgres_schema_import.nim " & - "tests/tqualified_schema_queries.nim") + "tests/tqualified_schema_queries.nim tests/tpostgres_expressions.nim " & + "tests/tsqlite_postgres_expressions.nim tests/tpostgres_type_syntax.nim") exec "atlas-run tests --jobs:2 tests/tquery_types.nim -- -d:release" task setup_postgres, "Ensure local Postgres has test DB/user": @@ -35,7 +36,8 @@ task test_postgres, "Run PostgreSQL test suite": # These suites share one PostgreSQL database and must execute serially. exec("atlas-run tests --jobs:1 tests/tfeature.nim tests/tcommon.nim " & - "tests/tpostgre.nim tests/tpostgre_statement_lifecycle.nim -- " & + "tests/tpostgre.nim tests/tpostgre_statement_lifecycle.nim " & + "tests/tpostgres_expressions.nim -- " & "-d:nimDebugDlOpen -d:postgre") exec("atlas-run tests --jobs:2 tests/tquery_types.nim -- " & "-d:nimDebugDlOpen -d:release -d:postgre") diff --git a/ormin/db_types.nim b/ormin/db_types.nim index df4b5f8..64ce557 100644 --- a/ormin/db_types.nim +++ b/ormin/db_types.nim @@ -16,8 +16,9 @@ proc dbTypFromName*(name: string): DbTypeKind = of "varchar", "text", "string": k = dbVarchar of "json", "jsonb": k = dbJson of "xml": k = dbXml - of "decimal": k = dbDecimal - of "float", "double", "longdouble", "real": k = dbFloat + of "decimal", "numeric": k = dbDecimal + of "float", "float4", "float8", "double", "double precision", "longdouble", "real": + k = dbFloat of "date", "day": k = dbDate of "time": k = dbTime of "datetime": k = dbDateTime diff --git a/ormin/importer_core.nim b/ormin/importer_core.nim index 901349a..ec83606 100644 --- a/ormin/importer_core.nim +++ b/ormin/importer_core.nim @@ -70,7 +70,12 @@ proc getType(n: SqlNode; enums: KnownEnums): DbType = var it = n if it.kind == nkCall: it = it[0] - if it.kind == nkEnumDef: + if it.kind == nkArrayType: + let element = getType(it[0], enums) + result = DbType(kind: dbArray, name: element.name & "[]") + elif it.kind == nkRaw: + result = DbType(kind: dbTypFromName(it.strVal), name: it.strVal) + elif it.kind == nkEnumDef: result.kind = dbEnum result.validValues = @[] for i in 0 ..< it.len: diff --git a/ormin/parsesql_tmp.nim b/ormin/parsesql_tmp.nim index 8563f3e..067aa05 100644 --- a/ormin/parsesql_tmp.nim +++ b/ormin/parsesql_tmp.nim @@ -530,6 +530,7 @@ type nkCreateIndex, nkCreateIndexIfNotExists, nkEnumDef, + nkArrayType, nkPragma, nkAutoIncrement, nkOnDelete, @@ -807,6 +808,9 @@ proc parseDataType(p: var SqlParser): SqlNode = eat(p, tkParRi) else: result = parseQualifiedIdentifier(p) + if sqlIdentName(result).toLowerAscii() == "double" and isKeyw(p, "precision"): + result = newNode(nkRaw, "double precision") + getTok(p) if p.tok.kind == tkParLe: var complexType = newNode(nkCall) complexType.add(result) @@ -822,6 +826,15 @@ proc parseDataType(p: var SqlParser): SqlNode = eat(p, tkParRi) if p.considerTypeParams: result = complexType + while p.tok.kind == tkBracketLe: + var arrayType = newNode(nkArrayType) + arrayType.add(result) + getTok(p) + if p.tok.kind == tkInteger: + arrayType.add(newNode(nkIntegerLit, p.tok.literal)) + getTok(p) + eat(p, tkBracketRi) + result = arrayType proc getPrecedence(p: SqlParser): int = if isOpr(p, "*") or isOpr(p, "/") or isOpr(p, "%"): @@ -1974,6 +1987,12 @@ proc ra(n: SqlNode, s: var SqlWriter) = of nkEnumDef: s.addKeyw("enum") rs(n, s) + of nkArrayType: + ra(n[0], s) + s.add('[') + if n.len == 2: + s.buffer.add(n[1].strVal) + s.add(']') of nkPragma: s.addKeyw("pragma") if n.len >= 1: diff --git a/ormin/queries.nim b/ormin/queries.nim index f2426b9..3a5a07c 100644 --- a/ormin/queries.nim +++ b/ormin/queries.nim @@ -6,6 +6,7 @@ when not declared(attributes): {.macros.error: "The query DSL requires a attributes const.".} import macros, strutils +from std/options import Option, get import db_connector/db_common from os import parentDir, `/` @@ -154,6 +155,7 @@ type retType: NimNode singleRow, retTypeIsJson: bool retNames: seq[string] + retDbTypes: seq[DbType] params: Params coln, qmark, aliasGen: int colAliases: seq[(string, DbType)] @@ -367,6 +369,10 @@ proc checkCompatibleSet(a, b: DbType; n: NimNode) = discard "too implement; might require a richer type system" proc toNimType(t: DbTypeKind): NimNode {.compileTime.} = + when dbBackend == DbBackend.postgre: + if t in {dbUuid, dbArray, dbDecimal, dbDate, dbTime, dbTimeInterval}: + # Preserve exact decimal values and PostgreSQL's textual array format. + return ident"varcharType" let name = ($t).substr(2).toLowerAscii & "Type" result = ident(name) @@ -497,6 +503,69 @@ proc renderInlineQuery(n: NimNode; params: var Params; proc cond(n: NimNode; q: var string; params: var Params; expected: DbType, qb: QueryBuilder): DbType +proc requirePostgres(n: NimNode) {.compileTime.} = + when dbBackend != DbBackend.postgre: + macros.error "this expression requires the PostgreSQL backend", n + +proc postgresCastType(name: string; n: NimNode): DbType {.compileTime.} = + let normalized = strutils.splitWhitespace(name).join(" ").toLowerAscii() + if normalized.endsWith("[]"): + let element = postgresCastType(normalized[0..^3], n) + return DbType(kind: dbArray, name: element.name & "[]") + let kind = + case normalized + of "text", "varchar", "character varying", "regclass": dbVarchar + of "uuid": dbUuid + of "json", "jsonb": dbJson + of "bool", "boolean": dbBool + of "smallint", "integer", "int", "bigint", "int2", "int4", "int8": dbInt + of "real", "double precision", "float4", "float8": dbFloat + of "numeric", "decimal": dbDecimal + of "date": dbDate + of "time", "time with time zone", "time without time zone": dbTime + of "timestamp", "timestamptz", "timestamp with time zone", + "timestamp without time zone": dbTimestamp + of "interval": dbTimeInterval + else: + macros.error "unsupported PostgreSQL cast type: " & name, n + dbUnknown + DbType(kind: kind, name: normalized) + +proc renderJsonAccess(left, right: NimNode; op: string; q: var string; + params: var Params; qb: QueryBuilder): DbType = + requirePostgres(left) + q.add '(' + let source = cond(left, q, params, DbType(kind: dbJson), qb) + if source.kind != dbJson: + macros.error "JSON extraction requires a json/jsonb expression", left + q.add " " & op & " " + let path = op in ["#>", "#>>"] + let expected = if path: DbType(kind: dbArray, name: "text[]") + elif right.kind in {nnkIntLit..nnkInt64Lit}: DbType(kind: dbInt) + else: DbType(kind: dbVarchar) + let key = cond(right, q, params, expected, qb) + if path: + if key.kind != dbArray or key.name != "text[]": + macros.error "JSON paths require a text[] expression", right + elif key.kind notin {dbVarchar, dbInt, dbSerial}: + macros.error "JSON extraction requires a text key or integer index", right + q.add ')' + DbType(kind: (if op in ["->>", "#>>"]: dbVarchar else: dbJson)) + +proc renderArrayComparison(n: NimNode; q: var string; + params: var Params; qb: QueryBuilder): DbType = + requirePostgres(n) + expectLen(n, 2) + q.add nodeName(n[0]) & "(" + let arrayType = cond(n[1], q, params, DbType(kind: dbUnknown), qb) + if arrayType.kind != dbArray or not arrayType.name.endsWith("[]"): + macros.error "ANY/ALL requires a typed array expression", n[1] + var elementName = arrayType.name + while elementName.endsWith("[]"): + elementName.setLen(elementName.len - 2) + result = postgresCastType(elementName, n[1]) + q.add ')' + proc renderWindowClause(n: NimNode; q: var string; params: var Params; qb: QueryBuilder) {.compileTime.} = let op = nodeName(n[0]).toLowerAscii() @@ -549,10 +618,11 @@ proc cond(n: NimNode; q: var string; params: var Params; of nnkDotExpr: let t = nodeName(n[0]) let a = nodeName(n[1]) - escIdent(q, t) + var alias: string + result = lookup(t, a, qb, alias) + escIdent(q, if alias.len > 0 and qb.kind in {qkSelect, qkJoin}: alias else: t) q.add '.' escIdent(q, a) - result = lookup(t, a, qb) of nnkPar, nnkStmtListExpr: if n.len == 1: q.add "(" @@ -601,6 +671,19 @@ proc cond(n: NimNode; q: var string; params: var Params; of nnkInfix: let op = $n[0] case op + of "->", "->>": + result = renderJsonAccess(n[1], n[2], op, q, params, qb) + of "@>", "<@", "&&": + requirePostgres(n) + q.add '(' + let a = cond(n[1], q, params, DbType(kind: dbUnknown), qb) + if a.kind notin {dbJson, dbArray} or (op == "&&" and a.kind != dbArray): + macros.error "containment requires jsonb or arrays; overlap requires arrays", n + q.add " " & op & " " + let b = cond(n[2], q, params, a, qb) + checkCompatible(a, b, n) + q.add ')' + result = DbType(kind: dbBool) of "and", "or": result = DbType(kind: dbBool) let a = cond(n[1], q, params, result, qb) @@ -635,7 +718,11 @@ proc cond(n: NimNode; q: var string; params: var Params; q.add ' ' if env.len == 2: qb.env = @[env[1]] - let b = cond(n[2], q, params, a, qb) + let b = + if n[2].kind == nnkCall and nodeName(n[2][0]) in ["any", "all", "some"]: + renderArrayComparison(n[2], q, params, qb) + else: + cond(n[2], q, params, a, qb) checkCompatible a, b, n result = DbType(kind: dbBool) of "in", "notin": @@ -709,6 +796,39 @@ proc cond(n: NimNode; q: var string; params: var Params; result = cond(n[1], q, params, DbType(kind: dbUnknown), qb) of nnkCall: let op = nodeName(n[0]) + if op == "sqlCast": + requirePostgres(n) + expectLen(n, 3) + if n[2].kind notin {nnkStrLit, nnkRStrLit, nnkTripleStrLit}: + macros.error "sqlCast requires a literal PostgreSQL type name", n[2] + result = postgresCastType(n[2].strVal, n[2]) + var value = n[1] + while value.kind == nnkPar and value.len == 1: + value = value[0] + q.add '(' + if value.kind == nnkPrefix and nodeName(value[0]) in ["?", "%"]: + q.add placeholder(qb) + # PostgreSQL performs the conversion; retain the Nim input's own type. + params.add((ex: value[1], typ: ident"auto", isJson: nodeName(value[0]) == "%")) + else: + discard cond(value, q, params, DbType(kind: dbUnknown), qb) + q.add ")::" & result.name + return + if op in ["jsonPath", "jsonPathText"]: + expectLen(n, 3) + let sqlOp = if op == "jsonPath": "#>" else: "#>>" + return renderJsonAccess(n[1], n[2], sqlOp, q, params, qb) + if op in ["isDistinctFrom", "isNotDistinctFrom"]: + requirePostgres(n) + expectLen(n, 3) + q.add '(' + let a = cond(n[1], q, params, DbType(kind: dbUnknown), qb) + q.add (if op == "isDistinctFrom": " is distinct from " else: " is not distinct from ") + let b = cond(n[2], q, params, a, qb) + if not isNullLiteral(n[1]) and not isNullLiteral(n[2]): + checkCompatible(a, b, n) + q.add ')' + return DbType(kind: dbBool) if isSetOpCall(n): let subq = renderInlineQuery(n, params, qb) q.add subq.sql @@ -935,6 +1055,7 @@ proc selectAll(q: QueryBuilder; tabIndex: int; arg, lineInfo: NimNode) = inc q.coln q.retType.add nnkIdentDefs.newTree(newIdentNode(a.name), toNimType(a.typ), newEmptyNode()) q.retNames.add a.name + q.retDbTypes.add a.typ doAssert q.env.len > 0 q.head.add q.env[^1][1] q.head.add '.' @@ -1053,6 +1174,7 @@ proc tableSel(n: NimNode; q: QueryBuilder) = cond(col, q.head, q.params, DbType(kind: dbUnknown), q) q.retType.add nnkIdentDefs.newTree(newIdentNode(getColumnName(col)), toNimType(t), newEmptyNode()) q.retNames.add getColumnName(col) + q.retDbTypes.add t else: macros.error "unknown selector: " & repr(n), n if q.kind notin {qkUpdate, qkSelect, qkJoin}: q.head.add ")" @@ -1106,12 +1228,7 @@ proc queryh(n: NimNode; q: QueryBuilder) = q.params.add p var cols: seq[SourceColumn] = @[] for i, name in subq.retNames: - let typNode = - if i < subq.retType.len and subq.retType[i].kind == nnkIdentDefs and subq.retType[i].len > 1: - subq.retType[i][1] - else: - newEmptyNode() - cols.add SourceColumn(name: name, typ: DbType(kind: typeNodeToDbKind(typNode))) + cols.add SourceColumn(name: name, typ: subq.retDbTypes[i]) q.ctes.add CteDef(name: cteName, sql: queryAsString(subq, n[1][1]), cols: cols) of "select": q.kind = qkSelect @@ -1458,6 +1575,7 @@ proc buildSetOpQueryParts(op: string; branches: openArray[NimNode]; if i == 0: q.retType = branch.retType q.retNames = branch.retNames + q.retDbTypes = branch.retDbTypes q.retTypeIsJson = branch.retTypeIsJson elif branch.retTypeIsJson != q.retTypeIsJson or not sameReturnShape(branch.retType, q.retType): @@ -1547,6 +1665,30 @@ proc makeSeq(retType: NimNode; singleRow: bool): NimNode = result = retType proc buildHookedParamBinding(prepStmt: NimNode; idx: int; ex, typ: NimNode; isJson: bool): NimNode = + if typ.kind == nnkIdent and typ.eqIdent("auto"): + if isJson: + return quote do: + block: + let value = `ex` + if value.kind == JNull: + bindNullParam(db, `prepStmt`, `idx`) + elif value.kind == JString: + bindParam(db, `prepStmt`, `idx`, value.str, string) + else: + bindParam(db, `prepStmt`, `idx`, value, JsonNode) + return quote do: + block: + let value = `ex` + when value is Option: + type InputType = typeof(value.get()) + else: + type InputType = typeof(value) + var converted: DbValue[InputType] + toQueryHook(converted, value) + if converted.isNull: + bindNullParam(db, `prepStmt`, `idx`) + else: + bindParam(db, `prepStmt`, `idx`, converted.value, InputType) if isJson: return newCall(bindSym"bindParamJson", ident"db", prepStmt, newLit(idx), ex, typ) diff --git a/tests/postgres_expressions_model.sql b/tests/postgres_expressions_model.sql new file mode 100644 index 0000000..7281932 --- /dev/null +++ b/tests/postgres_expressions_model.sql @@ -0,0 +1,9 @@ +create table records ( + id bigint primary key, + public_id uuid not null, + payload jsonb not null, + amount double precision not null, + exact_amount numeric(24, 6), + tags text[] not null, + note text +); diff --git a/tests/tpostgres_expressions.nim b/tests/tpostgres_expressions.nim new file mode 100644 index 0000000..05f3611 --- /dev/null +++ b/tests/tpostgres_expressions.nim @@ -0,0 +1,257 @@ +import std/[assertions, json, options, os, strutils] + +import db_connector/db_postgres as pg except DbConn, open, close, dbError +import ormin +importModel(DbBackend.postgre, "postgres_expressions_model", includeStatic = true) + +proc checkExpressions(db: DbConn) = + pg.exec(db, sql(string(sqlSchema).replace("create table", "create temporary table"))) + pg.exec(db, sql"""insert into records values + (1, '00000000-0000-0000-0000-000000000001', + '{"name":"alpha","nested":{"enabled":true},"items":[10,20]}', + 1.25, 123456789012345678.123456, '{red,blue}', NULL), + (2, '00000000-0000-0000-0000-000000000002', + '{"name":"beta","nested":{"enabled":false},"items":[30]}', + 2.5, 1.000001, '{green,blue}', 'ready'), + (3, '00000000-0000-0000-0000-000000000003', + '{"name":"gamma","items":[]}', 3.75, NULL, '{}', '')""") + + block cast_parameters_preserve_their_nim_input_types: + let number = 42 + let numericText = "2.5" + let enabled = "true" + let rows = query: + select records(sqlCast(?number, "text") as label, + sqlCast(?numericText, "double precision") as amount, + sqlCast(?enabled, "boolean") as enabled) + where id == 1 + doAssert rows == @[("42", 2.5, true)] + let numeric = "123456789012345678.123456" + let exact = query: + select records(sqlCast(?numeric, "numeric") as value, exact_amount) + where id == 1 + doAssert exact == @[(numeric, numeric)] + + block cast_columns_and_uuid_parameters: + let uuid = "00000000-0000-0000-0000-000000000002" + let rows = query: + select records(sqlCast(id, "text") as label, public_id) + where public_id == sqlCast(?uuid, "uuid") + doAssert rows == @[("2", uuid)] + + block null_casts: + let missing = none(string) + type Row = object + value: Option[int] + let rows = query(Row): + select records(sqlCast(?missing, "bigint") as value) + where id == 1 + doAssert rows == @[Row(value: none(int))] + + block json_parameter_casts: + let text = "{\"name\":\"alpha\"}" + let document = %*{"name": "alpha"} + let input = %*{"number": "42", "object": {"ok": true}, "missing": nil} + let rows = query: + select records(sqlCast(?text, "jsonb") as first, + sqlCast(?document, "jsonb") as second, + sqlCast(%input["number"], "bigint") as number, + sqlCast(%input["object"], "jsonb") as objectValue) + where id == 1 + doAssert rows == @[(document, document, 42, %*{"ok": true})] + let absent = query: + select records(id) + where isNotDistinctFrom(note, sqlCast(%input["missing"], "text")) + doAssert absent == @[1] + + block array_membership: + let ids = "{1,3}" + let selected = query: + select records(id) + where id == any(sqlCast(?ids, "bigint[]")) + orderby id + doAssert selected == @[1, 3] + let excluded = query: + select records(id) + where id != all(sqlCast(?ids, "bigint[]")) + orderby id + doAssert excluded == @[2] + let byTag = query: + select records(id) + where "blue" == any(tags) + orderby id + doAssert byTag == @[1, 2] + let uuids = "{00000000-0000-0000-0000-000000000001}" + let byUuid = query: + select records(id) + where public_id == any(sqlCast(?uuids, "uuid[]")) + doAssert byUuid == @[1] + let multidimensional = "{{1,2},{3,4}}" + let byMatrix = query: + select records(id) + where id == any(sqlCast(?multidimensional, "bigint[][]")) + orderby id + doAssert byMatrix == @[1, 2, 3] + + block empty_and_null_arrays: + let empty = "{}" + let none = query: + select records(id) + where id == any(sqlCast(?empty, "bigint[]")) + doAssert none.len == 0 + let allRows = query: + select records(id) + where id != all(sqlCast(?empty, "bigint[]")) + orderby id + doAssert allRows == @[1, 2, 3] + let missing = options.none(string) + let nullArray = query: + select records(id) + where id == any(sqlCast(?missing, "bigint[]")) + doAssert nullArray.len == 0 + + block json_extraction_and_paths: + let path = "{nested,enabled}" + let rows = query: + select records((payload ->> "name") as name, + ((payload -> "items") ->> 1) as item, + jsonPath(payload, sqlCast(?path, "text[]")) as enabled, + sqlCast(jsonPathText(payload, ?path), "boolean") as active) + where id == 1 + doAssert rows == @[("alpha", "20", %true, true)] + let index = 0 + let first = query: + select records(((payload -> "items") ->> sqlCast(?index, "integer")) as item) + where id == 1 + doAssert first == @["10"] + type Row = object + missing: Option[string] + let absent = query(Row): + select records(jsonPathText(payload, "{not,present}") as missing) + where id == 1 + doAssert absent == @[Row(missing: options.none(string))] + + block json_and_array_containment: + let document = %*{"nested": {"enabled": true}} + let matching = query: + select records(id) + where payload @> sqlCast(?document, "jsonb") + doAssert matching == @[1] + let reverse = query: + select records(id) + where sqlCast(?document, "jsonb") <@ payload + doAssert reverse == @[1] + let tags = "{red}" + let containsTag = query: + select records(id) + where records.tags @> sqlCast(?tags, "text[]") + doAssert containsTag == @[1] + let overlap = query: + select records(id) + where records.tags && sqlCast(?tags, "text[]") + doAssert overlap == @[1] + + block null_safe_comparisons: + let missing = options.none(string) + let absent = query: + select records(id) + where isNotDistinctFrom(note, ?missing) + doAssert absent == @[1] + let present = query: + select records(id) + where isDistinctFrom(note, nil) + orderby id + doAssert present == @[2, 3] + let values = query: + select records(isNotDistinctFrom(nil, nil) as equal) + where id == 1 + doAssert values == @[true] + + block generated_routines_and_parameter_order: + createProc lookupId: + select records(id) + where sqlCast(id, "text") == sqlCast(?value, "text") and id >= ?minimum + createIter lookupIds: + select records(id) + where id == any(sqlCast(?values, "bigint[]")) + orderby id + doAssert db.lookupId(2, 1) == @[2] + doAssert db.lookupId("3", 1) == @[3] + var rows: seq[int] + for id in db.lookupIds("{1,3}"): + rows.add id + doAssert rows == @[1, 3] + let first = "alpha" + let second = 2 + let found = query: + with chosen(select records(id) where (payload ->> "name") == sqlCast(?first, "text")) + select chosen(id) + where id < sqlCast(?second, "bigint") + doAssert found == @[1] + + block ctes_preserve_postgres_column_types: + let uuid = "00000000-0000-0000-0000-000000000001" + let selected = query: + with chosen(select records(id, public_id, sqlCast(tags, "text[]") as labels)) + select chosen(id, labels) + where "red" == any(labels) and public_id == sqlCast(?uuid, "uuid") + doAssert selected == @[(1, "{red,blue}")] + let allColumns = query: + with chosen(select records(_)) + select chosen(id) + where "red" == any(tags) and public_id == sqlCast(?uuid, "uuid") + doAssert allColumns == @[1] + + block cast_values_remain_bound: + let value = "x'); drop table records; --" + query: + update records(note = sqlCast(?value, "text")) + where id == 2 + doAssert pg.getValue(db, sql"select note from records where id = 2") == value + doAssert pg.getValue(db, sql"select count(*) from records") == "3" + + block failed_cast_does_not_poison_the_connection: + let invalid = "not an integer" + doAssertRaises(DbError): + discard query: + select records(sqlCast(?invalid, "bigint") as value) + where id == 1 + doAssert pg.getValue(db, sql"select count(*) from records") == "3" + +static: + var db: DbConn + doAssert not compiles(block: + discard query: + select records(sqlCast(id, "text); select 1; --")) + ) + doAssert not compiles(block: + let dynamicType = "text" + discard query: + select records(sqlCast(id, dynamicType)) + ) + doAssert not compiles(block: + discard query: + select records(id) + where id == any(note) + ) + doAssert not compiles(block: + discard query: + select records(any(tags)) + ) + doAssert not compiles(block: + discard query: + select records(note ->> "key") + ) + doAssert not compiles(block: + discard query: + select records(jsonPathText(payload, sqlCast("{}", "uuid[]"))) + ) + +when defined(postgre): + let target = getEnv("TEST_DATABASE_URL", "postgresql://test@localhost/test_ormin") + let db = pg.open("", "", "", target) + try: + checkExpressions(db) + echo "PostgreSQL expression tests passed" + finally: + pg.close(db) diff --git a/tests/tpostgres_type_syntax.nim b/tests/tpostgres_type_syntax.nim new file mode 100644 index 0000000..fba6711 --- /dev/null +++ b/tests/tpostgres_type_syntax.nim @@ -0,0 +1,43 @@ +import std/[assertions, strutils] + +import ormin/[db_types, importer_core, parsesql_tmp] +from db_connector/db_common import DbTypeKind + +block postgres_type_aliases: + doAssert dbTypFromName("float4") == dbFloat + doAssert dbTypFromName("float8") == dbFloat + doAssert dbTypFromName("DOUBLE PRECISION") == dbFloat + doAssert dbTypFromName("numeric") == dbDecimal + +block schema_types_round_trip: + let schema = """ + create table measurements ( + id bigint primary key, + value double precision not null, + labels text[], + ids uuid[8], + matrix numeric(18, 4)[][], + states "public"."status"[] + ); + """ + let tree = parseSql(schema, considerTypeParams = true) + let rendered = renderSql(tree) + doAssert "double precision" in rendered + doAssert "text[]" in rendered + doAssert "uuid[8]" in rendered + doAssert "numeric(18, 4)[][]" in rendered or "numeric(18,4)[][]" in rendered + doAssert "\"public\".\"status\"[]" in rendered + doAssert renderSql(parseSql(rendered, considerTypeParams = true)) == rendered + + let model = generateModelCode(schema, "measurements.sql", ImportTarget.postgre) + doAssert "typ: dbFloat, typeName: \"double precision\"" in model + doAssert "typ: dbArray, typeName: \"text[]\"" in model + doAssert "typ: dbArray, typeName: \"uuid[]\"" in model + doAssert "typ: dbArray, typeName: \"numeric[][]\"" in model + doAssert "typ: dbArray, typeName: \"public.status[]\"" in model + +block malformed_array_types: + doAssertRaises(SqlParseError): + discard parseSql("create table records (tags text[);") + doAssertRaises(SqlParseError): + discard parseSql("create table records (tags text[invalid]);") diff --git a/tests/tsqlite_postgres_expressions.nim b/tests/tsqlite_postgres_expressions.nim new file mode 100644 index 0000000..dfdd2a5 --- /dev/null +++ b/tests/tsqlite_postgres_expressions.nim @@ -0,0 +1,24 @@ +import std/assertions +import ormin +importModel(DbBackend.sqlite, "model_sqlite", includeStatic = true) + +static: + var db: DbConn + doAssert not compiles(block: + discard query: + select tb_serial(sqlCast(typinteger, "text")) + ) + doAssert not compiles(block: + discard query: + select tb_serial(typinteger) + where typinteger == any(typinteger) + ) + doAssert not compiles(block: + discard query: + select tb_json(typjson ->> "key") + ) + doAssert not compiles(block: + discard query: + select tb_serial(typinteger) + where isDistinctFrom(typinteger, nil) + ) From 313d7040c05956085b71a31dce2ebcbfe2436c97 Mon Sep 17 00:00:00 2001 From: Jaremy Creechley Date: Sat, 14 Nov 2026 03:46:26 +0200 Subject: [PATCH 2/5] Bump version to 0.12.0 --- ormin.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ormin.nimble b/ormin.nimble index 7abfa5a..4f59db0 100644 --- a/ormin.nimble +++ b/ormin.nimble @@ -1,6 +1,6 @@ # Package -version = "0.10.0" +version = "0.12.0" author = "Araq" description = "Prepared SQL statement generator. A lightweight ORM." license = "MIT" From 60f7b839e6da88e683220aa0f2d58d4fdc5a6f01 Mon Sep 17 00:00:00 2001 From: Jaremy Creechley Date: Sat, 14 Nov 2026 03:55:08 +0200 Subject: [PATCH 3/5] Bind Nim sequences as PostgreSQL arrays --- README.md | 20 +++++--- ormin/ormin_postgre.nim | 30 +++++++++++- ormin/queries.nim | 47 +++++++++++++++---- tests/tpostgres_expressions.nim | 83 +++++++++++++++++++++++++++++++++ 4 files changed, 163 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index afbf7cf..78f494a 100644 --- a/README.md +++ b/README.md @@ -191,11 +191,11 @@ parameter, and PostgreSQL performs the conversion. This works with columns, expressions, `?` Nim parameters, and `%` JSON parameters. ```nim -let ids = "{1,3,5}" # PostgreSQL array text +let ids = @[1, 3, 5] let required = %*{"enabled": true} let rows = query: select records(id, (payload ->> "name") as name) - where id == any(sqlCast(?ids, "bigint[]")) and + where id == any(?ids) and payload @> sqlCast(?required, "jsonb") orderby id ``` @@ -206,8 +206,8 @@ routines: | DSL expression | PostgreSQL expression | | --- | --- | | `sqlCast(?value, "uuid")` | `($1)::uuid` | -| `id == any(sqlCast(?ids, "bigint[]"))` | `id = ANY(($1)::bigint[])` | -| `id != all(sqlCast(?ids, "bigint[]"))` | `id <> ALL(($1)::bigint[])` | +| `id == any(?ids)` | `id = ANY($1)` | +| `id != all(?ids)` | `id <> ALL($1)` | | `payload -> "items"` | JSON extraction with `->` | | `payload ->> "name"` | Text extraction with `->>` | | `jsonPath(payload, ?path)` | JSON path extraction with `#>` | @@ -219,10 +219,18 @@ routines: `<@` also supports contained-by comparisons for JSONB and arrays; `@>` supports array containment. JSON extraction accepts text keys or integer indexes. For a -bound numeric index, use `sqlCast(?index, "integer")`. Pass JSON paths as text -arrays, such as `"{settings,enabled}"`. Missing JSON paths can be mapped to +bound numeric index, use `sqlCast(?index, "integer")`. Pass JSON paths as Nim +sequences, such as `@["settings", "enabled"]`. Missing JSON paths can be mapped to `Option` fields with `query(T)`. +PostgreSQL array parameters accept one-dimensional Nim sequences and fixed arrays +of strings, numbers, booleans, or `Option` values. Ormin encodes each element and +sends the array as one bound parameter. Empty sequences become empty arrays; +`none(seq[T])` becomes SQL NULL. Strings containing NUL raise `ValueError`, since +PostgreSQL text cannot contain NUL. A PostgreSQL array text string remains accepted +when already available. Use `sqlCast(?ids, "bigint[]")` when PostgreSQL needs an +explicit array type. + Cast type names must be supported built-in PostgreSQL types written as string literals. Supported types include text/varchar, UUID, JSON/JSONB, booleans, integers, real/float4/float8/double precision, numeric/decimal, date/time/timestamp, diff --git a/ormin/ormin_postgre.nim b/ormin/ormin_postgre.nim index bfeca82..6ce74d5 100644 --- a/ormin/ormin_postgre.nim +++ b/ormin/ormin_postgre.nim @@ -1,4 +1,4 @@ -import strutils, db_connector/postgres, json, times +import strutils, db_connector/postgres, json, times, options import db_connector/db_common import query_hooks @@ -39,6 +39,34 @@ proc prepareStmt*(db: DbConn; q: string): PStmt = # never cleared. Execute parameterized SQL directly instead. result = q +proc appendArrayElement[T](dest: var string; value: T) = + when T is Option: + if value.isSome: + appendArrayElement(dest, value.get()) + else: + dest.add "NULL" + elif T is string or T is SomeInteger or T is SomeFloat or T is bool: + let text = $value + dest.add '"' + for c in text: + if c == '\0': + raise newException(ValueError, "PostgreSQL array elements cannot contain NUL") + if c in {'"', '\\'}: + dest.add '\\' + dest.add c + dest.add '"' + else: + {.error: "PostgreSQL array elements must be strings, numbers, booleans, or Option values".} + +proc postgresArrayText*[T](values: openArray[T]): string = + ## Encode a one-dimensional Nim array or sequence as a PostgreSQL array parameter. + result = "{" + for i, value in values: + if i > 0: + result.add ',' + appendArrayElement(result, value) + result.add '}' + template startBindings*(s: PStmt; n: int) {.dirty.} = # pparams is a duplicated array to keep the Nim string alive # for the duration of the query. This is safer than relying diff --git a/ormin/queries.nim b/ormin/queries.nim index 3a5a07c..4ea79d8 100644 --- a/ormin/queries.nim +++ b/ormin/queries.nim @@ -378,6 +378,12 @@ proc toNimType(t: DbTypeKind): NimNode {.compileTime.} = proc toNimType(t: DbType): NimNode {.compileTime.} = toNimType(t.kind) +proc paramNimType(t: DbTypeKind; isJson: bool): NimNode {.compileTime.} = + when dbBackend == DbBackend.postgre: + if t == dbArray and not isJson: + return ident"arrayParam" + toNimType(t) + proc escIdent(dest: var string; src: string) = if allCharsInSet(src, {'\33'..'\127'}): dest.add(src) @@ -553,10 +559,15 @@ proc renderJsonAccess(left, right: NimNode; op: string; q: var string; DbType(kind: (if op in ["->>", "#>>"]: dbVarchar else: dbJson)) proc renderArrayComparison(n: NimNode; q: var string; - params: var Params; qb: QueryBuilder): DbType = + params: var Params; qb: QueryBuilder; element: DbType): DbType = requirePostgres(n) expectLen(n, 2) q.add nodeName(n[0]) & "(" + if n[1].kind == nnkPrefix and nodeName(n[1][0]) == "?": + q.add placeholder(qb) + params.add((ex: n[1][1], typ: ident"arrayParam", isJson: false)) + q.add ')' + return element let arrayType = cond(n[1], q, params, DbType(kind: dbUnknown), qb) if arrayType.kind != dbArray or not arrayType.name.endsWith("[]"): macros.error "ANY/ALL requires a typed array expression", n[1] @@ -720,7 +731,7 @@ proc cond(n: NimNode; q: var string; params: var Params; qb.env = @[env[1]] let b = if n[2].kind == nnkCall and nodeName(n[2][0]) in ["any", "all", "some"]: - renderArrayComparison(n[2], q, params, qb) + renderArrayComparison(n[2], q, params, qb, a) else: cond(n[2], q, params, a, qb) checkCompatible a, b, n @@ -775,7 +786,12 @@ proc cond(n: NimNode; q: var string; params: var Params; if result.kind == dbUnknown: macros.error "cannot infer the type of the placeholder", n else: - params.add((ex: n[1], typ: toNimType(result), isJson: op == "%")) + let paramType = + if dbBackend == DbBackend.postgre and result.kind == dbArray and op == "?": + ident"arrayParam" + else: + toNimType(result) + params.add((ex: n[1], typ: paramType, isJson: op == "%")) of "not": result = DbType(kind: dbBool) q.add "not " @@ -809,7 +825,9 @@ proc cond(n: NimNode; q: var string; params: var Params; if value.kind == nnkPrefix and nodeName(value[0]) in ["?", "%"]: q.add placeholder(qb) # PostgreSQL performs the conversion; retain the Nim input's own type. - params.add((ex: value[1], typ: ident"auto", isJson: nodeName(value[0]) == "%")) + let paramType = if result.kind == dbArray and nodeName(value[0]) == "?": + ident"arrayParam" else: ident"auto" + params.add((ex: value[1], typ: paramType, isJson: nodeName(value[0]) == "%")) else: discard cond(value, q, params, DbType(kind: dbUnknown), qb) q.add ")::" & result.name @@ -981,7 +999,8 @@ proc generateRoutine(name: NimNode, q: QueryBuilder; finalParams.add newIdentDefs(p.ex, ident"JsonNode") body.add buildHookedParamBinding(prepStmt, i, p.ex, p.typ, true) else: - finalParams.add newIdentDefs(p.ex, p.typ) + let paramType = if p.typ.eqIdent("arrayParam"): ident"auto" else: p.typ + finalParams.add newIdentDefs(p.ex, paramType) body.add buildHookedParamBinding(prepStmt, i, p.ex, p.typ, false) inc i body.add newCall(bindSym"startQuery", ident"db", prepStmt) @@ -1069,7 +1088,8 @@ proc selectAll(q: QueryBuilder; tabIndex: int; arg, lineInfo: NimNode) = if q.coln > 0: q.head.add ", " escIdent(q.head, a.name) inc q.coln - q.params.add((ex: field(), typ: toNimType(a.typ), isJson: q.retTypeIsJson)) + q.params.add((ex: field(), typ: paramNimType(a.typ, q.retTypeIsJson), + isJson: q.retTypeIsJson)) if q.values.len > 0: q.values.add ", " q.values.add placeholder(q) of qkUpdate: @@ -1080,7 +1100,8 @@ proc selectAll(q: QueryBuilder; tabIndex: int; arg, lineInfo: NimNode) = if q.coln > 0: q.head.add ", " escIdent(q.head, a.name) inc q.coln - q.params.add((ex: field(), typ: toNimType(a.typ), isJson: q.retTypeIsJson)) + q.params.add((ex: field(), typ: paramNimType(a.typ, q.retTypeIsJson), + isJson: q.retTypeIsJson)) q.head.add " = " q.head.add placeholder(q) else: @@ -1144,7 +1165,8 @@ proc tableSel(n: NimNode; q: QueryBuilder) = if q.coln > 0: q.head.add ", " escIdent(q.head, colname) inc q.coln - q.params.add((ex: col[1], typ: toNimType(coltype), isJson: op == "%")) + q.params.add((ex: col[1], typ: paramNimType(coltype.kind, op == "%"), + isJson: op == "%")) if q.kind == qkUpdate: q.head.add " = " q.head.add placeholder(q) @@ -1665,7 +1687,7 @@ proc makeSeq(retType: NimNode; singleRow: bool): NimNode = result = retType proc buildHookedParamBinding(prepStmt: NimNode; idx: int; ex, typ: NimNode; isJson: bool): NimNode = - if typ.kind == nnkIdent and typ.eqIdent("auto"): + if typ.kind == nnkIdent and (typ.eqIdent("auto") or typ.eqIdent("arrayParam")): if isJson: return quote do: block: @@ -1676,6 +1698,7 @@ proc buildHookedParamBinding(prepStmt: NimNode; idx: int; ex, typ: NimNode; isJs bindParam(db, `prepStmt`, `idx`, value.str, string) else: bindParam(db, `prepStmt`, `idx`, value, JsonNode) + let arrayParam = newLit(typ.eqIdent("arrayParam")) return quote do: block: let value = `ex` @@ -1688,7 +1711,11 @@ proc buildHookedParamBinding(prepStmt: NimNode; idx: int; ex, typ: NimNode; isJs if converted.isNull: bindNullParam(db, `prepStmt`, `idx`) else: - bindParam(db, `prepStmt`, `idx`, converted.value, InputType) + when `arrayParam` and (InputType is seq or InputType is array): + let encoded = postgresArrayText(converted.value) + bindParam(db, `prepStmt`, `idx`, encoded, string) + else: + bindParam(db, `prepStmt`, `idx`, converted.value, InputType) if isJson: return newCall(bindSym"bindParamJson", ident"db", prepStmt, newLit(idx), ex, typ) diff --git a/tests/tpostgres_expressions.nim b/tests/tpostgres_expressions.nim index 05f3611..5c180e3 100644 --- a/tests/tpostgres_expressions.nim +++ b/tests/tpostgres_expressions.nim @@ -93,6 +93,89 @@ proc checkExpressions(db: DbConn) = orderby id doAssert byMatrix == @[1, 2, 3] + block nim_array_parameters: + let ids = @[1, 3] + let selected = query: + select records(id) + where id == any(?ids) + orderby id + doAssert selected == @[1, 3] + let fixedIds = [2, 3] + let fixed = query: + select records(id) + where id == any(sqlCast(?fixedIds, "bigint[]")) + orderby id + doAssert fixed == @[2, 3] + let amounts = @[1.25, 3.75] + let byAmount = query: + select records(id) + where amount == any(?amounts) + orderby id + doAssert byAmount == @[1, 3] + let empty: seq[int] = @[] + let noMatches = query: + select records(id) + where id == any(?empty) + doAssert noMatches.len == 0 + let missing = options.none(seq[int]) + let nullArray = query: + select records(id) + where id == any(?missing) + doAssert nullArray.len == 0 + let tags = @["red", "green"] + let overlapping = query: + select records(id) + where records.tags && ?tags + orderby id + doAssert overlapping == @[1, 2] + let path = @["nested", "enabled"] + let fromPath = query: + select records(jsonPathText(payload, ?path) as value) + where id == 1 + doAssert fromPath == @["true"] + block: + let tags = @["yellow", "violet"] + query: + update records(?tags) + where id == 3 + let updated = query: + select records(id) + where id == 3 and "yellow" == any(tags) + doAssert updated == @[3] + createProc lookupArray: + select records(id) + where id == any(?values) + orderby id + doAssert db.lookupArray(@[1, 3]) == @[1, 3] + + block array_strings_are_encoded_as_data: + let values = @["", "NULL", "comma,value", "quote\"here", "back\\slash", + "{braces}", "'); drop table records; --", " space "] + for value in values: + let found = query: + select records(id) + where id == 1 and sqlCast(?value, "text") == any(sqlCast(?values, "text[]")) + doAssert found == @[1] + let nullable = @[some("NULL"), options.none(string), some("")] + let nullText = "NULL" + let found = query: + select records(id) + where id == 1 and sqlCast(?nullText, "text") == any(sqlCast(?nullable, "text[]")) + doAssert found == @[1] + let nullOnly = @[options.none(string)] + let nullArrayText = "{NULL}" + let nullMatches = query: + select records(id) + where id == 1 and isNotDistinctFrom(sqlCast(?nullOnly, "text[]"), + sqlCast(?nullArrayText, "text[]")) + doAssert nullMatches == @[1] + let nul = @["invalid\0value"] + doAssertRaises(ValueError): + discard query: + select records(id) + where id == 1 and "invalid" == any(sqlCast(?nul, "text[]")) + doAssert pg.getValue(db, sql"select count(*) from records") == "3" + block empty_and_null_arrays: let empty = "{}" let none = query: From 4b71c501533b055d02c67a078a049cfd48823ae4 Mon Sep 17 00:00:00 2001 From: Jaremy Creechley Date: Sat, 14 Nov 2026 04:05:54 +0200 Subject: [PATCH 4/5] Use backtick type names for SQL casts --- README.md | 55 +++++++++------ ormin/queries.nim | 85 ++++++++++++++-------- tests/tpostgres_expressions.nim | 97 ++++++++++++++------------ tests/tsqlite_postgres_expressions.nim | 68 +++++++++++++++++- 4 files changed, 210 insertions(+), 95 deletions(-) diff --git a/README.md b/README.md index 78f494a..a0f03c4 100644 --- a/README.md +++ b/README.md @@ -183,12 +183,35 @@ Joins use the syntax `join Person(name, city) on author == id` where `Person` is The join syntax differs from SQL but simplifies selecting fields from multiple tables by making them more explicit while still maintaing SQL's full query capabilities. -### PostgreSQL expressions +### Casts -Use `sqlCast(value, "type")` when PostgreSQL needs an explicit type. For example, -`sqlCast(?value, "text")` generates `($1)::text`: the value stays a bound -parameter, and PostgreSQL performs the conversion. This works with columns, -expressions, `?` Nim parameters, and `%` JSON parameters. +Use a backtick-quoted database type after `as` to cast a value: + +```nim +let value = 42 +let rows = query: + select records((?value as `text`) as label) +``` + +The cast becomes `($1)::text` on PostgreSQL or `CAST(? AS text)` on SQLite. +The value remains a bound parameter. Casts also work with columns, expressions, +`?` Nim parameters, and `%` JSON parameters. Parenthesize casts inside other +expressions; for example, use ``public_id == (?id as `uuid`)``. + +Backticks after `as` are reserved for cast types. Column aliases use unquoted +identifiers, as in `id as label`; a backtick-quoted alias is rejected. Type names +are checked at compile time against the supported list, so arbitrary SQL and +runtime type names cannot be inserted as types. + +PostgreSQL supports text/varchar, UUID, JSON/JSONB, booleans, integers, +real/float4/float8/double precision, numeric/decimal, date/time/timestamp, +interval, regclass, and their array forms. SQLite supports text/varchar, integer, +and real types, including their common aliases. SQLite rejects PostgreSQL-only +cast types. The backends can behave differently for the same cast: for example, +SQLite converts some invalid numeric text to zero, while PostgreSQL reports an +error. `none(T)` becomes SQL NULL. + +### PostgreSQL expressions ```nim let ids = @[1, 3, 5] @@ -196,7 +219,7 @@ let required = %*{"enabled": true} let rows = query: select records(id, (payload ->> "name") as name) where id == any(?ids) and - payload @> sqlCast(?required, "jsonb") + payload @> (?required as `jsonb`) orderby id ``` @@ -205,21 +228,21 @@ routines: | DSL expression | PostgreSQL expression | | --- | --- | -| `sqlCast(?value, "uuid")` | `($1)::uuid` | +| ``(?value as `uuid`)`` | `($1)::uuid` | | `id == any(?ids)` | `id = ANY($1)` | | `id != all(?ids)` | `id <> ALL($1)` | | `payload -> "items"` | JSON extraction with `->` | | `payload ->> "name"` | Text extraction with `->>` | | `jsonPath(payload, ?path)` | JSON path extraction with `#>` | | `jsonPathText(payload, ?path)` | Text path extraction with `#>>` | -| `payload @> sqlCast(?filter, "jsonb")` | JSONB containment | -| `tags && sqlCast(?tags, "text[]")` | Array overlap | +| ``payload @> (?filter as `jsonb`)`` | JSONB containment | +| ``tags && (?tags as `text[]`)`` | Array overlap | | `isDistinctFrom(note, ?value)` | `note IS DISTINCT FROM $1` | | `isNotDistinctFrom(note, ?value)` | `note IS NOT DISTINCT FROM $1` | `<@` also supports contained-by comparisons for JSONB and arrays; `@>` supports array containment. JSON extraction accepts text keys or integer indexes. For a -bound numeric index, use `sqlCast(?index, "integer")`. Pass JSON paths as Nim +bound numeric index, use ``(?index as `integer`)``. Pass JSON paths as Nim sequences, such as `@["settings", "enabled"]`. Missing JSON paths can be mapped to `Option` fields with `query(T)`. @@ -228,21 +251,13 @@ of strings, numbers, booleans, or `Option` values. Ormin encodes each element an sends the array as one bound parameter. Empty sequences become empty arrays; `none(seq[T])` becomes SQL NULL. Strings containing NUL raise `ValueError`, since PostgreSQL text cannot contain NUL. A PostgreSQL array text string remains accepted -when already available. Use `sqlCast(?ids, "bigint[]")` when PostgreSQL needs an +when already available. Use ``(?ids as `bigint[]`)`` when PostgreSQL needs an explicit array type. -Cast type names must be supported built-in PostgreSQL types written as string -literals. Supported types include text/varchar, UUID, JSON/JSONB, booleans, -integers, real/float4/float8/double precision, numeric/decimal, date/time/timestamp, -interval, regclass, and their array forms. Arbitrary SQL fragments and runtime -type names are rejected. Cast parameters use their Nim input types, so an integer -can be cast to text and a numeric string can be cast to a database number. -`none(T)` becomes SQL NULL. - Model imports accept `double precision` and array columns such as `text[]` and `uuid[]`. PostgreSQL UUID, array, and exact decimal results use Nim strings; arrays retain PostgreSQL's array text format and decimals retain their precision. -These PostgreSQL expression forms are rejected when using the SQLite backend. +The PostgreSQL-specific operators in this section are rejected on SQLite. ### Return Types diff --git a/ormin/queries.nim b/ormin/queries.nim index 4ea79d8..fd1ad81 100644 --- a/ormin/queries.nim +++ b/ormin/queries.nim @@ -537,6 +537,52 @@ proc postgresCastType(name: string; n: NimNode): DbType {.compileTime.} = dbUnknown DbType(kind: kind, name: normalized) +proc castType(n: NimNode): DbType {.compileTime.} = + var name = "" + for part in n: + if part.kind notin {nnkIdent, nnkSym}: + macros.error "cast type must be a backtick-quoted type name", part + let token = part.strVal + if name.len > 0 and not token.startsWith("["): + name.add ' ' + name.add token + when dbBackend == DbBackend.postgre: + result = postgresCastType(name, n) + elif dbBackend == DbBackend.sqlite: + case strutils.splitWhitespace(name).join(" ").toLowerAscii() + of "text", "varchar", "character varying": + result = DbType(kind: dbVarchar, name: "text") + of "int", "integer", "bigint", "smallint", "int2", "int4", "int8": + result = DbType(kind: dbInt, name: "integer") + of "real", "float", "float4", "float8", "double", "double precision": + result = DbType(kind: dbFloat, name: "real") + else: + macros.error "unsupported SQLite cast type: " & name, n + else: + macros.error "casts are not supported for this backend", n + +proc renderCast(n: NimNode; q: var string; params: var Params; + qb: QueryBuilder): DbType = + result = castType(n[2]) + var value = n[1] + while value.kind == nnkPar and value.len == 1: + value = value[0] + when dbBackend == DbBackend.sqlite: + q.add "cast(" + else: + q.add '(' + if value.kind == nnkPrefix and nodeName(value[0]) in ["?", "%"]: + q.add placeholder(qb) + let paramType = if result.kind == dbArray and nodeName(value[0]) == "?": + ident"arrayParam" else: ident"auto" + params.add((ex: value[1], typ: paramType, isJson: nodeName(value[0]) == "%")) + else: + discard cond(value, q, params, DbType(kind: dbUnknown), qb) + when dbBackend == DbBackend.sqlite: + q.add " as " & result.name & ")" + else: + q.add ")::" & result.name + proc renderJsonAccess(left, right: NimNode; op: string; q: var string; params: var Params; qb: QueryBuilder): DbType = requirePostgres(left) @@ -754,14 +800,17 @@ proc cond(n: NimNode; q: var string; params: var Params; checkCompatibleSet a, b, n result = DbType(kind: dbBool) of "as": - result = cond(n[1], q, params, expected, qb) - q.add " as " - expectKind n[2], nnkIdent - let alias = $n[2] - escIdent(q, alias) - qb.colAliases.add((alias, result)) - if expected.kind != dbUnknown: - checkCompatible result, expected, n + if n[2].kind == nnkAccQuoted: + result = renderCast(n, q, params, qb) + else: + result = cond(n[1], q, params, expected, qb) + q.add " as " + expectKind n[2], nnkIdent + let alias = $n[2] + escIdent(q, alias) + qb.colAliases.add((alias, result)) + if expected.kind != dbUnknown: + checkCompatible result, expected, n of "&": let a = cond(n[1], q, params, DbType(kind: dbVarchar), qb) q.add " || " @@ -812,26 +861,6 @@ proc cond(n: NimNode; q: var string; params: var Params; result = cond(n[1], q, params, DbType(kind: dbUnknown), qb) of nnkCall: let op = nodeName(n[0]) - if op == "sqlCast": - requirePostgres(n) - expectLen(n, 3) - if n[2].kind notin {nnkStrLit, nnkRStrLit, nnkTripleStrLit}: - macros.error "sqlCast requires a literal PostgreSQL type name", n[2] - result = postgresCastType(n[2].strVal, n[2]) - var value = n[1] - while value.kind == nnkPar and value.len == 1: - value = value[0] - q.add '(' - if value.kind == nnkPrefix and nodeName(value[0]) in ["?", "%"]: - q.add placeholder(qb) - # PostgreSQL performs the conversion; retain the Nim input's own type. - let paramType = if result.kind == dbArray and nodeName(value[0]) == "?": - ident"arrayParam" else: ident"auto" - params.add((ex: value[1], typ: paramType, isJson: nodeName(value[0]) == "%")) - else: - discard cond(value, q, params, DbType(kind: dbUnknown), qb) - q.add ")::" & result.name - return if op in ["jsonPath", "jsonPathText"]: expectLen(n, 3) let sqlOp = if op == "jsonPath": "#>" else: "#>>" diff --git a/tests/tpostgres_expressions.nim b/tests/tpostgres_expressions.nim index 5c180e3..63fd69b 100644 --- a/tests/tpostgres_expressions.nim +++ b/tests/tpostgres_expressions.nim @@ -21,30 +21,34 @@ proc checkExpressions(db: DbConn) = let numericText = "2.5" let enabled = "true" let rows = query: - select records(sqlCast(?number, "text") as label, - sqlCast(?numericText, "double precision") as amount, - sqlCast(?enabled, "boolean") as enabled) + select records((?number as `text`) as label, + (?numericText as `double precision`) as amount, + (?enabled as `boolean`) as enabled) where id == 1 doAssert rows == @[("42", 2.5, true)] let numeric = "123456789012345678.123456" let exact = query: - select records(sqlCast(?numeric, "numeric") as value, exact_amount) + select records((?numeric as `numeric`) as value, exact_amount) where id == 1 doAssert exact == @[(numeric, numeric)] block cast_columns_and_uuid_parameters: let uuid = "00000000-0000-0000-0000-000000000002" let rows = query: - select records(sqlCast(id, "text") as label, public_id) - where public_id == sqlCast(?uuid, "uuid") + select records((id as `text`) as label, public_id) + where public_id == (?uuid as `uuid`) doAssert rows == @[("2", uuid)] + let aliasNamedText = query: + select records(id as text) + where id == 2 + doAssert aliasNamedText == @[2] block null_casts: let missing = none(string) type Row = object value: Option[int] let rows = query(Row): - select records(sqlCast(?missing, "bigint") as value) + select records((?missing as `bigint`) as value) where id == 1 doAssert rows == @[Row(value: none(int))] @@ -53,27 +57,27 @@ proc checkExpressions(db: DbConn) = let document = %*{"name": "alpha"} let input = %*{"number": "42", "object": {"ok": true}, "missing": nil} let rows = query: - select records(sqlCast(?text, "jsonb") as first, - sqlCast(?document, "jsonb") as second, - sqlCast(%input["number"], "bigint") as number, - sqlCast(%input["object"], "jsonb") as objectValue) + select records((?text as `jsonb`) as first, + (?document as `jsonb`) as second, + (%input["number"] as `bigint`) as number, + (%input["object"] as `jsonb`) as objectValue) where id == 1 doAssert rows == @[(document, document, 42, %*{"ok": true})] let absent = query: select records(id) - where isNotDistinctFrom(note, sqlCast(%input["missing"], "text")) + where isNotDistinctFrom(note, (%input["missing"] as `text`)) doAssert absent == @[1] block array_membership: let ids = "{1,3}" let selected = query: select records(id) - where id == any(sqlCast(?ids, "bigint[]")) + where id == any((?ids as `bigint[]`)) orderby id doAssert selected == @[1, 3] let excluded = query: select records(id) - where id != all(sqlCast(?ids, "bigint[]")) + where id != all((?ids as `bigint[]`)) orderby id doAssert excluded == @[2] let byTag = query: @@ -84,12 +88,12 @@ proc checkExpressions(db: DbConn) = let uuids = "{00000000-0000-0000-0000-000000000001}" let byUuid = query: select records(id) - where public_id == any(sqlCast(?uuids, "uuid[]")) + where public_id == any((?uuids as `uuid[]`)) doAssert byUuid == @[1] let multidimensional = "{{1,2},{3,4}}" let byMatrix = query: select records(id) - where id == any(sqlCast(?multidimensional, "bigint[][]")) + where id == any((?multidimensional as `bigint[][]`)) orderby id doAssert byMatrix == @[1, 2, 3] @@ -103,7 +107,7 @@ proc checkExpressions(db: DbConn) = let fixedIds = [2, 3] let fixed = query: select records(id) - where id == any(sqlCast(?fixedIds, "bigint[]")) + where id == any((?fixedIds as `bigint[]`)) orderby id doAssert fixed == @[2, 3] let amounts = @[1.25, 3.75] @@ -154,43 +158,43 @@ proc checkExpressions(db: DbConn) = for value in values: let found = query: select records(id) - where id == 1 and sqlCast(?value, "text") == any(sqlCast(?values, "text[]")) + where id == 1 and (?value as `text`) == any((?values as `text[]`)) doAssert found == @[1] let nullable = @[some("NULL"), options.none(string), some("")] let nullText = "NULL" let found = query: select records(id) - where id == 1 and sqlCast(?nullText, "text") == any(sqlCast(?nullable, "text[]")) + where id == 1 and (?nullText as `text`) == any((?nullable as `text[]`)) doAssert found == @[1] let nullOnly = @[options.none(string)] let nullArrayText = "{NULL}" let nullMatches = query: select records(id) - where id == 1 and isNotDistinctFrom(sqlCast(?nullOnly, "text[]"), - sqlCast(?nullArrayText, "text[]")) + where id == 1 and isNotDistinctFrom((?nullOnly as `text[]`), + (?nullArrayText as `text[]`)) doAssert nullMatches == @[1] let nul = @["invalid\0value"] doAssertRaises(ValueError): discard query: select records(id) - where id == 1 and "invalid" == any(sqlCast(?nul, "text[]")) + where id == 1 and "invalid" == any((?nul as `text[]`)) doAssert pg.getValue(db, sql"select count(*) from records") == "3" block empty_and_null_arrays: let empty = "{}" let none = query: select records(id) - where id == any(sqlCast(?empty, "bigint[]")) + where id == any((?empty as `bigint[]`)) doAssert none.len == 0 let allRows = query: select records(id) - where id != all(sqlCast(?empty, "bigint[]")) + where id != all((?empty as `bigint[]`)) orderby id doAssert allRows == @[1, 2, 3] let missing = options.none(string) let nullArray = query: select records(id) - where id == any(sqlCast(?missing, "bigint[]")) + where id == any((?missing as `bigint[]`)) doAssert nullArray.len == 0 block json_extraction_and_paths: @@ -198,13 +202,13 @@ proc checkExpressions(db: DbConn) = let rows = query: select records((payload ->> "name") as name, ((payload -> "items") ->> 1) as item, - jsonPath(payload, sqlCast(?path, "text[]")) as enabled, - sqlCast(jsonPathText(payload, ?path), "boolean") as active) + jsonPath(payload, (?path as `text[]`)) as enabled, + (jsonPathText(payload, ?path) as `boolean`) as active) where id == 1 doAssert rows == @[("alpha", "20", %true, true)] let index = 0 let first = query: - select records(((payload -> "items") ->> sqlCast(?index, "integer")) as item) + select records(((payload -> "items") ->> (?index as `integer`)) as item) where id == 1 doAssert first == @["10"] type Row = object @@ -218,20 +222,20 @@ proc checkExpressions(db: DbConn) = let document = %*{"nested": {"enabled": true}} let matching = query: select records(id) - where payload @> sqlCast(?document, "jsonb") + where payload @> (?document as `jsonb`) doAssert matching == @[1] let reverse = query: select records(id) - where sqlCast(?document, "jsonb") <@ payload + where (?document as `jsonb`) <@ payload doAssert reverse == @[1] let tags = "{red}" let containsTag = query: select records(id) - where records.tags @> sqlCast(?tags, "text[]") + where records.tags @> (?tags as `text[]`) doAssert containsTag == @[1] let overlap = query: select records(id) - where records.tags && sqlCast(?tags, "text[]") + where records.tags && (?tags as `text[]`) doAssert overlap == @[1] block null_safe_comparisons: @@ -253,10 +257,10 @@ proc checkExpressions(db: DbConn) = block generated_routines_and_parameter_order: createProc lookupId: select records(id) - where sqlCast(id, "text") == sqlCast(?value, "text") and id >= ?minimum + where (id as `text`) == (?value as `text`) and id >= ?minimum createIter lookupIds: select records(id) - where id == any(sqlCast(?values, "bigint[]")) + where id == any((?values as `bigint[]`)) orderby id doAssert db.lookupId(2, 1) == @[2] doAssert db.lookupId("3", 1) == @[3] @@ -267,28 +271,28 @@ proc checkExpressions(db: DbConn) = let first = "alpha" let second = 2 let found = query: - with chosen(select records(id) where (payload ->> "name") == sqlCast(?first, "text")) + with chosen(select records(id) where (payload ->> "name") == (?first as `text`)) select chosen(id) - where id < sqlCast(?second, "bigint") + where id < (?second as `bigint`) doAssert found == @[1] block ctes_preserve_postgres_column_types: let uuid = "00000000-0000-0000-0000-000000000001" let selected = query: - with chosen(select records(id, public_id, sqlCast(tags, "text[]") as labels)) + with chosen(select records(id, public_id, (tags as `text[]`) as labels)) select chosen(id, labels) - where "red" == any(labels) and public_id == sqlCast(?uuid, "uuid") + where "red" == any(labels) and public_id == (?uuid as `uuid`) doAssert selected == @[(1, "{red,blue}")] let allColumns = query: with chosen(select records(_)) select chosen(id) - where "red" == any(tags) and public_id == sqlCast(?uuid, "uuid") + where "red" == any(tags) and public_id == (?uuid as `uuid`) doAssert allColumns == @[1] block cast_values_remain_bound: let value = "x'); drop table records; --" query: - update records(note = sqlCast(?value, "text")) + update records(note = (?value as `text`)) where id == 2 doAssert pg.getValue(db, sql"select note from records where id = 2") == value doAssert pg.getValue(db, sql"select count(*) from records") == "3" @@ -297,7 +301,7 @@ proc checkExpressions(db: DbConn) = let invalid = "not an integer" doAssertRaises(DbError): discard query: - select records(sqlCast(?invalid, "bigint") as value) + select records((?invalid as `bigint`) as value) where id == 1 doAssert pg.getValue(db, sql"select count(*) from records") == "3" @@ -305,12 +309,15 @@ static: var db: DbConn doAssert not compiles(block: discard query: - select records(sqlCast(id, "text); select 1; --")) + select records((id as `not_a_type`) as value) + ) + doAssert not compiles(block: + discard query: + select records(id as `column_alias`) ) doAssert not compiles(block: - let dynamicType = "text" discard query: - select records(sqlCast(id, dynamicType)) + select records((id as `text`) as `column_alias`) ) doAssert not compiles(block: discard query: @@ -327,7 +334,7 @@ static: ) doAssert not compiles(block: discard query: - select records(jsonPathText(payload, sqlCast("{}", "uuid[]"))) + select records(jsonPathText(payload, ("{}" as `uuid[]`))) ) when defined(postgre): diff --git a/tests/tsqlite_postgres_expressions.nim b/tests/tsqlite_postgres_expressions.nim index dfdd2a5..435ab0b 100644 --- a/tests/tsqlite_postgres_expressions.nim +++ b/tests/tsqlite_postgres_expressions.nim @@ -1,4 +1,5 @@ -import std/assertions +import std/[assertions, json, options] +import db_connector/db_sqlite as sq except DbConn, open, close, dbError import ormin importModel(DbBackend.sqlite, "model_sqlite", includeStatic = true) @@ -6,7 +7,23 @@ static: var db: DbConn doAssert not compiles(block: discard query: - select tb_serial(sqlCast(typinteger, "text")) + select tb_serial((typinteger as `uuid`) as value) + ) + doAssert not compiles(block: + discard query: + select tb_serial((typinteger as `integer[]`) as value) + ) + doAssert not compiles(block: + discard query: + select tb_serial(typinteger as `column_alias`) + ) + doAssert not compiles(block: + discard query: + select tb_serial((typinteger as `text`) as `column_alias`) + ) + doAssert not compiles(block: + discard query: + select tb_serial(typinteger as "text") ) doAssert not compiles(block: discard query: @@ -22,3 +39,50 @@ static: select tb_serial(typinteger) where isDistinctFrom(typinteger, nil) ) + +let db = open(":memory:", "", "", "") +sq.exec(db, sql"create table tb_serial (typserial integer primary key, typinteger integer not null)") +sq.exec(db, sql"insert into tb_serial values (1, 42)") + +block sqlite_casts: + let number = 42 + let numericText = "2.5" + let rows = query: + select tb_serial((?number as `text`) as label, + (?numericText as `double precision`) as value, + (typinteger as `text`) as columnValue) + where typserial == 1 + doAssert rows == @[("42", 2.5, "42")] + let aliasNamedText = query: + select tb_serial(typinteger as text) + where typserial == 1 + doAssert aliasNamedText == @[42] + let input = %*{"value": "12"} + let converted = query: + select tb_serial((%input["value"] as `integer`) as value) + where typserial == 1 + doAssert converted == @[12] + let invalidNumber = "not a number" + let sqliteConversion = query: + select tb_serial((?invalidNumber as `integer`) as value) + where typserial == 1 + doAssert sqliteConversion == @[0] + type Row = object + value: Option[int] + let missing = none(string) + let nullValue = query(Row): + select tb_serial((?missing as `integer`) as value) + where typserial == 1 + doAssert nullValue == @[Row(value: none(int))] + createProc castValue: + select tb_serial((?value as `text`) as label) + where typserial == 1 + doAssert db.castValue(42) == @["42"] + doAssert db.castValue("hello") == @["hello"] + let injection = "x'); drop table tb_serial; --" + let bound = query: + select tb_serial((?injection as `text`) as value) + where typserial == 1 + doAssert bound == @[injection] + doAssert sq.getValue(db, sql"select count(*) from tb_serial") == "1" +close(db) From 458df02733572ed3d34393446c7ee7e82ce412b3 Mon Sep 17 00:00:00 2001 From: Jaremy Creechley Date: Sat, 14 Nov 2026 04:17:30 +0200 Subject: [PATCH 5/5] Add SQLite list and JSON expression support --- README.md | 31 ++++- ormin/ormin_sqlite.nim | 32 ++++- ormin/queries.nim | 52 +++++++- tests/tsqlite_postgres_expressions.nim | 166 ++++++++++++++++++++++++- 4 files changed, 273 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a0f03c4..df989be 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,34 @@ cast types. The backends can behave differently for the same cast: for example, SQLite converts some invalid numeric text to zero, while PostgreSQL reports an error. `none(T)` becomes SQL NULL. +### List membership and JSON extraction + +PostgreSQL and SQLite can compare a column against a bound Nim sequence or +fixed-size array: + +```nim +let ids = @[1, 3, 5] +let rows = query: + select records(id) + where id == any(?ids) + orderby id +``` + +The sequence stays one bound parameter. PostgreSQL receives an array; SQLite +receives a JSON array and searches it with `json_each`. SQLite supports +`== any(?ids)`, `== some(?ids)`, and `!= all(?ids)` for bound sequences; +other quantified comparisons are currently PostgreSQL-only. Both backends +support empty sequences, `none(seq[T])`, and `Option` elements. On SQLite, +strings containing NUL, non-finite floating-point values, and unsigned integers +outside the signed 64-bit range raise `ValueError`. + +Both backends support JSON extraction with `->` and `->>`, and the +`isDistinctFrom` and `isNotDistinctFrom` NULL-safe comparison helpers. SQLite +JSON operators follow SQLite's path and value rules: for example, extracting +JSON `true` as text produces `"1"` on SQLite and `"true"` on PostgreSQL. +SQLite JSON support requires version 3.38 or later with JSON enabled; NULL-safe +comparisons require SQLite 3.39 or later. + ### PostgreSQL expressions ```nim @@ -257,7 +285,8 @@ explicit array type. Model imports accept `double precision` and array columns such as `text[]` and `uuid[]`. PostgreSQL UUID, array, and exact decimal results use Nim strings; arrays retain PostgreSQL's array text format and decimals retain their precision. -The PostgreSQL-specific operators in this section are rejected on SQLite. +JSON path helpers, JSONB containment, and array containment and overlap remain +PostgreSQL-only. ### Return Types diff --git a/ormin/ormin_sqlite.nim b/ormin/ormin_sqlite.nim index 2126cf4..f5ab320 100644 --- a/ormin/ormin_sqlite.nim +++ b/ormin/ormin_sqlite.nim @@ -1,7 +1,7 @@ {.deadCodeElim: on.} -import json, times +import json, times, options, math import db_connector/db_common import db_connector/sqlite3 @@ -21,6 +21,36 @@ type var jsonTimeFormat* = "yyyy-MM-dd HH:mm:ss" +proc sqliteArrayElement[T](value: T): JsonNode = + when T is Option: + if value.isSome: sqliteArrayElement(value.get()) + else: newJNull() + elif T is SomeFloat: + if classify(value) in {fcNan, fcInf, fcNegInf}: + raise newException(ValueError, "SQLite array parameters require finite numbers") + %float(value) + elif T is SomeUnsignedInt: + if uint64(value) > uint64(high(int64)): + raise newException(ValueError, "SQLite array integer is outside the signed 64-bit range") + %int64(value) + elif T is SomeSignedInt: + %int64(value) + elif T is string: + if '\0' in value: + raise newException(ValueError, "SQLite JSON array strings cannot contain NUL") + %value + elif T is bool: + %value + else: + {.error: "SQLite array elements must be strings, numbers, booleans, or Option values".} + +proc sqliteArrayJson*[T](values: openArray[T]): string = + ## Encode a one-dimensional Nim array as a JSON parameter for SQLite. + var items = newJArray() + for value in values: + items.add sqliteArrayElement(value) + result = $items + proc dbError*(db: DbConn) {.noreturn.} = ## raises a DbError exception. var e: ref DbError diff --git a/ormin/queries.nim b/ormin/queries.nim index fd1ad81..586b3d6 100644 --- a/ormin/queries.nim +++ b/ormin/queries.nim @@ -585,7 +585,14 @@ proc renderCast(n: NimNode; q: var string; params: var Params; proc renderJsonAccess(left, right: NimNode; op: string; q: var string; params: var Params; qb: QueryBuilder): DbType = - requirePostgres(left) + when dbBackend == DbBackend.sqlite: + if op in ["#>", "#>>"]: + macros.error "JSON path helpers require the PostgreSQL backend", left + elif dbBackend != DbBackend.postgre: + requirePostgres(left) + when dbBackend == DbBackend.sqlite: + if op == "->>": + q.add "cast(" q.add '(' let source = cond(left, q, params, DbType(kind: dbJson), qb) if source.kind != dbJson: @@ -602,6 +609,9 @@ proc renderJsonAccess(left, right: NimNode; op: string; q: var string; elif key.kind notin {dbVarchar, dbInt, dbSerial}: macros.error "JSON extraction requires a text key or integer index", right q.add ')' + when dbBackend == DbBackend.sqlite: + if op == "->>": + q.add " as text)" DbType(kind: (if op in ["->>", "#>>"]: dbVarchar else: dbJson)) proc renderArrayComparison(n: NimNode; q: var string; @@ -767,6 +777,24 @@ proc cond(n: NimNode; q: var string; params: var Params; if env.len == 2: qb.env = @[env[0]] let a = cond(n[1], q, params, DbType(kind: dbUnknown), qb) + when dbBackend == DbBackend.sqlite: + if n[2].kind == nnkCall and nodeName(n[2][0]) in ["any", "all", "some"]: + let quantifier = nodeName(n[2][0]) + if not ((op == "==" and quantifier in ["any", "some"]) or + (op == "!=" and quantifier == "all")): + macros.error "SQLite supports == any/some and != all with bound sequences", n + expectLen(n[2], 2) + let argument = n[2][1] + if argument.kind != nnkPrefix or nodeName(argument[0]) != "?": + macros.error "SQLite array comparison requires a bound Nim sequence", argument + if env.len == 2: + qb.env = @[env[1]] + q.add (if op == "==": " in (select value from json_each(" else: + " not in (select value from json_each(") + q.add placeholder(qb) + params.add((ex: argument[1], typ: ident"sqliteArrayParam", isJson: false)) + q.add "))" + return DbType(kind: dbBool) q.add ' ' if op == "==": q.add equals elif op == "!=": q.add nequals @@ -866,7 +894,8 @@ proc cond(n: NimNode; q: var string; params: var Params; let sqlOp = if op == "jsonPath": "#>" else: "#>>" return renderJsonAccess(n[1], n[2], sqlOp, q, params, qb) if op in ["isDistinctFrom", "isNotDistinctFrom"]: - requirePostgres(n) + when dbBackend notin {DbBackend.postgre, DbBackend.sqlite}: + requirePostgres(n) expectLen(n, 3) q.add '(' let a = cond(n[1], q, params, DbType(kind: dbUnknown), qb) @@ -1028,7 +1057,8 @@ proc generateRoutine(name: NimNode, q: QueryBuilder; finalParams.add newIdentDefs(p.ex, ident"JsonNode") body.add buildHookedParamBinding(prepStmt, i, p.ex, p.typ, true) else: - let paramType = if p.typ.eqIdent("arrayParam"): ident"auto" else: p.typ + let paramType = if p.typ.eqIdent("arrayParam") or p.typ.eqIdent("sqliteArrayParam"): + ident"auto" else: p.typ finalParams.add newIdentDefs(p.ex, paramType) body.add buildHookedParamBinding(prepStmt, i, p.ex, p.typ, false) inc i @@ -1716,6 +1746,22 @@ proc makeSeq(retType: NimNode; singleRow: bool): NimNode = result = retType proc buildHookedParamBinding(prepStmt: NimNode; idx: int; ex, typ: NimNode; isJson: bool): NimNode = + if typ.kind == nnkIdent and typ.eqIdent("sqliteArrayParam"): + return quote do: + block: + let value = `ex` + when value is Option: + type InputType = typeof(value.get()) + else: + type InputType = typeof(value) + when InputType is seq or InputType is array: + var converted: DbValue[InputType] + toQueryHook(converted, value) + # json_each('null') yields one NULL row, preserving NULL-array comparisons. + let encoded = if converted.isNull: "null" else: sqliteArrayJson(converted.value) + bindParam(db, `prepStmt`, `idx`, encoded, string) + else: + {.error: "SQLite array comparison requires a Nim sequence or array".} if typ.kind == nnkIdent and (typ.eqIdent("auto") or typ.eqIdent("arrayParam")): if isJson: return quote do: diff --git a/tests/tsqlite_postgres_expressions.nim b/tests/tsqlite_postgres_expressions.nim index 435ab0b..3fa6e00 100644 --- a/tests/tsqlite_postgres_expressions.nim +++ b/tests/tsqlite_postgres_expressions.nim @@ -1,4 +1,4 @@ -import std/[assertions, json, options] +import std/[algorithm, assertions, json, math, options] import db_connector/db_sqlite as sq except DbConn, open, close, dbError import ormin importModel(DbBackend.sqlite, "model_sqlite", includeStatic = true) @@ -32,12 +32,23 @@ static: ) doAssert not compiles(block: discard query: - select tb_json(typjson ->> "key") + select tb_serial(typinteger ->> "key") ) doAssert not compiles(block: + let values = @[1, 2] discard query: select tb_serial(typinteger) - where isDistinctFrom(typinteger, nil) + where typinteger > any(?values) + ) + doAssert not compiles(block: + let values = "[1,2]" + discard query: + select tb_serial(typinteger) + where typinteger == any(?values) + ) + doAssert not compiles(block: + discard query: + select tb_json(jsonPathText(typjson, "{a}")) ) let db = open(":memory:", "", "", "") @@ -85,4 +96,153 @@ block sqlite_casts: where typserial == 1 doAssert bound == @[injection] doAssert sq.getValue(db, sql"select count(*) from tb_serial") == "1" + +block sqlite_sequence_membership: + sq.exec(db, sql"insert into tb_serial values (2, 7), (3, 11)") + let ids = @[1, 3] + let selected = query: + select tb_serial(typserial) + where typserial == any(?ids) + orderby typserial + doAssert selected == @[1, 3] + let minimum = 10 + let inCte = query: + with chosen(select tb_serial(typserial, typinteger) where typserial == any(?ids)) + select chosen(typserial) + where typinteger >= ?minimum + orderby typserial + doAssert inCte == @[1, 3] + let someRows = query: + select tb_serial(typserial) + where typserial == some(?ids) + orderby typserial + doAssert someRows == @[1, 3] + let fixed = [1, 3] + let excluded = query: + select tb_serial(typserial) + where typserial != all(?fixed) + orderby typserial + doAssert excluded == @[2] + let empty: seq[int] = @[] + type Row = object + value: Option[bool] + let noMatches = query(Row): + select tb_serial((typserial == any(?empty)) as value) + where typserial == 1 + doAssert noMatches == @[Row(value: some(false))] + let allMatch = query(Row): + select tb_serial((typserial != all(?empty)) as value) + where typserial == 1 + doAssert allMatch == @[Row(value: some(true))] + let missing = none(seq[int]) + let nullArray = query(Row): + select tb_serial((typserial == any(?missing)) as value) + where typserial == 1 + doAssert nullArray == @[Row(value: none(bool))] + let nullExclusion = query(Row): + select tb_serial((typserial != all(?missing)) as value) + where typserial == 1 + doAssert nullExclusion == @[Row(value: none(bool))] + let withNull = @[some(1), none(int)] + let nullElement = query(Row): + select tb_serial((typserial == any(?withNull)) as value) + where typserial == 2 + doAssert nullElement == @[Row(value: none(bool))] + createProc findIds: + select tb_serial(typserial) + where typserial == any(?values) + orderby typserial + doAssert db.findIds(@[1, 3]) == @[1, 3] + createIter eachId: + select tb_serial(typserial) + where typserial == any(?values) + orderby typserial + var iterated: seq[int] + for id in db.eachId(@[1, 3]): + iterated.add id + doAssert iterated == @[1, 3] + let tooLarge = @[high(uint64)] + doAssertRaises(ValueError): + discard query: + select tb_serial(typserial) + where typserial == any(?tooLarge) + let notFinite = @[NaN] + doAssertRaises(ValueError): + discard query: + select tb_serial(typserial) + where typserial == any(?notFinite) + sq.exec(db, sql"create table tb_boolean (typboolean boolean not null)") + sq.exec(db, sql"insert into tb_boolean values (0), (1)") + let flags = @[true] + let trueValues = query: + select tb_boolean(typboolean) + where typboolean == any(?flags) + doAssert trueValues == @[true] + +block sqlite_sequence_strings_are_bound: + sq.exec(db, sql"create table tb_string (typstring text not null)") + let values = @["", "NULL", "comma,value", "quote\"here", "back\\slash", + "'); drop table tb_serial; --", " space "] + for value in values: + query: + insert tb_string(typstring = ?value) + let found = query: + select tb_string(typstring) + where typstring == any(?values) + orderby typstring + doAssert found == sorted(values) + let nul = @["nul\0value"] + doAssertRaises(ValueError): + discard query: + select tb_string(typstring) + where typstring == any(?nul) + doAssert sq.getValue(db, sql"select count(*) from tb_serial") == "3" + +block sqlite_json_access: + sq.exec(db, sql"create table tb_json (typjson json not null)") + sq.exec(db, sql"insert into tb_json values (?)", + """{"name":"alpha","nested":{"enabled":true},"items":[10,20],"empty":null}""") + let key = "name" + let rows = query: + select tb_json((typjson ->> ?key) as name, + ((typjson -> "items") ->> 1) as second, + (typjson -> "nested") as nested, + ((typjson -> "nested") -> "enabled") as enabled, + ((typjson -> "nested") ->> "enabled") as enabledText) + doAssert rows == @[("alpha", "20", %*{"enabled": true}, %true, "1")] + let name = "alpha" + let matching = query: + select tb_json((typjson ->> "name") as name) + where (typjson ->> "name") == ?name + doAssert matching == @["alpha"] + type Row = object + missing: Option[string] + let absent = query(Row): + select tb_json((typjson ->> "missing") as missing) + doAssert absent == @[Row(missing: none(string))] + type JsonRow = object + empty, missing: Option[JsonNode] + let jsonNulls = query(JsonRow): + select tb_json((typjson -> "empty") as empty, + (typjson -> "missing") as missing) + doAssert jsonNulls == @[JsonRow(empty: some(newJNull()), missing: none(JsonNode))] + +block sqlite_null_safe_comparisons: + let missing = none(string) + let matches = query: + select tb_serial(typserial) + where isNotDistinctFrom((nil as `text`), ?missing) + orderby typserial + doAssert matches == @[1, 2, 3] + let number = 42 + let different = query: + select tb_serial(typserial) + where isDistinctFrom(typinteger, ?number) + orderby typserial + doAssert different == @[2, 3] + let values = query: + select tb_serial(isDistinctFrom(typinteger, nil) as present, + isNotDistinctFrom(nil, nil) as equal) + where typserial == 1 + doAssert values == @[(true, true)] close(db)