-
Notifications
You must be signed in to change notification settings - Fork 0
Generated Client
GCORM generates Go code from .gcorm files. The generated code is intended to
be imported by your application and used with database/sql.
The default generator output is usually:
gen/client
gen/query
gen/model
Package roles:
-
client: top-level database client, model clients, raw SQL helpers, and transaction entry points. -
query: type-safe predicates, setters, ordering helpers, and input structs. -
model: generated Go structs and enum types.
PostgreSQL:
import (
"database/sql"
_ "github.com/jackc/pgx/v5/stdlib"
"example.com/app/gen/client"
)
db, err := sql.Open("pgx", dsn)
if err != nil {
return err
}
c := client.New(db, client.WithDialect("postgresql"))
defer c.Close()MySQL:
import _ "github.com/go-sql-driver/mysql"
db, err := sql.Open("mysql", dsn)
c := client.New(db, client.WithDialect("mysql"))SQLite:
import _ "modernc.org/sqlite"
db, err := sql.Open("sqlite", dsn)
c := client.New(db, client.WithDialect("sqlite"))PostgreSQL is the default dialect, but passing client.WithDialect(...) makes
the intent clear and is required for MySQL and SQLite.
A schema model like:
model User {
id String @id @default(uuid())
email String @unique
name String?
}
generates a Go model struct in the model package. Nullable fields are
represented with pointer types.
var u model.User
_ = u.Email
if u.Name != nil {
_ = *u.Name
}The query package exposes model-specific helpers:
query.User.Email.Equals("ada@example.com")
query.User.Email.Contains("@example.com")
query.User.CreatedAt.Desc()
query.User.Name.Set("Ada")These helpers build structured predicates and updates. Normal values are passed as SQL parameters.
The generated client wraps a *sql.DB. Closing the GCORM client should not be a
substitute for managing the database handle in your application. Prefer to close
both explicitly when your application shuts down:
defer c.Close()
defer db.Close()All execution methods accept context.Context:
users, err := c.User.Query().Take(20).Do(ctx)Use timeouts and request-scoped contexts in services:
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()Generated clients include transaction support through the runtime transaction APIs. Use transactions when multiple writes must commit or roll back together.
err := c.Tx(ctx, func(tx *client.Client) error {
_, err := tx.User.Create().
Set(query.User.Email.Set("ada@example.com")).
Do(ctx)
if err != nil {
return err
}
_, err = tx.AuditLog.Create().
Set(query.AuditLog.Message.Set("created user")).
Do(ctx)
return err
})Use the exact transaction helper shape generated by your installed version if the API changes.
Regenerate after changing schema files:
gco validate
gco generateCommit generated code if your project expects consumers to build without running the generator. Otherwise, add the output directory to your normal build workflow.