Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,111 @@ 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.

### Casts

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.

### 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
let ids = @[1, 3, 5]
let required = %*{"enabled": true}
let rows = query:
select records(id, (payload ->> "name") as name)
where id == any(?ids) and
payload @> (?required as `jsonb`)
orderby id
```

These forms work in inline queries and generated `createProc`/`createIter`
routines:

| DSL expression | PostgreSQL expression |
| --- | --- |
| ``(?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 @> (?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 ``(?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)`.

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 ``(?ids as `bigint[]`)`` when PostgreSQL needs an
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.
JSON path helpers, JSONB containment, and array containment and overlap remain
PostgreSQL-only.

### 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.
Expand Down
6 changes: 4 additions & 2 deletions config.nims
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand All @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion ormin.nimble
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
5 changes: 3 additions & 2 deletions ormin/db_types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion ormin/importer_core.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
30 changes: 29 additions & 1 deletion ormin/ormin_postgre.nim
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
32 changes: 31 additions & 1 deletion ormin/ormin_sqlite.nim
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

{.deadCodeElim: on.}

import json, times
import json, times, options, math

import db_connector/db_common
import db_connector/sqlite3
Expand All @@ -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
Expand Down
19 changes: 19 additions & 0 deletions ormin/parsesql_tmp.nim
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,7 @@ type
nkCreateIndex,
nkCreateIndexIfNotExists,
nkEnumDef,
nkArrayType,
nkPragma,
nkAutoIncrement,
nkOnDelete,
Expand Down Expand Up @@ -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)
Expand All @@ -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, "%"):
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading