**Second attempt (working)**
# Custom object with predefined global null: dbNullVal
# exec(db, sql"UPDATE myTable SET age = ? WHERE name = ?", dbNullVal,
"John")
# lib/impure/db_postgres.nim
# __ New
type
ArgObj = object
val: string
isNull: bool
var arg: ArgObj
var dbNullVal*: ArgObj
dbNullVal.isNull = true
proc argType*(v: ArgObj): ArgObj =
return dbNullVal
proc argType*(v: string | int): ArgObj =
arg.val = $v
arg.isNull = false
return arg
# __ Changes to existing
proc dbFormat[T](formatstr: SqlQuery, args: varargs[T, argType]): string =
# varargs[string, `$`] => varargs[T, argType]
result = ""
var a = 0
if args.len > 0 and not string(formatstr).contains("?"):
dbError("""parameter substitution expects "?" """)
if args.len == 0:
return string(formatstr)
else:
for c in items(string(formatstr)):
if c == '?':
# Check bool on arg
if args[a].isNull:
add(result, "NULL")
else:
# Use args.val instead
add(result, dbQuote(args[a].val))
inc(a)
else:
add(result, c)
# varargs[string, `$`] for all is just replaced with varargs[T, argType]
proc exec*[T](db: DbConn, query: SqlQuery, args: varargs[T, argType]) {.
tags: [ReadDbEffect, WriteDbEffect].} =
## executes the query and raises EDB if not successful.
var res = pqexecParams(db, dbFormat(query, args), 0, nil, nil,
nil, nil, 0)
if pqresultStatus(res) != PGRES_COMMAND_OK: dbError(db)
pqclear(res)
Run
- Insert 'NULL' value in Postgres with Nim 0.19.1 without 'nil' ThomasTJdev
- Re: Insert 'NULL' value in Postgres with Nim 0.19.1 witho... Araq
- Re: Insert 'NULL' value in Postgres with Nim 0.19.1 w... ThomasTJdev
- Re: Insert 'NULL' value in Postgres with Nim 0.19... mikra
- Re: Insert 'NULL' value in Postgres with Nim ... mashingan
- Re: Insert 'NULL' value in Postgres with... ThomasTJdev
- Re: Insert 'NULL' value in Postgres ... timothee
- Re: Insert 'NULL' value in Postg... mikra
- Re: Insert 'NULL' value in Postg... ThomasTJdev
- Re: Insert 'NULL' value in Postg... ThomasTJdev
- Re: Insert 'NULL' value in Postg... mikra
- Re: Insert 'NULL' value in Postg... timothee
- Re: Insert 'NULL' value in Postg... ThomasTJdev
- Re: Insert 'NULL' value in Postg... mikra
- Re: Insert 'NULL' value in Postg... ThomasTJdev
- Re: Insert 'NULL' value in Postg... mikra
- Re: Insert 'NULL' value in Postg... ThomasTJdev
- Re: Insert 'NULL' value in Postg... mikra
- Re: Insert 'NULL' value in Postg... rayman22201
- Re: Insert 'NULL' value in Postg... ThomasTJdev
