Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
tablecell opened this issue Nov 11, 2023 · 1 comment

Comments

@tablecell
Copy link

tablecell commented Nov 11, 2023

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 "

@bevzzz
Copy link
Contributor

bevzzz commented Nov 28, 2023

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.

bevzzz added a commit to bevzzz/bun that referenced this issue Jan 7, 2024
vmihailenco pushed a commit that referenced this issue Jan 10, 2024
* refactor: delegate autoincrement to dialects

* feat: support AUTOINCREMENT PKs in SQLite

* chore: use succinct syntax

* refactor: push the check for PK to the caller

#929
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants