Insert
Insert writes new entities and fills in generated keys. Every field is written as is, zeros included.
Insert one row
alice := &User{
Name: "Alice",
Email: "alice@example.com",
Age: 30,
}
err := db.Users.Insert(ctx, alice)
if err != nil {
return err
}
fmt.Println(alice.ID) // set by the database
// INSERT INTO "users" ("created_at", "updated_at", "name", "email", "age", "bio")
// VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"
CreatedAt and UpdatedAt are filled in when the model has them.
Insert several rows
Several entities go in as one multi-row statement in a transaction. If one fails, every row is rolled back and the keys that were set are cleared.
err := db.Users.Insert(ctx, alice, bob)
// INSERT INTO "users" (...) VALUES ($1, ...), ($7, ...) RETURNING "id"
// A slice of pointers spreads.
err = db.Users.Insert(ctx, users...)
For thousands of rows, use InsertMany, which splits the work into batches.
Insert a whole graph
Insert also saves the new entities a struct points at, parents first, and fills in the foreign keys.
alice := &User{
Name: "Alice",
Email: "alice@example.com",
Posts: []Post{{Title: "Hello"}, {Title: "Second"}},
}
err := db.Users.Insert(ctx, alice)
// INSERT INTO "users" (...) VALUES (...) RETURNING "id"
// INSERT INTO "posts" (...) VALUES (...), (...) RETURNING "id"
fmt.Println(alice.Posts[1].UserID == alice.ID) // true
From the child, a parent that already has its key is linked, not inserted again:
post := &Post{Title: "New", User: alice}
err := db.Posts.Insert(ctx, post)
// INSERT INTO "posts" (...) VALUES ($1, $2, $3, $4, $5) RETURNING "id" -- $3 = alice.ID
New rows that depend on each other in a loop are refused with ant.ErrCycle.
On a session, an entity inserted with its relations is tracked as if loaded with them. A later SaveChanges doesn't write the new join rows again, and a child you remove from its slice is deleted.
Insert without relations
InsertOnly writes the row and leaves its relation fields alone. Nothing is tracked for those relations.
err := db.Users.InsertOnly(ctx, alice)
// INSERT INTO "users" (...) VALUES (...) RETURNING "id"
Find or create
FirstOrCreate returns the first row that matches the conditions, or inserts yours. The bool reports which.
user, created, err := db.Users.FirstOrCreate(
ctx,
&User{Name: "Ada", Email: "ada@example.com"},
ant.Eq(&Users.Email, "ada@example.com"),
)
// SELECT ... FROM "users" WHERE "users"."email" = $1 LIMIT $2
// INSERT INTO "users" (...) VALUES (...) RETURNING "id"
If another writer inserts the row between the read and the insert, the unique constraint stops yours and you get the winner's row back. The conditions should match a unique column. Inside a transaction the re-read locks the row FOR UPDATE, so it sees the row even on MySQL's default REPEATABLE READ, and two callers that both lost the insert don't deadlock when they update it next.
FirstOrNew does the same without saving. Its bool reports whether a row was found.
user, found, err := db.Users.FirstOrNew(ctx, &User{Name: "Ada"}, ant.Eq(&Users.Name, "Ada"))
To update a row that exists instead of returning it, use an upsert.
Copy a row
ant.Clone copies an entity with its key and relations cleared, ready to insert as a new row.
twin := ant.Clone(alice)
twin.Email = "twin@example.com"
err := db.Users.Insert(ctx, twin)
Handle a constraint failure
The Is helpers read a constraint failure the same way on every database.
err := db.Users.Insert(ctx, &User{Email: alice.Email})
if ant.IsUniqueViolation(err) {
return errors.New("that email is taken")
}
See it tested: tests/features/writing/insert_test.go