Skip to content

Conversation

@elcritch
Copy link
Contributor

@elcritch elcritch commented Sep 20, 2025

Adds basic support for custom sql functions using importSql pragma:

proc substr(s: string; start, length: int): string {.importSql.}

proc exampleQuery() =
  let prefix = "Mr"
  let res = query:
    select tb_string(substr(typstring, 0, 2))
    where substr(typstring, 0, 2) == ?prefix
  let expected = ss.mapIt($(toRunes(it)[0..1]))
  check res == expected

Function(name: "length", arity: 1, typ: dbInt),
Function(name: "lower", arity: 1, typ: dbVarchar),
Function(name: "upper", arity: 1, typ: dbVarchar),
Function(name: "replace", arity: 3, typ: dbVarchar)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Be nice to upgrade these at some point to also support type checking the args. But alas, not today.

macro importSql*(n: typed): untyped =
## Registers a Nim proc as callable SQL function within the query DSL.
if n.kind notin {nnkProcDef, nnkFuncDef}:
macros.error("{.importSql.} can only be applied to proc or func definitions", n)
Copy link
Contributor Author

@elcritch elcritch Sep 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used GPT5-Codex-High for this. Seems to have done a good job. It checked for conditions I wouldn't have thought to check. I had to cleanup a little bit in the tests.

@Araq Araq merged commit 4ff369c into Araq:master Sep 22, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants