### Run Fixture Example Source: https://github.com/uptrace/bun/blob/master/example/fixture/README.md Use this command to execute the fixture example. Ensure you have Go installed. ```shell go run main.go ``` -------------------------------- ### Install pgdriver Source: https://github.com/uptrace/bun/blob/master/driver/pgdriver/README.md Use 'go get' to install the pgdriver package. ```shell go get github.com/uptrace/bun/driver/pgdriver ``` -------------------------------- ### Install Bunzerolog Package Source: https://github.com/uptrace/bun/blob/master/extra/bunzerolog/README.md Install the bunzerolog package using go get. ```bash go get github.com/uptrace/bun/extra/bunzerolog ``` -------------------------------- ### Run Basic Example Source: https://github.com/uptrace/bun/blob/master/example/basic/README.md Execute the main application file using the Go runtime. ```shell go run . ``` -------------------------------- ### Clone Repository and Navigate to Example Source: https://github.com/uptrace/bun/blob/master/example/opentelemetry/README.md Clone the Bun repository and navigate to the OpenTelemetry example directory. ```bash git clone https://github.com/uptrace/bun.git cd example/opentelemetry ``` -------------------------------- ### Run Bun Client Example with OpenTelemetry Source: https://github.com/uptrace/bun/blob/master/example/opentelemetry/README.md Execute the Bun client example, providing the Uptrace DSN as an environment variable. This instruments the application for telemetry data collection. ```bash UPTRACE_DSN="http://project1_secret@localhost:14318?grpc=14317" go run client.go ``` -------------------------------- ### Install bunslog Package Source: https://github.com/uptrace/bun/blob/master/extra/bunslog/README.md Use go get to install the bunslog package for your Bun project. ```bash go get github.com/uptrace/bun/extra/bunslog ``` -------------------------------- ### Install Bun ORM Source: https://github.com/uptrace/bun/blob/master/README.md Use 'go get' to add the Bun ORM to your project dependencies. ```bash go get github.com/uptrace/bun ``` -------------------------------- ### Basic Bun ORM Example Source: https://github.com/uptrace/bun/blob/master/README.md Demonstrates setting up Bun with SQLite, defining a model, creating a table, inserting a user, and querying for that user. ```go package main import ( "context" "database/sql" "fmt" "github.com/uptrace/bun" "github.com/uptrace/bun/dialect/sqlitedialect" "github.com/uptrace/bun/driver/sqliteshim" ) func main() { ctx := context.Background() // Open database sqldb, err := sql.Open(sqliteshim.ShimName, "file::memory:") if err != nil { panic(err) } // Create Bun instance db := bun.NewDB(sqldb, sqlitedialect.New()) // Define model type User struct { ID int64 `bun:",pk,autoincrement"` Name string `bun:",notnull"` } // Create table db.NewCreateTable().Model((*User)(nil)).Exec(ctx) // Insert user user := &User{Name: "John Doe"} db.NewInsert().Model(user).Exec(ctx) // Query user err = db.NewSelect().Model(user).Where("id = ?", user.ID).Scan(ctx) fmt.Printf("User: %+v\n", user) } ``` -------------------------------- ### Install sqliteshim Driver Source: https://github.com/uptrace/bun/blob/master/driver/sqliteshim/README.md Install the sqliteshim driver using go get. This command fetches and installs the necessary package for SQLite support. ```shell go get github.com/uptrace/bun/driver/sqliteshim ``` -------------------------------- ### Start Infrastructure Services with Docker Compose Source: https://github.com/uptrace/bun/blob/master/example/opentelemetry/README.md Launch PostgreSQL, ClickHouse, and Uptrace services using Docker Compose. Ensure Docker is running and your user has the necessary permissions. ```bash docker compose pull docker compose up -d ``` -------------------------------- ### Import bunslog Package Source: https://github.com/uptrace/bun/blob/master/extra/bunslog/README.md Import the bunslog package into your Go application to start using its features. ```go import "github.com/uptrace/bun/extra/bunslog" ``` -------------------------------- ### Verify Uptrace Service Logs Source: https://github.com/uptrace/bun/blob/master/example/opentelemetry/README.md Check the Uptrace service logs to confirm it has started successfully and is listening on the expected port. ```bash docker compose logs uptrace ``` -------------------------------- ### Stop and Remove Docker Services Source: https://github.com/uptrace/bun/blob/master/example/opentelemetry/README.md Clean up by stopping and removing all Docker containers, networks, and volumes created by the example. ```bash docker compose down -v ``` -------------------------------- ### Define Table with BigInt and BigFloat Fields Source: https://github.com/uptrace/bun/blob/master/extra/bunbig/README.md Example of defining a struct with fields using bunbig.Int and bunbig.Float for arbitrary-precision numbers. Ensure these types are used where large integer or decimal values are expected. ```go type TableWithBigint struct { ID uint64 Name string Deposit *bunbig.Int Residue *bunbig.Float } ``` -------------------------------- ### Run Database Migrations with Bun Source: https://github.com/uptrace/bun/blob/master/example/migrate/README.md Execute database migrations using the `go run . db migrate` command. Set `BUNDEBUG=2` for detailed output. ```shell BUNDEBUG=2 go run . db migrate ``` -------------------------------- ### Create a SQL Migration with Bun Source: https://github.com/uptrace/bun/blob/master/example/migrate/README.md Generate a new SQL migration file using `go run . db create_sql `. Replace `` with your desired name. ```shell go run . db create_sql sql_migration_name ``` -------------------------------- ### Initialize Bun with Bunzerolog QueryHook Source: https://github.com/uptrace/bun/blob/master/extra/bunzerolog/README.md Create a new QueryHook with custom log levels and thresholds, then add it to your Bun DB instance. ```go import "github.com/rs/zerolog" db := bun.NewDB(sqldb, dialect) hook := bunzerolog.NewQueryHook( bunzerolog.WithQueryLogLevel(zerolog.DebugLevel), bunzerolog.WithSlowQueryLogLevel(zerolog.WarnLevel), bunzerolog.WithErrorQueryLogLevel(zerolog.ErrorLevel), bunzerolog.WithSlowQueryThreshold(3 * time.Second), ) db.AddQueryHook(hook) ``` -------------------------------- ### Open SQL DB with pgdriver Source: https://github.com/uptrace/bun/blob/master/driver/pgdriver/README.md Import the pgdriver and use sql.Open with the DSN to create a database connection. ```go import _ "github.com/uptrace/bun/driver/pgdriver" dsn := "postgres://postgres:@localhost:5432/test" db, err := sql.Open("pg", dsn) ``` -------------------------------- ### Create a Go Migration with Bun Source: https://github.com/uptrace/bun/blob/master/example/migrate/README.md Generate a new Go migration file using `go run . db create_go `. Replace `` with your desired name. ```shell go run . db create_go go_migration_name ``` -------------------------------- ### Initialize and Add Query Hook Source: https://github.com/uptrace/bun/blob/master/extra/bunslog/README.md Create a new QueryHook with custom log levels and thresholds, then add it to your Bun DB instance. ```go db := bun.NewDB(sqldb, dialect) hook := bunslog.NewQueryHook( bunslog.WithQueryLogLevel(slog.LevelDebug), bunslog.WithSlowQueryLogLevel(slog.LevelWarn), bunslog.WithErrorQueryLogLevel(slog.LevelError), bunslog.WithSlowQueryThreshold(3 * time.Second), ) db.AddQueryHook(hook) ``` -------------------------------- ### Integrate OpenTelemetry for Monitoring in Go Source: https://github.com/uptrace/bun/blob/master/README.md Add production-ready observability with distributed tracing by integrating the bunotel query hook. Configure the database name for tracing. ```go import "github.com/uptrace/bun/extra/bunotel" db.AddQueryHook(bunotel.NewQueryHook( bunotel.WithDBName("myapp"), )) ``` -------------------------------- ### Manage Database Schema with Bun Migrations in Go Source: https://github.com/uptrace/bun/blob/master/README.md Version your database schema using Bun's migration system. Register functions to create and drop tables, then initialize and apply migrations. ```go import "github.com/uptrace/bun/migrate" migrations := migrate.NewMigrations() migrations.MustRegister(func(ctx context.Context, db *bun.DB) error { _, err := db.NewCreateTable().Model((*User)(nil)).Exec(ctx) return err }, func(ctx context.Context, db *bun.DB) error { _, err := db.NewDropTable().Model((*User)(nil)).Exec(ctx) return err }) migrator := migrate.NewMigrator(db, migrations) err := migrator.Init(ctx) err = migrator.Up(ctx) ``` -------------------------------- ### Convert between bunbig.Int and math/big.Int Source: https://github.com/uptrace/bun/blob/master/extra/bunbig/README.md Shows how to convert a bunbig.Int to a standard math/big.Int for use with other libraries, and how to convert it back to bunbig.Int. ```go d:= bunbig.ToMathBig(x) ``` ```go x = bunbig.FromBigint(d) ``` -------------------------------- ### Import Bunzerolog Package Source: https://github.com/uptrace/bun/blob/master/extra/bunzerolog/README.md Import the bunzerolog package to use its functionalities. ```go import "github.com/uptrace/bun/extra/bunzerolog" ``` -------------------------------- ### Open SQL DB with pgdriver Connector Source: https://github.com/uptrace/bun/blob/master/driver/pgdriver/README.md Use pgdriver.NewConnector with WithDSN option to create a database connection. ```go dsn := "postgres://postgres:@localhost:5432/test" db := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn))) ``` -------------------------------- ### Run Tests with Docker Source: https://github.com/uptrace/bun/blob/master/CONTRIBUTING.md Execute tests for the project using Docker to manage PostgreSQL and MySQL servers. Navigate to the test directory and run the provided script. ```shell cd internal/dbtest ./test.sh ``` -------------------------------- ### View Database Migration Status with Bun Source: https://github.com/uptrace/bun/blob/master/example/migrate/README.md Check the current status of your database migrations with the `go run . db status` command. ```shell go run . db status ``` -------------------------------- ### Perform Mathematical Operations with Big Integers Source: https://github.com/uptrace/bun/blob/master/extra/bunbig/README.md Demonstrates basic mathematical operations like addition, subtraction, negation, multiplication, and division using bunbig.Int. Supports creating numbers from int64 and strings, and chaining operations. ```go x := bunbig.FromInt64(100) y , err := bunbig.FromString("9999999999999999999999999999999999999999") if err!=nil { panic(err) } y.Add(x) // 9999999999999999999999999999999999999999 + 100 y.Sub(x) // 9999999999999999999999999999999999999999 - 100 y.Neg() // -9999999999999999999999999999999999999999 // on the fly operation c:= bunbig.FromInt64(100).Mul(y) // 100 * 100 = 10000 c.Div(x) // 10000/100 = 100 c.Neg().Abs() // |-10000| = 10000 ``` -------------------------------- ### Complex Query with CTEs Source: https://github.com/uptrace/bun/blob/master/README.md Illustrates writing complex SQL queries using Common Table Expressions (CTEs) with Bun, including aggregation and subqueries. ```go regionalSales := db.NewSelect(). ColumnExpr("region"). ColumnExpr("SUM(amount) AS total_sales"). TableExpr("orders"). GroupExpr("region") topRegions := db.NewSelect(). ColumnExpr("region"). TableExpr("regional_sales"). Where("total_sales > (SELECT SUM(total_sales) / 10 FROM regional_sales)") var results []struct { Region string `bun:"region"` Product string `bun:"product"` ProductUnits int `bun:"product_units"` ProductSales int `bun:"product_sales"` } err := db.NewSelect(). With("regional_sales", regionalSales). With("top_regions", topRegions). ColumnExpr("region, product"). ColumnExpr("SUM(quantity) AS product_units"). ColumnExpr("SUM(amount) AS product_sales"). TableExpr("orders"). Where("region IN (SELECT region FROM top_regions)"). GroupExpr("region, product"). Scan(ctx, &results) ``` -------------------------------- ### Bun DB Command Help Source: https://github.com/uptrace/bun/blob/master/example/migrate/README.md Display help information for the Bun database commands. Use `bun db help` or `bun db -h` for specific command details. ```shell go run . db ``` ```shell NAME: bun db - database commands USAGE: bun db command [command options] [arguments...] COMMANDS: init create migration tables migrate migrate database rollback rollback the last migration group unlock unlock migrations create_go create a Go migration create_sql create a SQL migration help, h Shows a list of commands or help for one command OPTIONS: --help, -h show help (default: false) ``` -------------------------------- ### Release Script Execution Source: https://github.com/uptrace/bun/blob/master/CONTRIBUTING.md Initiate the release process by running the release script. This script updates versions in go.mod files and pushes a new branch to GitHub. Specify the desired tag. ```shell TAG=v1.0.0 ./scripts/release.sh ``` -------------------------------- ### Implement Custom Log Formatting Source: https://github.com/uptrace/bun/blob/master/extra/bunslog/README.md Define and apply a custom function to format the slog output for SQL query events. ```go customFormat := func(event *bun.QueryEvent) []slog.Attr { // your custom formatting logic here } hook := bunslog.NewQueryHook( bunslog.WithLogFormat(customFormat), // other options... ) ``` -------------------------------- ### Set Custom Zerolog Logger Instance Source: https://github.com/uptrace/bun/blob/master/extra/bunzerolog/README.md Use the WithLogger option to provide a custom zerolog.Logger instance to bunzerolog. ```go logger := zerolog.New(os.Stderr).With().Timestamp().Logger() hook := bunzerolog.NewQueryHook( bunzerolog.WithLogger(logger), // other options... ) ``` -------------------------------- ### Compare Big Integers using Cmp Source: https://github.com/uptrace/bun/blob/master/extra/bunbig/README.md Illustrates how to compare two bunbig.Int values using the Cmp method, which returns a comparison object with methods like Eq, Gt, Lt, Geq, and Leq. ```go x:= bunbig.FromInt64(100) y:= bunbig.FromInt64(90) ``` ```go cmp:=x.Cmp(y) ``` ```go // equal Eq() bool // greater than Gt() bool // lower than Lt() bool // Greater or equal Geq() bool // Lower or equal Leq() bool ``` ```go x.Cmp(y).Eq() // 100 == 90 : false x.Cmp(y).Geq() // 100 >= 90 : true x.Cmp(y).Gt() // 100 > 90 : true x.Cmp(y).Lt() // 100 < 90 : false x.Cmp(y).Leq() // 100 <= 90 : false ``` -------------------------------- ### Enable Query Logging with Debug Hook in Go Source: https://github.com/uptrace/bun/blob/master/README.md Enable verbose query logging for development by adding the bundebug query hook. This helps in understanding the SQL queries being executed. ```go import "github.com/uptrace/bun/extra/bundebug" db.AddQueryHook(bundebug.NewQueryHook( bundebug.WithVerbose(true), )) ``` -------------------------------- ### Perform Bulk Operations in Go with Bun Source: https://github.com/uptrace/bun/blob/master/README.md Efficiently handle large datasets using Bun's bulk operations for insert, update, and delete. Bulk update supports setting specific fields and conditions. ```go // Bulk insert users := []User{{Name: "John"}, {Name: "Jane"}, {Name: "Bob"}} _, err := db.NewInsert().Model(&users).Exec(ctx) ``` ```go // Bulk update with CTE _, err = db.NewUpdate(). Model(&users). Set("updated_at = NOW()"). Where("active = ?", true). Exec(ctx) ``` ```go // Bulk delete _, err = db.NewDelete(). Model((*User)(nil)). Where("created_at < ?", time.Now().AddDate(-1, 0, 0)). Exec(ctx) ``` -------------------------------- ### Debug Tests with Query Logging Source: https://github.com/uptrace/bun/blob/master/CONTRIBUTING.md Run tests while printing all executed queries for debugging purposes. Set the BUNDEBUG environment variable to 2 and specify the TZ. ```shell BUNDEBUG=2 TZ= go test -run=TestName ``` -------------------------------- ### Open SQLite Database with Shim Source: https://github.com/uptrace/bun/blob/master/driver/sqliteshim/README.md Open an in-memory SQLite database using sqliteshim. This method uses the ShimName constant to register the driver. ```go sqldb, err := sql.Open(sqliteshim.ShimName, "file::memory:?cache=shared") ``` -------------------------------- ### Scanning Query Results into Structs Source: https://github.com/uptrace/bun/blob/master/README.md Fetches data from the 'users' table and scans the results directly into a slice of User structs. ```go // Into structs var users []User db.NewSelect().Model(&users).Scan(ctx) ``` -------------------------------- ### Rollback Last Migration Group with Bun Source: https://github.com/uptrace/bun/blob/master/example/migrate/README.md Revert the last applied group of database migrations using `go run . db rollback`. ```shell go run . db rollback ``` -------------------------------- ### Disable Query Logging Source: https://github.com/uptrace/bun/blob/master/example/basic/README.md Run the application with query logging disabled by setting the BUNDEBUG environment variable to 0. ```shell BUNDEBUG=0 go run . ``` -------------------------------- ### Tagging Packages After Release Source: https://github.com/uptrace/bun/blob/master/CONTRIBUTING.md Create tags for packages after a pull request has been merged. This step is performed using the tag script and requires the release tag as an argument. ```shell TAG=v1.0.0 ./scripts/tag.sh ``` -------------------------------- ### Scanning Query Results into Individual Variables Source: https://github.com/uptrace/bun/blob/master/README.md Selects the 'id' and 'name' columns for the first row in the 'users' table and scans them into separate scalar variables. ```go // Into individual variables var id int64 var name string db.NewSelect().Table("users").Column("id", "name").Limit(1).Scan(ctx, &id, &name) ``` -------------------------------- ### Custom Log Formatting Function Source: https://github.com/uptrace/bun/blob/master/extra/bunzerolog/README.md Define a custom log format function to control how SQL query events are logged by zerolog. ```go customFormat := func(ctx context.Context, event *bun.QueryEvent, zerevent *zerolog.Event) *zerolog.Event { duration := h.now().Sub(event.StartTime) return zerevent. Err(event.Err). Str("request_id", requestid.FromContext(ctx)). Str("query", event.Query). Str("operation", event.Operation()). Str("duration", duration.String()) } hook := bunzerolog.NewQueryHook( bunzerolog.WithLogFormat(customFormat), // other options... ) ``` -------------------------------- ### Scanning Query Results into Maps Source: https://github.com/uptrace/bun/blob/master/README.md Retrieves data from the 'users' table and scans each row into a map[string]interface{}, resulting in a slice of maps. ```go // Into maps var userMaps []map[string]interface{} db.NewSelect().Table("users").Scan(ctx, &userMaps) ``` -------------------------------- ### Open SQLite Database with Driver Name Source: https://github.com/uptrace/bun/blob/master/driver/sqliteshim/README.md Conditionally open an in-memory SQLite database using sqliteshim. This method checks for driver availability using HasDriver() and then uses the DriverName() constant. ```go if sqliteshim.HasDriver() { sqldb, err := sql.Open(sqliteshim.DriverName(), "file::memory:?cache=shared") } ``` -------------------------------- ### Scanning Query Results into Scalars Source: https://github.com/uptrace/bun/blob/master/README.md Executes a query to count the number of rows in the 'users' table and scans the single scalar result into an integer variable. ```go // Into scalars var count int db.NewSelect().Table("users").ColumnExpr("COUNT(*)").Scan(ctx, &count) ``` -------------------------------- ### Set Custom slog.Logger Instance Source: https://github.com/uptrace/bun/blob/master/extra/bunslog/README.md Configure bunslog to use a specific slog.Logger instance instead of the global one. ```go logger := slog.NewLogger() hook := bunslog.NewQueryHook( bunslog.WithLogger(logger), // other options... ) ``` -------------------------------- ### Define Table Relationships with Struct Tags in Go Source: https://github.com/uptrace/bun/blob/master/README.md Use struct tags to define complex relationships like has-many, has-one, and belongs-to. Ensure join conditions are correctly specified. ```go type User struct { ID int64 `bun:",pk,autoincrement" Name string `bun:",notnull" Posts []Post `bun:"rel:has-many,join:id=user_id" Profile Profile `bun:"rel:has-one,join:id=user_id" } type Post struct { ID int64 `bun:",pk,autoincrement" Title string UserID int64 User *User `bun:"rel:belongs-to,join:user_id=id" } ``` ```go // Load users with their posts var users []User err := db.NewSelect(). Model(&users). Relation("Posts"). Scan(ctx) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.