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

How to use dbfixture.WithTruncateTables with table that have foreign key? #447

Closed
hhuseyinpay opened this issue Feb 22, 2022 · 0 comments
Closed

Comments

@hhuseyinpay
Copy link

I have the following models:

type Kisi struct {
        ID        int64      `json:"id" bun:"id,pk,autoincrement"`
        ...
}
type Cevap struct {
        ID        int64      `json:"id" bun:"id,pk,autoincrement"`
	Kisi      Kisi  `json:"kisi" bun:"rel:belongs-to"`
	KisiID    int64 `json:"kisi_id"`
        SoruID     int64 `json:"soru_id"`
        ....
}

func (*Cevap) BeforeCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
	query.ForeignKey(`("kisi_id") REFERENCES "kisi" ("id") ON DELETE CASCADE`)
	return nil
}

func (*Cevap) AfterCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
	_, err := query.DB().NewCreateIndex().
		Model((*Cevap)(nil)).
		Index("soru_kisi_idx").
		Column("soru_id", "kisi_id").Exec(ctx)
	return err
}

I'm trying to load the fixture with the following code:

db.RegisterModel((*model.Kisi)(nil))
db.RegisterModel((*model.Cevap)(nil))
fixture := dbfixture.New(db, dbfixture.WithTruncateTables())
err := fixture.Load(context.Background(), os.DirFS("base/model/fixture"), "fixture.yml")

The following error occurs:

[bun]  10:36:37.912   TRUNCATE TABLE       61.063ms  TRUNCATE TABLE "kisi" RESTART IDENTITY       pgdriver.Error: ERROR: cannot truncate a table referenced in a foreign key constraint (SQLSTATE=0A000) 
panic: ERROR: cannot truncate a table referenced in a foreign key constraint (SQLSTATE=0A000)

I tried WithRecreateTables, same error:

[bun]  10:49:11.211   DROP TABLE           59.978ms  DROP TABLE IF EXISTS "kisi"          pgdriver.Error: ERROR: cannot drop table kisi because other objects depend on it (SQLSTATE=2BP01) 
panic: ERROR: cannot drop table kisi because other objects depend on it (SQLSTATE=2BP01)

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

1 participant