@@ -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 &= " )"
0 commit comments