Create & batch inserts
Create over structs and slices, CreateBatchSize chunking, primary-key and timestamp backfill, and the hooks that run on the way in.
Create inserts a struct or a slice of structs. It is the finisher for the
create callback chain; the statement it builds depends only on the parsed
schema and the dialect's feature flags.
func (db *DB) Create(value any) *DB {
tx := db.getInstance()
tx.Statement.Dest = value
tx.callbacks.create.Execute(tx)
return tx
}Single insert
u := crudUser{Name: "dave", Age: 22}
if err := db.Create(&u).Error; err != nil {
panic(err)
}
// u.ID, u.CreatedAt and u.UpdatedAt are now populatedAfter the INSERT, fusion-orm backfills:
- the primary key — from the driver's
LastInsertIdor the statement'sRETURNINGrow (below); - timestamps —
CreatedAtandUpdatedAtare set on the struct fromConfig.NowFuncbefore the row is written.
// Assign through typed pointers: reflect.ValueOf(time.Time) heap-boxes
// the value on every call, and this runs per row.Pass the value by pointer so the backfill can reach your struct.
What runs
The create chain is fixed:
// The create chain, in order: begin_tx, before_create,
// save_before_associations, create, save_after_associations,
// after_create, commit_or_rollback.So a single Create runs, in order: the implicit transaction boundary,
your BeforeCreate hook (when the model defines one), belongs-to
association saves, the INSERT itself, has-one/has-many/many-to-many
association saves, your AfterCreate hook, and commit-or-rollback. Hooks
are dispatched only for models that define the method — there is no
reflection cost otherwise (see
model hooks).
Associations cascade
If the model carries relations, the associated records are saved as part of the same create: belongs-to links are resolved before the root INSERT, and has-one/has-many/many-to-many children are written after it, inside the same transaction. See association callbacks.
Batch inserts
Create accepts a slice and inserts every element. All rows go into as few
statements as possible — one INSERT with multiple VALUES tuples — and
every element's primary key is backfilled:
users := make([]crudUser, 7)
for i := range users {
users[i].Name = fmt.Sprintf("u%d", i)
}
if err := db.CreateBatchSize(3).Create(&users).Error; err != nil {
panic(err)
}
// every users[i].ID is set; the count is now 7CreateBatchSize(n) caps the number of rows per statement; the slice is
chunked into ceil(n / size) INSERTs (7 rows at size 3 → statements of 3, 3
and 1 rows). Without it, the whole slice is one statement.
func (db *DB) CreateBatchSize(size int) *DBRETURNING vs LastInsertID
The primary key comes back differently per dialect capability. The create
callback branches on the dialect's feature.InsertReturning flag — never
on a dialect-name string:
returning := db.Dialector.Features().Has(feature.InsertReturning)- With
InsertReturning(both built-in dialects declare it — PostgreSQL and SQLite), the INSERT appendsRETURNING "id"and the callback scans the returned ids back onto the structs, in order, for any batch size. - Without it, the INSERT runs plain and the single-row driver
LastInsertIdresult is backfilled instead. This fallback only fires for a single-row insert of a single-key model: composite keys are client-assigned, and backfilling the engine's rowid over them would corrupt the model.
Rendered for db.Create(&User{Name: "Ada", Age: 30}) (PK excluded from the
column list because it is autoincrement; the statement is assembled by the
create callback at callbacks_default.go:288):
INSERT INTO "users" ("name", "age", "email", "created_at", "updated_at")
VALUES ('Ada', 30, '', '2026-11-28 10:00:00', '2026-11-28 10:00:00') RETURNING "id"PostgreSQL binds $n placeholders; SQLite binds ?. That is the only
difference in the statement — the RETURNING shape is identical.
Custom dialects
A third-party dialector that does not declare feature.InsertReturning
falls back to the LastInsertId path automatically — no code changes, but
batch inserts on such a dialect cannot backfill per-row ids, and composite
keys are never backfilled from the driver result.
Transactions: what Create wraps
By default a create runs inside an implicit transaction — except when the
write is provably one statement (no relations, no hooks, no multi-chunk
batch). Since v0.3.1, that single-statement path skips the synthetic
BEGIN/COMMIT entirely, which halves the common-case write path
(the operation is atomic by itself; the wrapping added round-trips without
extending atomicity).
// SkipDefaultTransaction disables the implicit transaction wrapping
// single create/update/delete operations.Config.SkipDefaultTransaction (or
Session(&fusion.Session{SkipDefaultTransaction: true})) turns the
remaining wrapping off globally or per session. Multi-statement creates —
models with associations, hooks that issue their own statements, chunked
batches — keep the transaction regardless.
Skip what you don't need
Session(&fusion.Session{NewDB: true})— start a clean chain.- For inserts that must not fire association callbacks (raw bulk loads
through the model's table), use
db.Table("users").Exec("INSERT ...")instead ofCreate.