sqlite icon indicating copy to clipboard operation
sqlite copied to clipboard

autoIncrement ignored when combined with primaryKey

Open pboguslawski opened this issue 2 years ago • 3 comments

Description

According to https://www.sqlitetutorial.net/sqlite-autoincrement/ https://www.sqlite.org/autoinc.html AUTOINCREMENT should be used in sqlite if one want's ID values not to be reused (i.e. after row deletion).

With table definition

ID uint64   `gorm:"column:id;not null;primaryKey;autoIncrement"`

GORM creates column without autoincrement:

CREATE TABLE `[...]` (`id` integer NOT NULL,[...],PRIMARY KEY (`id`));

but should add autoincrement also.

According to https://github.com/go-gorm/sqlite/issues/126 one can create primary key + autoincrement with autoIncrement tag only but this looks like dirty hack and error

failed to create database schema: table "[...]" has more than one primary key

is thrown when trying to create table with

	IDH uint64 `gorm:"column:idh;not null;autoIncrement"` // Tried to create as PK+autoincrement.
	ID  uint64 `gorm:"column:id;not null"`                 // Tried to create as foreign key with ID name (makes sense in history table for us).

because GORM tries ID as PK by default (because of col name) and adds PK also to IDH (because of wrong handling of tags like above).

Expected behaviour

Column defined with gorm:"[...];primaryKey;autoIncrement" should be created as PK with autoincrement in sqlite db.

pboguslawski avatar Feb 24 '23 11:02 pboguslawski

I have the same issue, it causes weird bugs because IDs get reuse.

dvdlevanon avatar Mar 26 '23 15:03 dvdlevanon

@dvdlevanon @pboguslawski This has been fixed in 1.25.5 https://github.com/go-gorm/gorm/commit/2095d42b4c15de8d0cdaf64fd75e306bec40d9c4

championswimmer avatar Nov 04 '23 16:11 championswimmer