uptrace / bun

SQL-first Golang ORM

Home Page:https://bun.uptrace.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

db.NewCreateTable with `bun:",pk,autoincrement"` did not create table sqlite_sequence

tablecell opened this issue · comments

package main

import(
"fmt"
"context"
    "database/sql"
     "github.com/uptrace/bun"
  "github.com/uptrace/bun/driver/sqliteshim"
"github.com/uptrace/bun/dialect/sqlitedialect"
)

type User struct {
 bun.BaseModel `bun:"table:users,alias:u"`
 ID	 int64  `bun:",pk,autoincrement"`
 Name string


}
func main(){
ctx:=context.Background()
sqldb, err := sql.Open(sqliteshim.ShimName, "test.db")  // "file::memory:?cache=shared"
if err != nil {
	panic(err)
}
db := bun.NewDB(sqldb, sqlitedialect.New())
 fmt.Println(db)
// user := &User{Name: "admin"}

ret, err := db.NewCreateTable().Model((*User)(nil)).Exec(ctx)
fmt.Println(ret,err )
}

generated create table sql is:

CREATE TABLE "users" ("id" INTEGER NOT NULL, "name" VARCHAR, PRIMARY KEY ("id"));

there is no " autoincrement "

As far as I can tell, the reason the sequence was not created is that in SQLite you get unique autoincremented ID column (called ROWID) for any table that has INTEGER PRIMARY KEY column in it.

References:

That being said, there is a dedicated AUTOINCREMENT keyword in SQLite, which ensures that the next ROWID is is at least one larger than the largest ROWID that has ever before existed in that same table.

I imagine that the current lack of support for it in bun was due to the default mechanism being able to fulfil most of the requirements you'd have for an autoincremented column. You're right in that it'd make sense if bun:",autoincrement" created the sequence instead of silently falling back to ROWID.

Looks like a small change, I'll try to come up with a PR for this.