norm icon indicating copy to clipboard operation
norm copied to clipboard

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

Open PhilippMDoerner opened this issue 1 year ago • 1 comments

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

PhilippMDoerner avatar Aug 14 '22 16:08 PhilippMDoerner

There's an ungoing PR that fixes this by adding quotes around column names.

The PR stuck on test suite update: since the table names are all different now, the entire test suite needs revision and update.

moigagoo avatar Aug 15 '22 08:08 moigagoo