Create Table [PostgreSQL MySQL]

API

For the full list of supported methods, see CreateTableQueryCREATE TABLE - 图1open in new window.

  1. db.NewCreateTable().
  2. Model(&strct).
  3. Table("table1"). // quotes table names
  4. TableExpr("table1"). // arbitrary unsafe expression
  5. ModelTableExpr("table1"). // overrides model table name
  6. Temp().
  7. IfNotExists().
  8. Varchar(100). // turns VARCHAR into VARCHAR(100)
  9. WithForeignKeys().
  10. ForeignKey(`(fkey) REFERENCES table1 (pkey) ON DELETE CASCADE`).
  11. PartitionBy("HASH (id)").
  12. TableSpace("fasttablespace").
  13. Exec(ctx)

Example

To create a table:

  1. _, err := db.NewCreateTable().
  2. Model((*Book)(nil)).
  3. ForeignKey(`("author_id") REFERENCES "users" ("id") ON DELETE CASCADE`).
  4. Exec(ctx)
  5. if err != nil {
  6. panic(err)
  7. }

ResetModel

Bun provides ResetModel method to quickly drop and create tables:

  1. err := db.ResetModel(ctx, (*Model1)(nil), (*Model2)(nil))
  1. DROP TABLE IF EXISTS model1 CASCADE;
  2. CREATE TABLE model1 (...);
  3. DROP TABLE IF EXISTS model2 CASCADE;
  4. CREATE TABLE model2 (...);

Hooks

You can also modify query from the bun.BeforeCreateTableHook hook.

  1. var _ bun.BeforeCreateTableHook = (*Book)(nil)
  2. func (*Book) BeforeCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
  3. query.ForeignKey(`("author_id") REFERENCES "users" ("id") ON DELETE CASCADE`)
  4. return nil
  5. }
  6. if _, err := db.NewCreateTable().Model((*Book)(nil)).Exec(ctx); err != nil {
  7. panic(err)
  8. }

To create an index on the table, you can use bun.AfterCreateTableHook hook:

  1. var _ bun.AfterCreateTableHook = (*Book)(nil)
  2. func (*Book) AfterCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
  3. _, err := query.DB().NewCreateIndex().
  4. Model((*Book)(nil)).
  5. Index("category_id_idx").
  6. Column("category_id").
  7. Exec(ctx)
  8. return err
  9. }

See exampleCREATE TABLE - 图2open in new window for details.