Defining models

Mapping tables to structs

For each table you need to define a corresponding Go struct (model). Bun maps the exported struct fields to the table columns and ignores the unexported fields.

  1. type User struct {
  2. bun.BaseModel `bun:"table:users,alias:u"`
  3. ID int64 `bun:"id,pk,autoincrement"`
  4. Name string `bun:"name,notnull"`
  5. email string // unexported fields are ignored
  6. }

Struct tags

Bun uses sensible defaults to generate names and deduct types, but you can use the following struct tags to override the defaults.

TagComment
bun.BaseModel bun:"table:table_name"Override default table name.
bun.BaseModel bun:"alias:table_alias"Override default table alias.
bun.BaseModel bun:"select:view_name"Override table name for SELECT queries.
bun:”-“Ignore the field.
bun:”column_name”Override default column name.
bun:”alt:alt_name”Alternative column name. Useful during migrations.
bun:”,pk”Mark column as a primary key and apply notnull option. Multiple/composite primary keys are supported.
bun:”,autoincrement”Mark column as a serial in PostgreSQL, autoincrement in MySQL, and identity in MSSQL. Also applies nullzero option.
bun:”type:uuid”Override default SQL type.
bun:”default:gen_random_uuid()”Tell CreateTable to set DEFAULT expression.
bun:”,notnull”Tell CreateTable to add NOT NULL constraint.
bun:”,unique”Tell CreateTable to add an unique constraint.
bun:”,unique:group_name”Unique constraint for a group of columns.
bun:”,nullzero”Marshal Go zero values as SQL NULL or DEFAULT (when supported).
bun:”,scanonly”Only use this field to scan query results and ignore in SELECT/INSERT/UPDATE/DELETE.
bun:”,array”Use PostgreSQL array.
bun:”,json_use_number”Use json.Decoder.UseNumber to decode JSON.
bun:”,msgpack”Encode/decode data using MessagePack.
DeletedAt time.Time bun:",soft_delete"Enable soft deletes on the model.

Table names

Bun generates table names and aliases from struct names by underscoring them. It also pluralizes table names, for example, struct ArticleCategory gets table name article_categories and alias article_category.

To override the generated name and the alias:

  1. type User struct {
  2. bun.BaseModel `bun:"table:myusers,alias:u"`
  3. }

To specify a different table name for SELECT queries:

  1. type User struct {
  2. bun.BaseModel `bun:"select:users_view,alias:u"`
  3. }

Column names

Bun generates column names from struct field names by underscoring them. For example, struct field UserID gets column name user_id.

To override the generated column name:

  1. type User struct {
  2. Name string `bun:"myname"`
  3. }

SQL naming convention

Use snake_caseDefining models - 图1open in new window identifiers for table and column names. If you get spurious SQL parser errors, try to quote the identifier with double quotes (backticks for MySQL) to check if the problem goes away.

WARNING

Don’t use SQL keywordsDefining models - 图2open in new window (for example order, user) as identifiers.

WARNING

Don’t use case-sensitive names because such names are folded to lower case, for example, UserOrders becomes userorders.

Column types

Bun generates column types from the struct field types. For example, Go type string is translated to SQL type varchar.

To override the generated column type:

  1. type User struct {
  2. ID int64 `bun:"type:integer"`
  3. }

NULLs

To represent SQL NULL, you can use pointers or sql.Null* types:

  1. type Item struct {
  2. Active *bool
  3. // or
  4. Active sql.NullBool
  5. }

For example:

  • (*bool)(nil) and sql.NullBool{} represent NULL.
  • (*bool)(false) and sql.NullBool{Valid: true} represent FALSE.
  • (*bool)(true) and sql.NullBool{Valid: true, Value: true} represent TRUE.

Go zero values and NULL

To marshal a zero Go value as NULL, use nullzero tag:

  1. type User struct {
  2. Name string `bun:",nullzero"`
  3. }

DEFAULT

To specify a default SQL expression, use the combination of nullzero, notnull, and default tags:

  1. type User struct {
  2. Name string `bun:",nullzero,notnull,default:'unknown'"`
  3. }
  4. err := db.NewCreateTable().Model((*User)(nil)).Exec(ctx)
  1. CREATE TABLE users (
  2. name text NOT NULL DEFAULT 'unknown'
  3. );

Automatic timestamps

Use the following code to automatically set creation and update time on INSERT:

  1. type User struct {
  2. CreatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
  3. UpdatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
  4. }

If you don’t want to set update time, use bun.NullTime:

  1. type User struct {
  2. CreatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
  3. UpdatedAt bun.NullTime
  4. }

You can also use hooks to set struct fields:

  1. var _ bun.BeforeAppendModelHook = (*User)(nil)
  2. func (u *User) BeforeAppendModel(ctx context.Context, query bun.Query) error {
  3. switch query.(type) {
  4. case *bun.InsertQuery:
  5. u.CreatedAt = time.Now()
  6. case *bun.UpdateQuery:
  7. u.UpdatedAt = time.Now()
  8. }
  9. return nil
  10. }

Extending models

You can add/remove fields to/from an existing model by using extend tag option. The new model will inherit the table name and the alias from the original model.

  1. type UserWithCount struct {
  2. User `bun:",extend"`
  3. Name string `bun:"-"` // remove this field
  4. AvatarCount int // add a new field
  5. }

Embedding structs

Bun allows to embed a model in another model using a prefix, for example:

  1. type Role struct {
  2. Name string
  3. Users Permissions `bun:"embed:users_"`
  4. Profiles Permissions `bun:"embed:profiles_"`
  5. Roles Permissions `bun:"embed:roles_"`
  6. }
  7. type Permissions struct {
  8. View bool
  9. Create bool
  10. Update bool
  11. Delete bool
  12. }

The code above generates the following table:

  1. CREATE TABLE roles (
  2. name TEXT,
  3. users_view BOOLEAN,
  4. users_create BOOLEAN,
  5. users_update BOOLEAN,
  6. users_delete BOOLEAN,
  7. profiles_view BOOLEAN,
  8. profiles_create BOOLEAN,
  9. profiles_update BOOLEAN,
  10. profiles_delete BOOLEAN,
  11. roles_view BOOLEAN,
  12. roles_create BOOLEAN,
  13. roles_update BOOLEAN,
  14. roles_delete BOOLEAN
  15. );

See also