Create Table [PostgreSQL MySQL]

API

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

1. db.NewCreateTable().

3. Model(&strct).

5. Table("table1"). // quotes table names
6. TableExpr("table1"). // arbitrary unsafe expression
7. ModelTableExpr("table1"). // overrides model table name

9. Temp().
10. IfNotExists().
11. Varchar(100). // turns VARCHAR into VARCHAR(100)

13. WithForeignKeys().
14. ForeignKey(`(fkey) REFERENCES table1 (pkey) ON DELETE CASCADE`).
15. PartitionBy("HASH (id)").
16. TableSpace("fasttablespace").

18. 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 (...);

4. DROP TABLE IF EXISTS model2 CASCADE;
5. CREATE TABLE model2 (...);

Hooks

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

1. var _ bun.BeforeCreateTableHook = (*Book)(nil)

3. func (*Book) BeforeCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
4. query.ForeignKey(`("author_id") REFERENCES "users" ("id") ON DELETE CASCADE`)
5. return nil
6. }

8. if _, err := db.NewCreateTable().Model((*Book)(nil)).Exec(ctx); err != nil {
9. panic(err)
10. }

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

1. var _ bun.AfterCreateTableHook = (*Book)(nil)

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

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