### Starter Method Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Provides a starting point for building queries against a table. Accepts query modifiers for customization. ```go func Users(mods ...qm.QueryMod) *queries.Query ``` -------------------------------- ### Install null package Source: https://github.com/aarondl/sqlboiler/blob/master/CONTRIBUTING.md Install the 'null' package using go get. This may be required before running tests. ```bash go get -u github.com/aarondl/null ``` -------------------------------- ### Install SQLBoiler and PostgreSQL Driver Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/00-START-HERE.md Installs the SQLBoiler CLI tool and the PostgreSQL driver using go install. Also adds SQLBoiler and the null package as project dependencies. ```bash go install github.com/aarondl/sqlboiler/v4@latest go install github.com/aarondl/sqlboiler/v4/drivers/sqlboiler-psql@latest # Add as project dependency go get github.com/aarondl/sqlboiler/v4 go get github.com/aarondl/null/v8 ``` -------------------------------- ### Full TOML Configuration Example Source: https://github.com/aarondl/sqlboiler/blob/master/README.md A comprehensive TOML configuration file example demonstrating settings for output, wiping, disabling tests, enabling enum types, and detailed driver-specific configurations for PostgreSQL, MySQL, and MSSQL. ```toml output = "my_models" wipe = true no-tests = true add-enum-types = true [psql] dbname = "dbname" host = "localhost" port = 5432 user = "dbusername" pass = "dbpassword" schema = "myschema" blacklist = ["migrations", "other"] [mysql] dbname = "dbname" host = "localhost" port = 3306 user = "dbusername" pass = "dbpassword" sslmode = "false" tinyint_as_int = true [mssql] dbname = "dbname" host = "localhost" port = 1433 user = "dbusername" pass = "dbpassword" sslmode = "disable" schema = "notdbo" ``` -------------------------------- ### Complete SQLBoiler Configuration Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md A comprehensive TOML configuration file example covering generic options, feature flags, code generation settings, struct tags, and PostgreSQL specific settings. ```toml # Generic options output = "models" pkg_name = "models" debug = false wipe = true no_tests = false # Feature flags add_global = true add_panic = false add_enum_types = true add_soft_deletes = false no_auto_timestamps = false no_hooks = false no_context = false # Code generation struct_tag_casing = "snake" enum_null_prefix = "Null" # Struct tags and imports tag = ["xml", "db"] tag_ignore = ["secret_col"] # PostgreSQL configuration [psql] dbname = "production_db" host = "db.example.com" port = 5432 user = "app_user" pass = "secure_password" schema = "public" sslmode = "require" blacklist = ["migrations", "audit_log"] ``` -------------------------------- ### Database Connection Example Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Opens a connection to a PostgreSQL database using the standard `database/sql` package. ```go // Open handle to database like normal db, err := sql.Open("postgres", "dbname=fun user=abc") if err != nil { return err } ``` -------------------------------- ### SQLite3 Configuration Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for SQLite3. Specifies the database file path. ```toml [sqlite3] dbname = "app.db" ``` -------------------------------- ### Install SQLBoiler and PostgreSQL Driver Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md Installs the SQLBoiler CLI and the PostgreSQL driver, then adds SQLBoiler and the null package as project dependencies. ```bash # Install sqlboiler and PostgreSQL driver go install github.com/aarondl/sqlboiler/v4@latest go install github.com/aarondl/sqlboiler/v4/drivers/sqlboiler-psql@latest # Add as project dependency go get github.com/aarondl/sqlboiler/v4 go get github.com/aarondl/null/v8 ``` -------------------------------- ### Install SQLBoiler CLI and Driver Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Provides commands for installing the SQLBoiler code generator and the PostgreSQL driver using Go modules. Use `go install` with the correct version suffix. ```shell # Go 1.16 and above: go install github.com/aarondl/sqlboiler/v4@latest go install github.com/aarondl/sqlboiler/v4/drivers/sqlboiler-psql@latest # Go 1.15 and below: ``` -------------------------------- ### BuildQuery Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/queries-package.md Converts a Query object into an SQL string and arguments. ```go sql, args := queries.BuildQuery(q) fmt.Println(sql) fmt.Println(args) ``` -------------------------------- ### Microsoft SQL Server Configuration Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for Microsoft SQL Server. Includes database name, host, user, password, and schema. ```toml [mssql] dbname = "mydb" host = "localhost" user = "sa" pass = "MyP@ssw0rd" schema = "dbo" ``` -------------------------------- ### MySQL Configuration Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for MySQL. Specifies database name, host, user, password, and SSL mode. ```toml [mysql] dbname = "mydb" host = "localhost" user = "root" pass = "password" sslmode = "false" ``` -------------------------------- ### SQLBoiler Configuration Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/00-START-HERE.md A sample sqlboiler.toml configuration file specifying the output directory, package name, and PostgreSQL connection details. ```toml output = "models" pkg_name = "models" add_global = true [psql] dbname = "myapp" host = "localhost" user = "postgres" ``` -------------------------------- ### PostgreSQL Driver Configuration Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md This TOML snippet demonstrates how to configure the PostgreSQL driver, including database credentials, schema, and table whitelisting. ```toml [psql] dbname = "mydb" host = "localhost" user = "postgres" pass = "secret" schema = "public" whitelist = ["users", "posts"] ``` -------------------------------- ### User Model Starter Method Examples Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Demonstrates how to initiate query chains using the Users starter method with different query modifiers like Where, Limit, and OrderBy. ```go models.Users(qm.Where("age > ?", 18)).All(ctx, db) models.Users(qm.Limit(10), qm.OrderBy("name")).All(ctx, db) ``` -------------------------------- ### Template Directory Structure Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generation-system.md Illustrates the organization of template files by extension and subdirectory for SQLBoiler code generation. ```text templates/ ├── 00_struct.go.tpl # Model struct definitions ├── 01_find.go.tpl # Find by primary key methods ├── 02_query.go.tpl # Query builder methods ├── singleton/ │ └── boil_queries.go.tpl # Generated once, not per table └── 02_query_test.go.tpl # Tests (in templates_test/) ``` -------------------------------- ### All Finisher Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Demonstrates fetching all users where the 'active' field is true, handling potential errors, and iterating through the results to print user names. ```go users, err := models.Users(qm.Where("active = ?", true)).All(ctx, db) if err != nil { return err } for _, user := range users { fmt.Println(user.Name) } ``` -------------------------------- ### Finder Method Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Retrieves a single record by its primary key. Requires context, an executor, and the ID. ```go func FindUser(ctx context.Context, exec boil.ContextExecutor, id int) (*User, error) ``` -------------------------------- ### Pagination Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Implements pagination by calculating the offset based on page number and page size, then applying `Limit` and `Offset` query modifiers. ```go page := 2 pageSize := 20 offset := (page - 1) * pageSize users, _ := models.Users( OrderBy("created_at DESC"), Limit(pageSize), Offset(offset), ).All(ctx, db) ``` -------------------------------- ### Install sqlboiler v4 and PostgreSQL Driver Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Installs sqlboiler v4 and the PostgreSQL driver globally. Avoid running this within your Go module to prevent polluting your go.mod file. ```shell GO111MODULE=on go get -u -t github.com/aarondl/sqlboiler/v4 GO111MODULE=on go get github.com/aarondl/sqlboiler/v4/drivers/sqlboiler-psql ``` -------------------------------- ### Environment Variables for Configuration Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example of setting SQLBoiler configuration options using environment variables. Shows generic and database-specific variables. ```bash export OUTPUT="models" export PKG_NAME="models" export ADD_GLOBAL="true" export DEBUG="false" export PSQL_DBNAME="mydb" export PSQL_HOST="localhost" export PSQL_PORT="5432" export PSQL_USER="postgres" export PSQL_PASS="password" ``` -------------------------------- ### Relationship Methods Examples Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Methods to access related data. Use `To-many` for one-to-many and `To-one` for many-to-one relationships. ```go func (u *User) Posts() *queries.Query // To-many func (p *Post) User() *queries.Query // To-one ``` -------------------------------- ### Exists Finisher Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Verifies if a user with a specific email address exists in the database. ```go exists, err := models.Users(qm.Where("email = ?", "test@example.com")).Exists(ctx, db) ``` -------------------------------- ### Global Transaction Setup Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md This snippet shows how to set a global database connection for SQLBoiler and initiate a transaction. It demonstrates using the 'G' variants for global operations within a transaction context. ```go boil.SetDB(db) // Set global DB ctx := context.Background() tx, err := boil.BeginTx(ctx, nil) if err != nil { log.Fatal(err) } deferr tx.Rollback() // Use G variants which use the global executor users, err := models.UsersG(ctx).All(ctx) // Wait, needs executor still // Actually use the transaction directly user := &models.User{Name: "Alice"} err = user.Insert(ctx, tx, boil.Infer()) ``` -------------------------------- ### Type Mapping Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Illustrates the mapping between SQL database types and Go types, including nullable variants provided by the `github.com/aarondl/null/v8` package. ```go | INT | int | null.Int | | VARCHAR(255) | string | null.String | | TIMESTAMP | time.Time | null.Time | | BOOLEAN | bool | null.Bool | | DECIMAL | decimal.Decimal | null.Decimal | | JSON | types.JSON | types.NullJSON | ``` -------------------------------- ### SQLBoiler Relationship Examples Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/00-START-HERE.md Demonstrates how to fetch related data using one-to-many, many-to-one, and eager loading patterns in SQLBoiler. Ensure you have the necessary models and database connection set up. ```go // One-to-many user, _ := models.FindUser(ctx, db, 1) posts, _ := user.Posts().All(ctx, db) ``` ```go // Many-to-one post, _ := models.FindPost(ctx, db, 1) author, _ := post.User().One(ctx, db) ``` ```go // Eager loading (N+1 prevention) posts, _ := models.Posts(qm.Load("User", qm.Load("Comments"))).All(ctx, db) ``` -------------------------------- ### SQLBoiler TOML Configuration Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md This snippet shows a basic TOML configuration file structure for SQLBoiler, including generic options and PostgreSQL-specific settings. ```toml # Generic configuration output = "models" pkg_name = "models" debug = false # PostgreSQL driver configuration [psql] dbname = "mydb" host = "localhost" port = 5432 user = "postgres" pass = "password" schema = "public" ``` -------------------------------- ### One Finisher Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Fetches a single user record based on a specific ID. ```go user, err := models.Users(qm.Where("id = ?", 1)).One(ctx, db) ``` -------------------------------- ### JOIN Queries Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md This snippet illustrates how to perform JOIN operations between tables. It shows an example of an INNER JOIN to retrieve posts along with their associated active users. ```go posts, err := models.Posts( InnerJoin("users u ON u.id = posts.user_id"), Where("u.status = ?", "active"), ).All(ctx, db) ``` -------------------------------- ### Bind Finisher Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Selects only the 'id' and 'name' columns from the users table and binds the first result into a UserSummary struct. ```go type UserSummary struct { ID int `boil:"id"` Name string `boil:"name"` } var summary UserSummary err := models.Users(qm.Select("id", "name")).One(ctx, db).Bind(ctx, db, &summary) ``` -------------------------------- ### Registering Before and After Insert Hooks Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md This example shows how to register custom hooks that execute automatically before and after a user record is inserted into the database. It allows for custom logic like setting a creator or logging. ```go // Hook runs before insert models.AddUserHook(boil.BeforeInsertHook, func(ctx context.Context, exec boil.ContextExecutor, u *models.User) error { u.CreatedBy = getCurrentUserID() return nil }) // Hook runs after insert models.AddUserHook(boil.AfterInsertHook, func(ctx context.Context, exec boil.ContextExecutor, u *models.User) error { fmt.Printf("User %d inserted\n", u.ID) return nil }) // Now insert normally, hooks run automatically user := &models.User{Name: "Alice"} err := user.Insert(ctx, db, boil.Infer()) ``` -------------------------------- ### CRUD Methods Examples Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Standard methods for inserting, updating, deleting, reloading, and upserting records. They operate on a model instance and require context and an executor. ```go func (u *User) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error func (u *User) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) func (u *User) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) func (u *User) Reload(ctx context.Context, exec boil.ContextExecutor) error func (u *User) Upsert(ctx context.Context, exec boil.ContextExecutor, ...) error ``` -------------------------------- ### Batch Delete Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Performs a batch delete operation based on a `Where` clause. Returns the number of rows affected. ```go rowsAff, _ := models.Users( Where("created_at < ?", cutoffDate), ).DeleteAll(ctx, db) ``` -------------------------------- ### Using Generated Models in Go Application Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/00-START-HERE.md Example of how to import and use generated models for querying and inserting data in a Go application. ```go import "myapp/models" users, err := models.Users().All(ctx, db) user, err := models.FindUser(ctx, db, 1) er := user.Insert(ctx, db, boil.Infer()) ``` -------------------------------- ### Conditional Query Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Builds query modifiers dynamically based on conditions. This allows for flexible query construction. ```go mods := []qm.QueryMod{OrderBy("name")} if status != "" { mods = append(mods, Where("status = ?", status)) } users, _ := models.Users(mods...).All(ctx, db) ``` -------------------------------- ### Start Database Transaction Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Initiate a database transaction using either the standard SQL package method or SQLBoiler's global handle method. ```go db.Begin() // Normal sql package way of creating a transaction boil.BeginTx(ctx, nil) // Uses the global database handle set by boil.SetDB() (doesn't require flag) ``` -------------------------------- ### SQLBoiler Configuration TOML Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Example of a TOML configuration file for SQLBoiler, specifying output directory, package name, and enabling global variants. ```toml # Generic output = "models" pkg_name = "models" add_global = true ``` -------------------------------- ### Executing Raw SQL with Bind Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Example of executing a raw SQL query and binding the results to a Go struct using SQLBoiler's `queries.Raw()` and `Bind()` methods. ```go err := queries.Raw("select * from pilots where id=$1", 5).Bind(ctx, db, &obj) ``` -------------------------------- ### Transaction Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Demonstrates how to group multiple database operations within a single transaction. Ensures atomicity, rolling back on error or committing on success. ```go tx, err := db.BeginTx(ctx, nil) defer tx.Rollback() // Use tx as executor for multiple operations models.Users().All(ctx, tx) user.Insert(ctx, tx, boil.Infer()) tx.Commit() ``` -------------------------------- ### Setting and Using Global Database Connection Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/00-START-HERE.md Example of setting a global database connection using boil.SetDB and then using the G-variants of generated methods to avoid passing the database object explicitly. ```go boil.SetDB(db) user, _ := models.FindUserG(ctx, 1) ``` -------------------------------- ### Get Global Database Handle Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Returns the global database handle previously set with `SetDB`. Returns nil if not set. ```go func GetDB() Executor ``` -------------------------------- ### Custom Imports Configuration Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for overriding or adding import statements for generated code, both globally and based on type. ```toml [imports.all] standard = ['"context"', '"fmt"'] third_party = ['"github.com/my/package"'] [imports.based_on_type.null.Time] third_party = ['"github.com/aarondl/null/v8"'] ``` -------------------------------- ### Bind Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/queries-package.md Binds SQL rows to a struct or slice of structs. Works with generated model structs or custom structs with `boil` tags. ```go rows, err := queries.Raw("SELECT id, name FROM users").QueryContext(ctx, db) var users []models.User err = queries.Bind(rows, &users) ``` -------------------------------- ### Order and Limit Query Results Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md Retrieves a limited set of users, ordered by creation date in descending order. Includes an example for pagination using offset. ```go // Order by and limit users, err := models.Users( OrderBy("created_at DESC"), Limit(10), ).All(ctx, db) // With offset for pagination users, err := models.Users( OrderBy("created_at DESC"), Limit(20), Offset(40), // Page 3 (0-20, 20-40, 40-60) ).All(ctx, db) ``` -------------------------------- ### SQLBoiler Command-Line Flags Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example of using SQLBoiler command-line flags to configure code generation, including output path, package name, and feature flags. ```bash sqlboiler \ --output models \ --pkg-name models \ --add-global-variants \ --add-panic-variants \ --add-enum-types \ --no-auto-timestamps \ --struct-tag-casing camel \ --tag xml \ --tag db \ psql ``` -------------------------------- ### Configure PostgreSQL Database Name Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Example of configuring the database name for the PostgreSQL driver in a TOML configuration file. This configuration must be prefixed by the driver name. ```toml [psql] dbname = "your_database_name" ``` -------------------------------- ### Custom SELECT Clause Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md This example demonstrates how to specify a custom SELECT clause in your query to retrieve specific columns and potentially aggregate data, like counting records. ```go users, err := models.Users( Select("id", "name", "COUNT(*) as count"), ).All(ctx, db) ``` -------------------------------- ### Chained Query Modifiers Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/query-mods.md Demonstrates chaining multiple query modifiers together to construct a complex SQL query, including select, where, order by, limit, and eager loading. ```go users, err := models.Users( qm.Select("id", "name", "email"), qm.Where("age > ?", 18), qm.Where("status = ?", "active"), qm.OrderBy("created_at DESC"), qm.Limit(10), qm.Load("Posts"), ).All(ctx, db) ``` -------------------------------- ### Setting a 'To One' Relationship in SQLBoiler Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Shows how to set or update a 'to one' relationship using the SetX helper method. Includes examples for setting to an existing record and inserting a new record. ```go jet, _ := models.FindJet(ctx, db, 1) pilot, _ := models.FindPilot(ctx, db, 1) // Set the pilot to an existing jet err := jet.SetPilot(ctx, db, false, &pilot) pilot = models.Pilot{ Name: "Erlich", } // Insert the pilot into the database and assign it to a jet err := jet.SetPilot(ctx, db, true, &pilot) ``` -------------------------------- ### Beginner Interface Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Begins a transaction without options. ```APIDOC ## Beginner Interface ### Description Begins a transaction without options. ### Methods - `Begin() (*sql.Tx, error)` ``` -------------------------------- ### Model Struct Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Represents a database table with columns and relationships. Use `boil` tags for mapping and `json` tags for JSON serialization. The `R` field holds relationship data. ```go type User struct { ID int `boil:"id" json:"id"` Name string `boil:"name" json:"name"` // ... columns R *userR `boil:"-"` // Relationships } ``` -------------------------------- ### Begin Context-Aware Transaction Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Begins a context-aware transaction with options using the global database handle. Panics if the database doesn't support context transactions. ```go func BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) ``` ```go boil.SetDB(db) tx, err := boil.BeginTx(ctx, &sql.TxOptions{ Isolation: sql.LevelSerializable, }) if err != nil { return err } defer tx.Rollback() ``` -------------------------------- ### AppendWith Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/queries-package.md Appends a Common Table Expression (WITH clause) to a query. ```go queries.AppendWith(q, "active_users AS (SELECT * FROM users WHERE active = ?)", true) ``` -------------------------------- ### Begin Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Begins a transaction using the global database handle set via `SetDB`. Panics if the database doesn't support transactions. ```APIDOC ## Begin ### Description Begins a transaction using the global database handle set via `SetDB`. Panics if the database doesn't support transactions. ### Signature `func Begin() (Transactor, error)` ### Example ```go boil.SetDB(db) tx, err := boil.Begin() if err != nil { return err } defer tx.Rollback() users, err := models.Users().All(context.Background(), tx) tx.Commit() ``` ``` -------------------------------- ### Setting a 'To Many' Relationship in SQLBoiler Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Illustrates how to set or replace all existing 'to many' relationships with a new set of related records. Includes examples for both existing and new records. ```go pilots, _ := models.Pilots().All(ctx, db) languages, _ := models.Languages().All(ctx, db) // Set a group of language relationships err := pilots.SetLanguages(db, false, &languages) languages := []*models.Language{ {Language: "Strayan"}, {Language: "Yupik"}, {Language: "Pawnee"}, } // Insert new a group of languages and assign them to a pilot err := pilots.SetLanguages(ctx, db, true, languages...) ``` -------------------------------- ### Add sqlboiler as Project Dependency Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Installs sqlboiler v4 and the null package as project dependencies, updating your go.mod file. Ensure you are inside your Go module's directory tree. ```shell go get github.com/aarondl/sqlboiler/v4 # Assuming you're going to use the null package for its additional null types go get github.com/aarondl/null/v8 ``` -------------------------------- ### Basic User Query with SQLBoiler Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Demonstrates how to query all users using the generated models. Ensure the 'boil' package is imported and optionally set globally with boil.SetDB for convenience. ```go import ( // Import this so we don't have to use qm.Limit etc. . "github.com/aarondl/sqlboiler/v4/queries/qm" ) // Open handle to database like normal db, err := sql.Open("postgres", "dbname=fun user=abc") if err != nil { return err } // If you don't want to pass in db to all generated methods // you can use boil.SetDB to set it globally, and then use // the G variant methods like so (--add-global-variants to enable) boil.SetDB(db) users, err := models.Users().AllG(ctx) ``` ```go // Query all users users, err := models.Users().All(ctx, db) ``` ```go // Panic-able if you like to code that way (--add-panic-variants to enable) users := models.Users().AllP(db) ``` -------------------------------- ### SQL Enum Definition Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Example SQL syntax for creating an ENUM type in PostgreSQL. ```sql CREATE TYPE workday AS ENUM('monday', 'tuesday', 'wednesday', 'thursday', 'friday'); CREATE TABLE event_one ( id serial PRIMARY KEY NOT NULL, name VARCHAR(255), day workday NOT NULL ); ``` -------------------------------- ### Configure PostgreSQL Blacklist Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Example of using the blacklist configuration option for PostgreSQL to exclude specific tables or columns from generation. Be aware of potential issues with foreign keys referencing excluded items. ```toml [psql] blacklist = ["migrations", "addresses.name", "*.secret_col"] ``` -------------------------------- ### Get Debug Writer Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Returns the debug writer for the context, or the global `boil.DebugWriter` if not set. ```go func DebugWriterFrom(ctx context.Context) io.Writer ``` -------------------------------- ### Get Timestamp Location Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Returns the current timezone for automatic timestamps. Defaults to `time.UTC`. ```go func GetLocation() *time.Location ``` -------------------------------- ### Inflection Rules Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for customizing plural, singular, and irregular word forms. ```toml [inflections.plural] ium = "ia" [inflections.plural_exact] stadium = "stadia" [inflections.singular] ia = "ium" [inflections.singular_exact] stadia = "stadium" [inflections.irregular] radius = "radii" ``` -------------------------------- ### User Model Starter Variants (Global and Panic) Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Shows alternative starter methods generated when flags like --add-global-variants and --add-panic-variants are enabled. UsersG uses a global DB, and methods with a 'P' suffix panic on error. ```go func Users(mods ...qm.QueryMod) *queries.Query func UsersG(mods ...qm.QueryMod) *queries.Query // Uses global DB // Regular finishers gain P suffix users, err := models.Users().All(ctx, db) users := models.Users().AllP(ctx, db) // Panics on error ``` -------------------------------- ### Get SELECT Clause Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/queries-package.md Retrieves the current list of columns specified in the SELECT clause of the query. ```go func GetSelect(q *Query) []string ``` -------------------------------- ### Foreign Key Definition Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for defining foreign keys that are not present in the database schema. ```toml [foreign_keys.jet_pilots_fkey] table = "jets" column = "pilot_id" foreign_table = "pilots" foreign_column = "id" ``` -------------------------------- ### BeginTx Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Begins a context-aware transaction with options using the global database handle. Panics if the database doesn't support context transactions. ```APIDOC ## BeginTx ### Description Begins a context-aware transaction with options using the global database handle. Panics if the database doesn't support context transactions. ### Signature `func BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)` ### Example ```go boil.SetDB(db) tx, err := boil.BeginTx(ctx, &sql.TxOptions{ Isolation: sql.LevelSerializable, }) if err != nil { return err } defer tx.Rollback() ``` ``` -------------------------------- ### Beginner Interface Definition Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Interface for beginning a transaction without options. ```go type Beginner interface { Begin() (*sql.Tx, error) } ``` -------------------------------- ### Type Replacement Configuration Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for overriding inferred column types and specifying custom imports. ```toml [[types]] [types.match] type = "null.String" nullable = true [types.replace] type = "mynull.String" [types.imports] third_party = ['"github.com/me/mynull"'] ``` -------------------------------- ### Column and Table Aliases Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for renaming tables, columns, and foreign keys in generated code. ```toml [aliases.tables.user_profiles] up_singular = "UserProfile" up_plural = "UserProfiles" [aliases.tables.user_profiles.columns] first_name = "FirstName" last_name = "LastName" [aliases.tables.user_profiles.relationships.fk_user_id] foreign = "User" ``` -------------------------------- ### Set LIMIT and OFFSET Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Control the number of results returned and the starting point using LIMIT and OFFSET clauses. ```go Limit(15) Offset(5) ``` -------------------------------- ### DeleteAll Finisher Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Deletes all user records created before a specified old date. Returns the number of rows affected. ```go rowsAff, err := models.Users(qm.Where("created_at < ?", oldDate)).DeleteAll(ctx, db) ``` -------------------------------- ### UpdateAll Finisher Example Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Updates the 'last_email_sent_at' timestamp for all users whose status is 'inactive'. Returns the number of rows affected. ```go rowsAff, err := models.Users(qm.Where("status = ?", "inactive")). UpdateAll(ctx, db, models.M{ "last_email_sent_at": time.Now(), }) ``` -------------------------------- ### Alias Many-to-Many Relationship Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Configure aliases for many-to-many relationships in TOML format. This example renames the relationship between videos and tags. ```toml [aliases.tables.video_tags.relationships.fk_video_id] local = "Rags" foreign = "Videos" ``` -------------------------------- ### Select Users with WHERE Clauses Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md Demonstrates selecting users based on different WHERE conditions, including single, multiple (AND), and type-safe conditions. ```go // Single condition users, err := models.Users( Where("age > ?", 18), ).All(ctx, db) // Multiple conditions (AND) users, err := models.Users( Where("age > ?", 18), And("status = ?", "active"), ).All(ctx, db) // Type-safe WHERE users, err := models.Users( models.UserWhere.Age.GT(18), models.UserWhere.Status.EQ("active"), ).All(ctx, db) ``` -------------------------------- ### Begin Transaction Using Global DB Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Begins a transaction using the global database handle set via `SetDB`. Panics if the database doesn't support transactions. ```go boil.SetDB(db) tx, err := boil.Begin() if err != nil { return err } defer tx.Rollback() users, err := models.Users().All(context.Background(), tx) tx.Commit() ``` -------------------------------- ### Import Path for Queries Package Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/queries-package.md Standard import path for the main queries package. ```go import "github.com/aarondl/sqlboiler/v4/queries" ``` -------------------------------- ### Count Records with SQLBoiler Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Use the `Count` finisher to get the total number of records in a table. This is a basic query operation. ```go // SELECT COUNT(*) FROM pilots; count, err := models.Pilots().Count(ctx, db) ``` -------------------------------- ### SetUpdate Function Signature Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/queries-package.md Sets the UPDATE clause with column values for a query. ```go func SetUpdate(q *Query, cols map[string]any) ``` -------------------------------- ### Run tests Source: https://github.com/aarondl/sqlboiler/blob/master/CONTRIBUTING.md Execute this command to run the project's tests. ```bash ./boil.sh test ``` -------------------------------- ### Automatic Column Naming Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for customizing the names of automatic timestamp columns like created_at, updated_at, and deleted_at. ```toml [auto_columns] created = "created_at" updated = "updated_at" deleted = "deleted_at" ``` -------------------------------- ### SQLBoiler Query Building Pattern Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/00-START-HERE.md Illustrates the fundamental pattern for building queries in SQLBoiler, consisting of a Starter, Query Mods, and a Finisher. ```go models.TableName(qm.Modifier(), qm.Modifier()).Finisher(ctx, db) ↑ ↑ ↑ Starter Query Mods Finisher ``` -------------------------------- ### Postgres Schema Definition Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Defines the tables, primary keys, foreign keys, and composite primary keys for the example database schema. ```sql CREATE TABLE pilots ( id integer NOT NULL, name text NOT NULL ); ALTER TABLE pilots ADD CONSTRAINT pilot_pkey PRIMARY KEY (id); CREATE TABLE jets ( id integer NOT NULL, pilot_id integer NOT NULL, age integer NOT NULL, name text NOT NULL, color text NOT NULL ); ALTER TABLE jets ADD CONSTRAINT jet_pkey PRIMARY KEY (id); ALTER TABLE jets ADD CONSTRAINT jet_pilots_fkey FOREIGN KEY (pilot_id) REFERENCES pilots(id); CREATE TABLE languages ( id integer NOT NULL, language text NOT NULL ); ALTER TABLE languages ADD CONSTRAINT language_pkey PRIMARY KEY (id); -- Join table CREATE TABLE pilot_languages ( pilot_id integer NOT NULL, language_id integer NOT NULL ); -- Composite primary key ALTER TABLE pilot_languages ADD CONSTRAINT pilot_language_pkey PRIMARY KEY (pilot_id, language_id); ALTER TABLE pilot_languages ADD CONSTRAINT pilot_language_pilots_fkey FOREIGN KEY (pilot_id) REFERENCES pilots(id); ALTER TABLE pilot_languages ADD CONSTRAINT pilot_language_languages_fkey FOREIGN KEY (language_id) REFERENCES languages(id); ``` -------------------------------- ### Build all executables Source: https://github.com/aarondl/sqlboiler/blob/master/CONTRIBUTING.md Run this command to build all executables after making changes to core or driver code. ```bash ./boil.sh build all ``` -------------------------------- ### Running SQLBoiler Benchmarks Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Command to execute benchmarks for SQLBoiler. Ensure you have the boilbench repository cloned. ```bash go test -bench . -benchmem ``` -------------------------------- ### Add FOR Clause for Row Locking Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/query-mods.md Appends a FOR clause to the query for row locking, which is database-specific. Example shows PostgreSQL's FOR UPDATE NOWAIT. ```go func For(clause string) QueryMod ``` ```go models.Users( qm.Where("id = ?", 1), qm.For("UPDATE NOWAIT"), ).One(ctx, db) // Generates: FOR UPDATE NOWAIT (PostgreSQL) ``` -------------------------------- ### ContextBeginner Interface Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Begins a transaction with context and options. Implemented by `*sql.DB`. ```APIDOC ## ContextBeginner Interface ### Description Begins a transaction with context and options. Implemented by `*sql.DB`. ### Methods - `BeginTx(context.Context, *sql.TxOptions) (*sql.Tx, error)` ``` -------------------------------- ### Execute Operations within a Transaction Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/00-START-HERE.md Demonstrates how to begin a transaction, perform operations (like insert), and then commit or rollback the transaction. ```go tx, err := db.BeginTx(ctx, nil) deferr tx.Rollback() user.Insert(ctx, tx, boil.Infer()) er := tx.Commit() ``` -------------------------------- ### Complex User Query with SQLBoiler Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Illustrates how to construct more complex queries by chaining methods like Where, Limit, and Offset. Ensure the necessary query modifiers are imported. ```go // More complex query users, err := models.Users(Where("age > ?", 30), Limit(5), Offset(6)).All(ctx, db) ``` ```go // Ultra complex query users, err := models.Users( Select("id", "name"), InnerJoin("credit_cards c on c.user_id = users.id"), Where("age > ?", 30), AndIn("c.kind in ?", "visa", "mastercard"), Or("email like ?", `%aol.com%`), GroupBy("id", "name"), Having("count(c.id) > ?", 2), Limit(5), Offset(6), ).All(ctx, db) ``` -------------------------------- ### Using Transactions with SQLBoiler Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Shows how to execute queries within a database transaction using `db.BeginTx`. This is recommended for multiple related database operations. ```go // Use any "boil.Executor" implementation (*sql.DB, *sql.Tx, data-dog mock db) // for any query. tx, err := db.BeginTx(ctx, nil) if err != nil { return err } users, err := models.Users().All(ctx, tx) ``` -------------------------------- ### Execute Raw SQL with Bind Parameters Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md Use this to execute custom SQL queries with bind parameters. Ensure the struct used for binding matches the query's selected columns. ```go type UserStats struct { ID int `boil:"id"` Name string `boil:"name"` Count int `boil:"count"` } var stats []UserStats er := queries.Raw( ` SELECT u.id, u.name, COUNT(p.id) as count FROM users u LEFT JOIN posts p ON p.user_id = u.id GROUP BY u.id, u.name `).Bind(ctx, db, &stats) ``` -------------------------------- ### Column Management for Inserts Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/00-START-HERE.md Demonstrates different strategies for controlling which columns are included during an insert operation: inferring, whitelisting, blacklisting, and greylisting. ```go user.Insert(ctx, db, boil.Infer()) user.Insert(ctx, db, boil.Whitelist("name")) user.Insert(ctx, db, boil.Blacklist("secret")) user.Insert(ctx, db, boil.Greylist("id")) ``` -------------------------------- ### Get Global Context Database Handle Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md Returns the global database handle as a ContextExecutor. Returns nil if the handle doesn't support context methods. ```go func GetContextDB() ContextExecutor ``` -------------------------------- ### Execute Query with Different Executors Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/README.md Illustrates executing a query using different types of database executors, such as a connection pool (*sql.DB) or a transaction (*sql.Tx). ```go models.Users().All(ctx, db) // Using connection pool models.Users().All(ctx, tx) // Using transaction ``` -------------------------------- ### Custom Template Directory Configuration Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generation-system.md Demonstrates how to specify custom template directories for SQLBoiler using the `--templates` flag. Multiple directories can be provided, with later ones overriding earlier ones. ```bash sqlboiler --templates=/path/to/my/templates --templates=/path/to/sqlboiler/templates psql ``` -------------------------------- ### Struct Tag Casing Customization Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Example TOML configuration for customizing struct tag casing for different tag types like JSON, YAML, and TOML. ```toml [struct_tag_cases] json = "camel" yaml = "camel" toml = "snake" boil = "alias" ``` -------------------------------- ### Select All Users Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md Fetches all records from the users table and prints their names. Ensure the database connection and context are properly set up. ```go package main import ( "context" "database/sql" "fmt" "log" "github.com/aarondl/sqlboiler/v4/boil" . "github.com/aarondl/sqlboiler/v4/queries/qm" "myapp/models" ) func main() { db, err := sql.Open("postgres", "dbname=myapp user=postgres") if err != nil { log.Fatal(err) } defer db.Close() ctx := context.Background() // Simple select all users, err := models.Users().All(ctx, db) if err != nil { log.Fatal(err) } for _, user := range users { fmt.Println(user.Name) } } ``` -------------------------------- ### Use Common Table Expressions (CTEs) Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md Employ CTEs for complex queries by defining them within the query builder. This example selects users from a CTE named 'active_users'. ```go users, err := models.Users( With("active_users AS (SELECT * FROM users WHERE active = ?)"), From("active_users"), ).All(ctx, db) ``` -------------------------------- ### Setting Relationships Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md Shows how to establish or update relationships between models. It covers inserting a new user and setting them as the author of a post, or updating the author of an existing post. ```go post, _ := models.FindPost(ctx, db, 1) user := &models.User{Name: "Alice"} // Insert user and set as author of post err := post.SetUser(ctx, db, true, user) // Or update existing relationship existingUser, _ := models.FindUser(ctx, db, 2) err = post.SetUser(ctx, db, false, existingUser) ``` -------------------------------- ### Fetching Relationships with SQLBoiler Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Demonstrates how to retrieve related data, such as a user's favorite movies, after fetching a primary record. Ensure the relationship methods are generated. ```go // Relationships user, err := models.Users().One(ctx, db) if err != nil { return err } movies, err := user.FavoriteMovies().All(ctx, db) ``` -------------------------------- ### Upsert User Record (PostgreSQL) Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/generated-models.md Inserts a user record or updates it if a conflict exists on the specified columns. This example demonstrates the PostgreSQL specific 'update on conflict' behavior. ```go func (u *User) Upsert( ctx context.Context, exec boil.ContextExecutor, updateOnConflict bool, conflictColumns []string, updateColumns boil.Columns, insertColumns boil.Columns, opts ...interface{}, ) error ``` ```go user := &models.User{ID: 1, Name: "Alice"} err := user.Upsert( ctx, db, true, // updateOnConflict []string{"id"}, // conflictColumns boil.Whitelist("name"), // updateColumns boil.Infer(), // insertColumns ) ``` -------------------------------- ### Define Type Replacements Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/configuration.md Customize how SQLBoiler maps database types to Go types. This example shows how to replace a nullable string type with a regular string type. ```toml [[types]] [types.match] type = "null.String" nullable = true [types.replace] type = "string" ``` -------------------------------- ### Eager Loading in SQLBoiler Source: https://github.com/aarondl/sqlboiler/blob/master/README.md Illustrates how to use eager loading to efficiently retrieve related data and avoid N+1 query issues. Shows both string-based and type-safe relationship loading. ```go // Avoid this loop query pattern, it is slow. jets, _ := models.Jets().All(ctx, db) pilots := make([]models.Pilot, len(jets)) for i := 0; i < len(jets); i++ { pilots[i] = jets[i].Pilot().OneP(ctx, db) } // Instead, use Eager Loading! jets, _ := models.Jets(Load("Pilot")).All(ctx, db) // Type safe relationship names exist too: jets, _ := models.Jets(Load(models.JetRels.Pilot)).All(ctx, db) // Then access the loaded structs using the special Relation field for _, j := range jets { _ = j.R.Pilot } ``` ```go // Example of a nested load. // Each jet will have its pilot loaded, and each pilot will have its languages loaded. jets, _ := models.Jets(Load("Pilot.Languages")).All(ctx, db) // Note that each level of a nested Load call will be loaded. No need to call Load() multiple times. // Type safe queries exist for this too! jets, _ := models.Jets(Load(Rels(models.JetRels.Pilot, models.PilotRels.Languages))).All(ctx, db) ``` ```go // A larger example. In the below scenario, Pets will only be queried one time, despite // showing up twice because they're the same query (the user's pets) users, _ := models.Users( Load("Pets.Vets"), // the query mods passed in below only affect the query for Toys // to use query mods against Pets itself, you must declare it separately Load("Pets.Toys", Where("toys.deleted = ?", isDeleted)), Load("Property"), Where("age > ?", 23), ).All(ctx, db) ``` -------------------------------- ### Generate models from existing tables Source: https://github.com/aarondl/sqlboiler/blob/master/CONTRIBUTING.md Use this command to generate your models from existing database tables. Replace '[driver]' with your specific database driver. ```bash ./boil.sh gen [driver] ``` -------------------------------- ### Import Path Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/boil-package.md All types and functions are in the `github.com/aarondl/sqlboiler/v4/boil` package. ```APIDOC ## Import Path ### Description All types and functions are in the `github.com/aarondl/sqlboiler/v4/boil` package. ### Code ```go import "github.com/aarondl/sqlboiler/v4/boil" ``` ``` -------------------------------- ### Distinct Clause Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/usage-guide.md Demonstrates how to retrieve unique values for a specific column using the DISTINCT clause. This is useful for getting a list of all unique statuses present in the users table. ```go statuses, err := models.Users( Select("status"), Distinct("status"), ).All(ctx, db) ``` -------------------------------- ### Reflection Utilities Source: https://github.com/aarondl/sqlboiler/blob/master/_autodocs/API-INDEX.md Provides utility functions for working with Go reflection, particularly useful for data mapping and manipulation within SQLBoiler. ```APIDOC ## Reflection Utilities This section details utility functions for reflection operations. ### Functions - `MakeStructMapping(typ reflect.Type) map[string]uint64`: Creates a mapping of struct field names to their offsets. - `MustTime(val driver.Valuer) time.Time`: Safely extracts a time.Time value from a driver.Valuer. - `SetScanner(scanner sql.Scanner, val driver.Value) error`: Sets a value into a sql.Scanner. - `IsValuerNil(val driver.Valuer) bool`: Checks if a driver.Valuer is nil. - `IsNil(val any) bool`: Checks if any value is nil. - `Equal(a, b any) bool`: Compares two values for equality. - `Assign(dst, src any)`: Assigns values from a source to a destination. - `SetFromEmbeddedStruct(to any, from any) bool`: Sets values from a source struct to a destination struct, handling embedded structs. - `PtrsFromMapping(val reflect.Value, mapping []uint64) []any`: Retrieves pointers to fields from a reflect.Value based on a mapping. - `ValuesFromMapping(val reflect.Value, mapping []uint64) []any`: Retrieves values from a reflect.Value based on a mapping. - `NonZeroDefaultSet(defaults []string, obj any) []string`: Sets non-zero default values on an object. ```