### SQLBoiler Installation Commands Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Provides shell commands for installing the SQLBoiler code generator and its PostgreSQL driver for different Go versions. ```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: ``` -------------------------------- ### SQLBoiler Configuration Example Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates a typical configuration file for SQLBoiler, highlighting settings that might cause issues if not properly configured, such as database connection details. ```toml [settings] # Example: Database connection string # DSN = "postgres://user:password@host:port/dbname?sslmode=disable" # Example: Tables to exclude # ExcludeTables = ["schema_migrations"] ``` -------------------------------- ### Install Null Package for Go Source: https://github.com/volatiletech/sqlboiler/blob/master/CONTRIBUTING.md Installs the 'null' package from GitHub, which may be required before running tests or certain functionalities within the SQLBoiler project. ```go go get -u github.com/aarondl/null ``` -------------------------------- ### SQLBoiler Query Construction Example (Go) Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Provides an example of how to use generated column and where clause helpers to construct complex queries, including OR conditions and direct column references. ```go cols := &models.UserColumns where := &models.UserWhere u, err := models.Users(where.Name.EQ("hello"), qm.Or(cols.Age + "=?", 5)) ``` -------------------------------- ### Go Variable Assignment Example Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md A simple Go variable assignment demonstrating a foreign key name. ```go foreign = "Author" ``` -------------------------------- ### Install sqlboiler v4 and PostgreSQL Driver Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Installs the latest version of sqlboiler v4 and the PostgreSQL driver globally using Go modules. It's recommended to run this outside your project directory. ```shell GO111MODULE=on go get -u -t github.com/aarondl/sqlboiler/v4 GO111MODULE=on go get github.com/aarondl/sqlboiler/v4/drivers/sqlboiler-psql ``` -------------------------------- ### Install sqlboiler v4 as Project Dependency Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Installs sqlboiler v4 and the null package as dependencies within your Go module. This ensures correct versioning in your go.mod file. ```shell # Do not forget the trailing /v4 and /v8 in the following commands 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 ``` -------------------------------- ### Go SQLBoiler Basic and Advanced Queries Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates how to perform basic and complex database queries using SQLBoiler in Go. Includes examples for selecting columns, applying filters, limiting results, and joining tables. ```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) // Query all users users, err := models.Users().All(ctx, db) // Panic-able if you like to code that way (--add-panic-variants to enable) users := models.Users().AllP(db) // More complex query users, err := models.Users(Where("age > ?", 30), Limit(5), Offset(6)).All(ctx, db) // 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) ``` -------------------------------- ### Specify SQLBoiler Custom Template Paths Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Provides an example of how to configure SQLBoiler to use custom template directories via the `--templates` flag, including paths for Go templates, test templates, and additional project templates. ```toml templates = [ "/path/to/sqlboiler/templates", "/path/to/sqlboiler/templates_test", "/path/to/your_project/more_templates" ] ``` -------------------------------- ### Open Database Connection Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates how to establish a connection to a PostgreSQL database using the standard Go `database/sql` package and the `postgres` driver. ```go // Open handle to database like normal db, err := sql.Open("postgres", "dbname=fun user=abc") if err != nil { return err } ``` -------------------------------- ### System Configuration Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Details the hardware and software environment used for running the benchmarks, including Operating System, CPU, Memory, and Go version. ```text OS: Ubuntu 16.04 CPU: Intel(R) Core(TM) i7-4771 CPU @ 3.50GHz Mem: 16GB Go: go version go1.8.1 linux/amd64 ``` -------------------------------- ### SQLBoiler Using boil.BeginTx Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows how to initiate a transaction using the `boil.BeginTx()` function, which utilizes a globally stored database connection. ```go // Example usage of boil.BeginTx (function signature not shown) // tx := boil.BeginTx(ctx, db) ``` -------------------------------- ### SQLBoiler Go API Initialization and Debugging Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates essential Go API calls for initializing SQLBoiler's global database handle and enabling debug mode for troubleshooting. ```go import ( "os" "github.com/volatiletech/sqlboiler/v4/boil" ) func setupBoiler() { // Ensure your passed in boil.Executor is not nil. // If you decide to use the G variant of functions instead, make sure you've initialized your // global database handle using boil.SetDB(). // boil.SetDB(dbHandle) // Setting boil.DebugMode to true can help with debugging. boil.DebugMode = true // You can change the output using boil.DebugWriter (defaults to os.Stdout). // boil.DebugWriter = os.Stdout } ``` -------------------------------- ### Insert Pilot with SQLBoiler Go Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates inserting pilot records into the database using SQLBoiler. It explains the behavior of column lists like Infer and Whitelist, and how SQLBoiler handles Go zero values versus database default values during insertion. ```go var p1 models.Pilot p1.Name = "Larry" err := p1.Insert(ctx, db, boil.Infer()) // Insert the first pilot with name "Larry" // p1 now has an ID field set to 1 var p2 models.Pilot p2.Name = "Boris" err := p2.Insert(ctx, db, boil.Infer()) // Insert the second pilot with name "Boris" // p2 now has an ID field set to 2 var p3 models.Pilot p3.ID = 25 p3.Name = "Rupert" err := p3.Insert(ctx, db, boil.Infer()) // Insert the third pilot with a specific ID // The id for this row was inserted as 25 in the database. var p4 models.Pilot p4.ID = 0 p4.Name = "Nigel" err := p4.Insert(ctx, db, boil.Whitelist("id", "name")) // Insert the fourth pilot with a zero value ID // The id for this row was inserted as 0 in the database. // Note: We had to use the whitelist for this, otherwise // SQLBoiler would presume you wanted to auto-increment ``` -------------------------------- ### SQLBoiler Model Generation and Testing Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates the basic workflow for generating Go ORM models using SQLBoiler with a specific database driver (e.g., PostgreSQL) and how to run the generated compatibility tests. ```sh # Generate our models and exclude the migrations table # When passing 'psql' here, it looks for a binary called # 'sqlboiler-psql' in your CWD and PATH. You can also pass # an absolute path to a driver if you desire.sqlboiler psql # Run the generated tests go test ./models ``` -------------------------------- ### Limit Query Results with SQLBoiler Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows how to fetch a limited number of records from a table using the starter method, the Limit query mod, and the All finisher. Useful for pagination or previewing data. ```go // SELECT * FROM "pilots" LIMIT 5; pilots, err := models.Pilots(qm.Limit(5)).All(ctx, db) ``` -------------------------------- ### Count Records with SQLBoiler Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates how to count all records in a table using the starter method and the Count finisher. This is a common operation for retrieving the total number of items. ```go // SELECT COUNT(*) FROM pilots; count, err := models.Pilots().Count(ctx, db) ``` -------------------------------- ### SQLBoiler Benchmark Command (Bash) Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows the command to run benchmarks for SQLBoiler, allowing users to measure performance and compare it against other ORMs or custom solutions. ```bash go test -bench . -benchmem ``` -------------------------------- ### Go SQLBoiler Transactions and Relationships Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates how to use SQLBoiler with database transactions and how to fetch related data. Shows fetching a single user and then their favorite movies, and eager loading relationships. ```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) // Relationships user, err := models.Users().One(ctx, db) if err != nil { return err } movies, err := user.FavoriteMovies().All(ctx, db) // Eager loading users, err := models.Users(Load("FavoriteMovies")).All(ctx, db) if err != nil { return err } fmt.Println(len(users.R.FavoriteMovies)) ``` -------------------------------- ### Go: Simple Function Extension for SQLBoiler Models Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates extending SQLBoiler models with standalone Go functions. This method is highly testable as all dependencies are passed as parameters, making it the most desirable approach for adding helper logic. ```go // Package modext is for SQLBoiler helper methods package modext import ( "context" "database/sql" "volatiletech/sqlboiler/models" ) // UserFirstTimeSetup is an extension of the user model. func UserFirstTimeSetup(ctx context.Context, db *sql.DB, u *models.User) error { return nil /* ... */ } ``` ```go user, err := Users().One(ctx, db) // elided error check err = modext.UserFirstTimeSetup(ctx, db, user) // elided error check ``` -------------------------------- ### SQLBoiler Integration with Go Generate Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows how to use the `go generate` command to automate the SQLBoiler model generation process, ensuring models are updated with the build. ```go //go:generate sqlboiler --flags-go-here psql ``` -------------------------------- ### SQLBoiler CLI Usage and Flags Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Displays the command-line interface usage for SQLBoiler, including available drivers and configuration flags. This output details options for customizing ORM generation. ```text SQL Boiler generates a Go ORM from template files, tailored to your database schema. Complete documentation is available at http://github.com/aarondl/sqlboiler Usage: sqlboiler [flags] Examples: sqlboiler psql Flags: --add-global-variants Enable generation for global variants --add-panic-variants Enable generation for panic variants --add-soft-deletes Enable soft deletion by updating deleted_at timestamp --add-enum-types Enable generation of types for enums --enum-null-prefix Name prefix of nullable enum types (default "Null") -c, --config string Filename of config file to override default lookup -d, --debug Debug mode prints stack traces on error -h, --help help for sqlboiler --no-auto-timestamps Disable automatic timestamps for created_at/updated_at --no-back-referencing Disable back referencing in the loaded relationship structs --no-context Disable context.Context usage in the generated code --no-driver-templates Disable parsing of templates defined by the database driver --no-hooks Disable hooks feature for your models --no-rows-affected Disable rows affected in the generated API --no-tests Disable generated go test files --no-relation-getters Disable generating getters for relationship tables -o, --output string The name of the folder to output to (default "models") -p, --pkgname string The name you wish to assign to your generated package (default "models") --struct-tag-casing string Decides the casing for go structure tag names. camel, title, alias or snake (default "snake") -t, --tag strings Struct tags to be included on your models in addition to json, yaml, toml --tag-ignore strings List of column names that should have tags values set to '-' (ignored during parsing) --templates strings A templates directory, overrides the embedded template folders in sqlboiler --replace strings An array of templates file and the actual template file to be replaces --version Print the version --strict-verify-mod-version Prevent code generation, if project version of sqlboiler not match with executable --wipe Delete the output folder (rm -rf) before generation to ensure sanity ``` -------------------------------- ### Query Mod System: WHERE Clause Building Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates building WHERE clauses, including simple equality checks, type-safe comparisons, and constructing complex conditions using `Expr` for manual grouping and `Or2` for OR logic. It also covers WHERE IN clauses for multiple values. ```go // WHERE clause building Where("name=?", "John") models.PilotWhere.Name.EQ("John") And("age=?", 24) // No equivalent type safe query yet Or("height=?", 183) // No equivalent type safe query yet Where("(name=? and age=?) or (age=?)", "John", 5, 6) // Expr allows manual grouping of statements Where( Expr( models.PilotWhere.Name.EQ("John"), Or2(models.PilotWhere.Age.EQ(5)), ), Or2(models.PilotAge), ) // WHERE IN clause building WhereIn("(name, age) in ?", "John", 24, "Tim", 33) // Generates: WHERE ("name","age") IN (($1,$2),($3,$4)) WhereIn(fmt.Sprintf("(%s, %s) in ?", models.PilotColumns.Name, models.PilotColumns.Age), "John", 24, "Tim", 33) AndIn("weight in ?", 84) AndIn(models.PilotColumns.Weight + " in ?", 84) OrIn("height in ?", 183, 177, 204) OrIn(models.PilotColumns.Height + " in ?", 183, 177, 204) ``` -------------------------------- ### Function Variations: Global and Panic Variants Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Explains how functions can have variations generated using flags like `--add-global-variants` and `--add-panic-variants`. Demonstrates `Delete` method variations: regular, panic (`P`), global (`G`), and global-panic (`GP`), and how to set a global database handle. ```go // Set the global db handle for G method variants. boil.SetDB(db) pilot, _ := models.FindPilot(ctx, db, 1) err := pilot.Delete(ctx, db) // Regular variant, takes a db handle (boil.Executor interface). pilot.DeleteP(ctx, db) // Panic variant, takes a db handle and panics on error. err := pilot.DeleteG(ctx) // Global variant, uses the globally set db handle (boil.SetDB()). pilot.DeleteGP(ctx) // Global&Panic variant, combines the global db handle and panic on error. 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 Raw Query Execution Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows how to execute raw SQL queries using `queries.Raw()` and bind the results to Go structs. Supports binding to generated or custom structs, and executing queries without binding. ```go err := queries.Raw("select * from pilots where id=$1", 5).Bind(ctx, db, &obj) ``` -------------------------------- ### Update Pilot with SQLBoiler Go Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates updating pilot records in the database using SQLBoiler. It covers updating single objects, slices of objects, and collections, explaining the use of whitelists to specify which columns should be updated. ```go // Find a pilot and update his name pilot, _ := models.FindPilot(ctx, db, 1) pilot.Name = "Neo" rowsAff, err := pilot.Update(ctx, db, boil.Infer()) // Update a slice of pilots to have the name "Smith" pilots, _ := models.Pilots().All(ctx, db) rowsAff, err := pilots.UpdateAll(ctx, db, models.M{"name": "Smith"}) // Update all pilots in the database to to have the name "Smith" rowsAff, err := models.Pilots().UpdateAll(ctx, db, models.M{"name": "Smith"}) ``` -------------------------------- ### SQLBoiler Custom Template Directory Structure Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates the expected directory structure for custom SQLBoiler templates. It shows how to organize template files, including singletons and language-specific templates, for generating non-Go files or custom Go files. ```text templates/ ├── 00_struct.go.tpl # Merged into output_dir/table_name.go ├── 00_struct.js.tpl # Merged into output_dir/table_name.js ├── singleton │ └── boil_queries.go.tpl # Rendered as output_dir/boil_queries.go └── js ├── jsmodel.js.tpl # Merged into output_dir/js/table_name.js └── singleton └── jssingle.js.tpl # Merged into output_dir/js/jssingle.js ``` -------------------------------- ### Run SQLBoiler Tests Source: https://github.com/volatiletech/sqlboiler/blob/master/CONTRIBUTING.md Executes the test suite for SQLBoiler. This command is used to verify the integrity and correctness of the project after making changes or for general testing. ```shell ./boil.sh test ``` -------------------------------- ### Delete Records with SQLBoiler Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates how to delete records from a table using the starter method, a Where query mod, and the DeleteAll finisher. It shows both string-based and type-safe query conditions. ```go // DELETE FROM "pilots" WHERE "id"=$1; err := models.Pilots(qm.Where("id=?", 1)).DeleteAll(ctx, db) // type safe version of above err := models.Pilots(models.PilotWhere.ID.EQ(1)).DeleteAll(ctx, db) ``` -------------------------------- ### Query Mod System: Joins, Grouping, Ordering, and Limits Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Covers methods for specifying JOIN clauses, GROUP BY and ORDER BY clauses (including type-safe options), setting LIMIT and OFFSET, and applying explicit table locking with `For`. ```go InnerJoin("pilots p on jets.pilot_id=?", 10) InnerJoin(models.TableNames.Pilots + " p on " + models.TableNames.Jets + "." + models.JetColumns.PilotID + "=?", 10) GroupBy("name") GroupBy("name like ? DESC, name", "John") GroupBy(models.PilotColumns.Name) OrderBy("age, height") OrderBy(models.PilotColumns.Age, models.PilotColumns.Height) Having("count(jets) > 2") Having(fmt.Sprintf("count(%s) > 2", models.TableNames.Jets)) Limit(15) Offset(5) // Explicit locking For("update nowait") ``` -------------------------------- ### SQLBoiler Select Specific Columns Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows how to select specific columns for multiple rows using `qm.Select` with string names and a type-safe variant using `models.JetColumns`. ```go // Select specific columns of many jets jets, err := models.Jets(qm.Select("age", "name")).All(ctx, db) // Type safe variant jets, err := models.Jets(qm.Select(models.JetColumns.Age, models.JetColumns.Name)).All(ctx, db) ``` -------------------------------- ### To One Relationship Management Methods Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Details the helper methods generated for 'to one' relationships. `SetX` is used to establish or change a foreign key relationship, and `RemoveX` is used to nullify the foreign key, effectively breaking the link. These operations should ideally be performed within transactions. ```APIDOC SetX(ctx context.Context, exec boil.Executor, insert bool, related *Model) error - Sets the foreign key to point to another model. - Parameters: - ctx: The context for the operation. - exec: The database executor. - insert: If true, the related model will be inserted into the database if it doesn't exist. - related: A pointer to the related model to associate. - Example: jet.SetPilot(ctx, db, false, &pilot) jet.SetPilot(ctx, db, true, &pilot) // Inserts pilot if it doesn't exist RemoveX(ctx context.Context, exec boil.Executor, related *Model) error - Nullifies the foreign key, removing the relationship. - This method is only available for foreign keys that can be NULL. - Parameters: - ctx: The context for the operation. - exec: The database executor. - related: A pointer to the related model to disassociate. - Example: jet.RemovePilot(ctx, db, &pilot) ``` -------------------------------- ### Enum Generation in Go Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates how SQL ENUM types from PostgreSQL and MySQL are converted into Go constants. It shows the generated Go const block and explains the naming conventions used for different database systems. ```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 ); ``` ```go const ( WorkdayMonday = "monday" WorkdayTuesday = "tuesday" WorkdayWednesday = "wednesday" WorkdayThursday = "thursday" WorkdayFriday = "friday" ) ``` -------------------------------- ### SQLBoiler Transaction Management Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates how to manage database transactions using `db.BeginTx`, `tx.Commit()`, and `tx.Rollback()`. It highlights that `sql.DB` and `sql.Tx` conform to the `boil.Executor` interface. ```go tx, err := db.BeginTx(ctx, nil) if err != nil { return err } users, _ := models.Pilots().All(ctx, tx) users.DeleteAll(ctx, tx) // Rollback or commit tx.Commit() tx.Rollback() ``` -------------------------------- ### Query Mod System: Basic Operations Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates fundamental query modification methods like executing raw SQL, selecting specific columns using string literals or type-safe identifiers, and manually specifying the FROM table. It highlights the use of dot imports for query modifiers and the safety of type-safe identifiers. ```go // Dot import so we can access query mods directly instead of prefixing with "qm." import . "github.com/aarondl/sqlboiler/v4/queries/qm" // Use a raw query against a generated struct (Pilot in this example) // If this query mod exists in your call, it will override the others. // "?" placeholders are not supported here, use "$1, $2" etc. SQL("select * from pilots where id=$1", 10) models.Pilots(SQL("select * from pilots where id=$1", 10)).All() Select("id", "name") // Select specific columns. Select(models.PilotColumns.ID, models.PilotColumns.Name) From("pilots as p") // Specify the FROM table manually, can be useful for doing complex queries. From(models.TableNames.Pilots + " as p") ``` -------------------------------- ### Eager Loading Relationships (Basic and Type-Safe) Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates the contrast between inefficient loop-based queries and the recommended eager loading approach. Eager loading fetches related data in fewer queries, preventing N+1 performance issues. It 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 } ``` -------------------------------- ### Build Executable with SQLBoiler Source: https://github.com/volatiletech/sqlboiler/blob/master/CONTRIBUTING.md Command to build the SQLBoiler executable. This should be run after making changes to core or driver code to ensure the executable reflects the latest modifications. ```shell ./boil.sh build all ``` -------------------------------- ### Go: Empty Struct Method Extension for SQLBoiler Models Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md An alternative method for extending SQLBoiler models by defining methods on an empty struct. This offers slightly more organization than simple functions but incurs a minor runtime cost and offers minimal benefit over the first method. ```go // Package modext is for SQLBoiler helper methods package modext import ( "context" "database/sql" "volatiletech/sqlboiler/models" ) type users struct {} var Users = users{} // FirstTimeSetup is an extension of the user model. func (users) FirstTimeSetup(ctx context.Context, db *sql.DB, u *models.User) error { return nil /* ... */ } ``` ```go user, err := Users().One(ctx, db) // elided error check err = modext.Users.FirstTimeSetup(ctx, db, user) // elided error check ``` -------------------------------- ### Query Mod System: Combined Clauses Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows that query modifiers can be combined into a single clause, demonstrating flexibility in how complex queries are constructed without necessarily breaking them into separate method calls. ```go Where("(name=? OR age=?) AND height=?", "John", 24, 183) ``` -------------------------------- ### Generate Models with SQLBoiler Source: https://github.com/volatiletech/sqlboiler/blob/master/CONTRIBUTING.md Command to generate SQLBoiler models from existing database tables. Replace '[driver]' with the specific database driver you are using (e.g., 'postgres', 'mysql'). ```shell ./boil.sh gen [driver] ``` -------------------------------- ### Retrieve Related Models (To One and To Many) Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates how to find a parent model (e.g., Jet) and then retrieve its associated 'to one' model (e.g., Pilot) and subsequently its 'to many' related models (e.g., Languages). These helpers are attached directly to the model structs. ```go jet, _ := models.FindJet(ctx, db, 1) // "to one" relationship helper method. // This will retrieve the pilot for the jet. pilot, err := jet.Pilot().One(ctx, db) // "to many" relationship helper method. // This will retrieve all languages for the pilot. languages, err := pilot.Languages().All(ctx, db) ``` -------------------------------- ### Complex Eager Loading with Filters Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates advanced eager loading scenarios, including loading multiple distinct relationships for a single model, applying query modifiers (like WHERE clauses) to specific eager loads, and handling cases where related data appears multiple times in the query graph. ```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) ``` -------------------------------- ### SQLBoiler Custom Struct Binding Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Illustrates binding query results to custom Go structs, including structs that embed multiple generated models or select a subset of data. Demonstrates using `Bind()` with custom structs for complex queries. ```go // Custom struct using two generated structs type PilotAndJet struct { models.Pilot `boil:",bind"` models.Jet `boil:",bind"` } var paj PilotAndJet // Use a raw query err := queries.Raw(` select pilots.id as "pilots.id", pilots.name as "pilots.name", jets.id as "jets.id", jets.pilot_id as "jets.pilot_id", jets.age as "jets.age", jets.name as "jets.name", jets.color as "jets.color" from pilots inner join jets on jets.pilot_id=?`, 23, ).Bind(ctx, db, &paj) // Use query building err := models.NewQuery( Select("pilots.id", "pilots.name", "jets.id", "jets.pilot_id", "jets.age", "jets.name", "jets.color"), From("pilots"), InnerJoin("jets on jets.pilot_id = pilots.id"), ).Bind(ctx, db, &paj) ``` ```go // Custom struct for selecting a subset of data type JetInfo struct { AgeSum int `boil:"age_sum"` Count int `boil:"juicy_count"` } var info JetInfo // Use query building err := models.NewQuery(Select("sum(age) as age_sum", "count(*) as juicy_count", From("jets"))).Bind(ctx, db, &info) // Use a raw query err := queries.Raw(`select sum(age) as "age_sum", count(*) as "juicy_count" from jets`).Bind(ctx, db, &info) ``` -------------------------------- ### SQLBoiler Decimal Library Version Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Specifies the recommended version for the decimal library to avoid 'pq: encode: unknown type types.NullDecimal' errors. ```go module github.com/ericlagergren/decimal replace github.com/ericlagergren/decimal v0.0.0-20181231230500-73749d4874d5 => github.com/ericlagergren/decimal v0.0.0-20181231230500-73749d4874d5 ``` -------------------------------- ### SQLite3 Configuration Source: https://github.com/volatiletech/sqlboiler/blob/master/drivers/sqlboiler-sqlite3/README.md This snippet demonstrates the TOML configuration for the sqlboiler-sqlite3 driver. It specifies the absolute path to the SQLite database file, which is recommended for consistency during generation and testing. ```toml # Absolute path is recommended since the location\n# sqlite3 is being run can change.\n# For example generation time and model test time.\n[sqlite3]\ndbname = \"/path/to/file\" ``` -------------------------------- ### Configure SQLBoiler Imports Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows how to override default import statements for generated Go code in SQLBoiler. This includes global overrides, overrides for specific files (like boil_queries), and overrides based on data types. ```toml [imports.all] standard = ['"context"'] third_party = ['"github.com/my/package"'] # Changes imports for the boil_queries file [imports.singleton."boil_queries"] standard = ['"context"'] third_party = ['"github.com/my/package"'] # Same syntax as all [imports.test] # Same syntax as singleton [imports.test_singleton] # Changes imports when a model contains null.Int32 [imports.based_on_type.string] standard = ['"context"'] third_party = ['"github.com/my/package"'] ``` ```toml [[imports.singleton]] name = "boil_queries" third_party = ['"github.com/my/package"'] [[imports.based_on_type]] name = "null.Int64" third_party = ['"github.com/int64"'] ``` -------------------------------- ### Query Mod System: CTEs and Eager Loading Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates the use of Common Table Expressions (CTEs) with the `With` clause and eager loading related data using the `Load` method, which can also accept query modifiers for filtering the loaded relationships. ```go // Common Table Expressions With("cte_0 AS (SELECT * FROM table_0 WHERE thing=$1 AND stuff=$2)") // Eager Loading -- Load takes the relationship name, ie the struct field name of the // Relationship struct field you want to load. Optionally also takes query mods to filter on that query. Load("Languages", Where(...)) // If it's a ToOne relationship it's in singular form, ToMany is plural. Load(models.PilotRels.Languages, Where(...)) ``` -------------------------------- ### Upsert Functionality in Go Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates how to use the Upsert method to perform inserts that optionally update existing rows on conflict. It covers different conflict targets, update strategies (DO NOTHING vs. DO UPDATE), and column whitelisting for PostgreSQL, MySQL, and MSSQL. ```go var p1 models.Pilot p1.ID = 5 p1.Name = "Gaben" // INSERT INTO pilots ("id", "name") VALUES($1, $2) // ON CONFLICT DO NOTHING err := p1.Upsert(ctx, db, false, nil, boil.Infer()) ``` ```go // INSERT INTO pilots ("id", "name") VALUES ($1, $2) // ON CONFLICT ("id") DO UPDATE SET "name" = EXCLUDED."name" err := p1.Upsert(ctx, db, true, []string{"id"}, boil.Whitelist("name"), boil.Infer()) ``` ```go // Set p1.ID to a zero value. We will have to use the whitelist now. p1.ID = 0 p1.Name = "Hogan" // INSERT INTO pilots ("id", "name") VALUES ($1, $2) // ON CONFLICT ("id") DO UPDATE SET "name" = EXCLUDED."name" err := p1.Upsert(ctx, db, true, []string{"id"}, boil.Whitelist("name"), boil.Whitelist("id", "name")) ``` ```go // Custom conflict_target expression: // INSERT INTO pilots ("id", "name") VALUES (9, 'Antwerp Design') // ON CONFLICT ON CONSTRAINT pilots_pkey DO NOTHING; conflictTarget := models.UpsertConflictTarget err := p1.Upsert(ctx, db, false, nil, boil.Whitelist("id", "name"), boil.None(), conflictTarget("ON CONSTRAINT pilots_pkey")) ``` ```go // Custom UPDATE SET expression: // INSERT INTO pilots ("id", "name") VALUES (9, 'Antwerp Design') // ON CONFLICT ("id") DO UPDATE SET (id, name) = (sub-SELECT) updateSet := models.UpsertUpdateSet err := p1.Upsert(ctx, db, true, []string{"id"}, boil.Whitelist("id", "name"), boil.None(), updateSet("(id, name) = (sub-SELECT)")) ``` -------------------------------- ### SQLBoiler Where Clause Helpers (Go) Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Shows the generated Go structs used for constructing type-safe WHERE clauses in queries. These helpers abstract column names and operators for cleaner query building. ```go var MessageWhere = struct { ID whereHelperint Text whereHelperstring }{ ID: whereHelperint{field: `id`}, PurchaseID: whereHelperstring{field: `purchase_id`}, } // Usage example: // models.Messages(models.MessageWhere.PurchaseID.EQ("hello")) ``` -------------------------------- ### SQLBoiler Registering a Before Insert Hook Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates how to define a custom hook function and register it for a specific model (e.g., Pilot) using the AddModelHook method. The hook function signature includes context, executor, and the model pointer. ```go // Define my hook function func myHook(ctx context.Context, exec boil.ContextExecutor, p *Pilot) error { // Do stuff return nil } // Register my before insert hook for pilots models.AddPilotHook(boil.BeforeInsertHook, myHook) ``` -------------------------------- ### SQLBoiler Debug Logging Configuration Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Details how to enable and configure debug logging for SQLBoiler, which prints generated SQL statements and their arguments. This involves setting the global `boil.DebugMode` and optionally `boil.DebugWriter`. ```go boil.DebugMode = true // Optionally set the writer as well. Defaults to os.Stdout fh, _ := os.Open("debug.txt") boil.DebugWriter = fh ``` -------------------------------- ### SQL Schema Definition Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Defines the database schema for pilots, jets, and languages, including relationships and primary keys. This schema serves as the basis for generating Go models. ```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); ``` -------------------------------- ### Check Existence of Records in Go Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates how to check if a record exists in the database using the `Exists` method. This can be called on a specific object's relationship or on a query builder instance. ```go jet, err := models.FindJet(ctx, db, 1) // Check if the pilot assigned to this jet exists. exists, err := jet.Pilot().Exists(ctx, db) ``` ```go // Check if the pilot with ID 5 exists exists, err := models.Pilots(Where("id=?", 5)).Exists(ctx, db) ``` -------------------------------- ### TOML Advanced Table Aliasing with Array of Tables Source: https://github.com/volatiletech/sqlboiler/blob/master/README.md Demonstrates advanced TOML configuration using array of tables syntax for aliasing table names, column names, and relationships, including custom struct tag cases. ```toml [[aliases.tables]] name = "team_names" up_plural = "TeamNames" up_singular = "TeamName" down_plural = "teamNames" down_singular = "teamName" [[aliases.tables.columns]] name = "team_name" alias = "OurTeamName" [[aliases.tables.relationships]] name = "fk_video_id" local = "Rags" foreign = "Videos" ```