bun icon indicating copy to clipboard operation
bun copied to clipboard

Why not use struct tags for index creation in Bun?

Open Flipped199 opened this issue 9 months ago • 5 comments

I'm currently working with Bun ORM in my Go project and I'm curious about the design decision behind index creation. While Bun uses struct tags for many database-related features (primary keys, default values, etc.), indexes need to be created using the CreateIndex API.

// Model definition with tags for other features
type WalletLog struct {
	Id        int `bun:",pk,autoincrement"`
	WalletId  int // No way to define index via tag
	Balance   int64
	CreatedAt time.Time    `bun:",notnull,default:current_timestamp"`
	UpdatedAt bun.NullTime `bun:",nullzero"`
	DeletedAt bun.NullTime `bun:",soft_delete,nullzero"`
}

// Separate index creation
_, err := db.NewCreateIndex().
    Model((*WalletLog)(nil)).
    Index("idx_wallet_log_wallet_id").
    Column("wallet_id").
    IfNotExists().
    Exec(ctx)

I'm curious about the reasoning behind this design choice. Many other ORMs support index creation via struct tags, which keeps the schema definition centralized in the model structs.

Was there a specific technical limitation or design philosophy that led to separating index creation from struct tags? Are there advantages to this approach that I might be missing?

Thank you for your insights.

Flipped199 avatar Mar 29 '25 17:03 Flipped199

I don’t know the exact reason, but I guess it’s simply because we haven’t supported this feature.

This doesn’t seem essential, and Bun isn’t particularly advantageous when it comes to migration-related aspects.

j2gg0s avatar Apr 02 '25 09:04 j2gg0s

I also need such a feature: creating index through struct tag

ilxqx avatar Apr 11 '25 03:04 ilxqx

The only thing that makes me feel a bit inconvenient when using bun is this. Since it supports adding unique, why not consider index?

Flipped199 avatar Apr 28 '25 09:04 Flipped199

We will consider it when we have the time

j2gg0s avatar Apr 29 '25 06:04 j2gg0s

I don't think it's very versatile, indexes could have complex conditions, it's best to declare them as code rather than tags.

john8329 avatar Oct 28 '25 15:10 john8329