bun icon indicating copy to clipboard operation
bun copied to clipboard

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

Open tablecell opened this issue 1 year ago • 1 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 "

tablecell avatar Nov 11 '23 06:11 tablecell

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:

  • https://www.sqlite.org/lang_createtable.html#rowid (Section 5. ROWID)
  • https://stackoverflow.com/a/7906029/14726116

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.

bevzzz avatar Nov 28 '23 17:11 bevzzz