Skip to content

[Bugfix] Enable creation of tables whose fieldName otherwise clashes with SQL keywords such as group #165

@PhilippMDoerner

Description

@PhilippMDoerner

In the nim discord ajusa previously encountered this issue where they had a database, but one of the columns they had was called group.
This causes issues with sqlite's SQL (and likely postgres but I didn't test that). In the language you can avoid those by escaping the name with '.

So minimal reproducible example:

import norm/[model, sqlite]

type A = ref object of Model
    group: string 

let x = A(group: "")
let con = open(":memory:", "", "", "")
con.createTables(x)
Error: unhandled exception: near "group": syntax error [DbError]

The SQL generated is

CREATE TABLE IF NOT EXISTS "A"(group TEXT NOT NULL, id INTEGER NOT NULL PRIMARY KEY)

To fix this, the SQL it would need to generate would be this (can also use " instead of '):

CREATE TABLE IF NOT EXISTS "A"('group' TEXT NOT NULL, id INTEGER NOT NULL PRIMARY KEY)

A similar issue goes for selectAll as it generates for example this sql:

import norm/[model, sqlite]

type A* = ref object of Model
    group*: string 

let con = open(":memory:", "", "", "")

let y = """CREATE TABLE IF NOT EXISTS "A"('group' TEXT NOT NULL, id INTEGER NOT NULL PRIMARY KEY)"""
con.exec(sql y)

var objs = @[A(group: "")]
con.selectAll(objs)
SELECT "A".group, "A".id FROM "A"  WHERE 1

Should be generating

SELECT "A"."group", "A"."id" FROM "A"  WHERE 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions