go-gorm / sqlite

GORM sqlite driver
MIT License
169 stars 174 forks source link

fix: AUTOINCREMENT flag cannot apply with PRIMARY KEY #167

Closed samuelncui closed 11 months ago

samuelncui commented 11 months ago

What did this pull request do?

Fix #4760. Currently, sqlite dialector can't apply AUTOINCREMENT to the field type. The reason this method cannot work is if a field is marked as AutoIncrement and PrimaryKey at the same time, when we apply AUTOINCREMENT to data type, it will create SQL like the following:

CREATE TABLE `example_table` (`id` integer PRIMARY KEY AUTOINCREMENT, ..., PRIMARY KEY (`id`))'

This can cause SQL logic error: table "example_table" has more than one primary key (1) error, because there is two PRIMARY KEY definition in this statement. The root cause is hasPrimaryKeyInDataType doesn't check the result of Dialector.DataTypeOf method.

By checking the result of Dialector.DataTypeOf method, a dialector can define its behavior for AUTOINCREMENT & PRIMARY KEY situation.

User Case Description

The following struct:

type ExampleTable struct {
    ID     int64  `gorm:"primaryKey;autoIncrement" json:"id,omitempty"`
    ...
}

Used to generate table DDL as:

CREATE TABLE `example_table` (`id` integer, ..., PRIMARY KEY (`id`))'

Which doesn't mark id field as AUTOINCREMENT. Currently, the id field roughly acts like AUTOINCREMENT, but it doesn't in many areas. This implementation may cause some issues like id reusing when deleting rows.

Now, it will generate table DDL as (if sqlite dialector is also changed):

CREATE TABLE `example_table` (`id` integer PRIMARY KEY AUTOINCREMENT, ...)'
xuxiaowei-com-cn commented 11 months ago

https://github.com/go-gorm/sqlite/issues/168