Skip to content

Commit 047d1e1

Browse files
committed
auto add pk when id col exists
Signed-off-by: George Lemon <georgelemon@protonmail.com>
1 parent 0f3adc3 commit 047d1e1

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

src/ozark/query.nim

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,27 +129,34 @@ macro prepareTable*(modelName): untyped =
129129
let fieldName = f[0][1].strVal
130130
types.add(schema[fieldName])
131131

132-
var compositePkCols: seq[string] # to hold column names for composite primary keys
132+
var compositePkCols: seq[string] # to hold column names for primary keys
133133
let columnDefs = types.map(proc(t: SqlNode): string =
134134
var colDef = t[0].strVal & " "
135135
if t[1].kind == nkIdent:
136136
colDef &= t[1].strVal
137137
elif t[1].kind == nkCall:
138138
colDef &= t[1][0].strVal & "(" &
139139
t[1].sons[1..^1].mapIt($it.strVal).join(", ") & ")"
140-
# handle column constraints
141140
if t.len > 2:
142141
for i in 2..<t.len:
143142
if t[i].kind == nkPrimaryKey:
144-
# if it's a primary key constraint, we need to
145-
# add the column name to the compositePkCols list
146143
compositePkCols.add(t[0].strVal)
147144
else:
148145
colDef &= " " & $t[i]
149146
colDef
150147
)
151-
var sql = "CREATE TABLE IF NOT EXISTS " & tableName & " (" &
152-
columnDefs.join(", ")
148+
149+
# fallback if no `{.pk.}` pragma is explicitly declared,
150+
# use `id` when present, as the primary key column by convention
151+
# otherwise the table will be created without a primary key, which
152+
# is not ideal but still functional for basic queries
153+
if compositePkCols.len == 0:
154+
for t in types:
155+
if t[0].strVal == "id":
156+
compositePkCols.add("id")
157+
break
158+
159+
var sql = "CREATE TABLE IF NOT EXISTS " & tableName & " (" & columnDefs.join(", ")
153160
if compositePkCols.len > 0:
154161
sql &= ", PRIMARY KEY (" & compositePkCols.join(", ") & ")"
155162
sql &= ")"

tests/test2.nim

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ newModel Users:
2323
email: Varchar(100)
2424

2525
newModel Subscriptions:
26-
id: Serial
26+
id {.pk.}: Serial
2727
user_id: Users.id
2828
plan: Varchar(50)
2929

0 commit comments

Comments
 (0)