### Install ksqlserver Adapter Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command shows how to get the `ksqlserver` adapter for KSQL, enabling connections to SQLServer databases through the `database/sql` package. ```bash go get github.com/vingarcia/ksql/adapters/ksqlserver ``` -------------------------------- ### Go KSQL Adapter Installation: ksqlserver Source: https://github.com/vingarcia/ksql/blob/master/README.md Instructions for installing the ksqlserver adapter for SQLServer, which works on top of the standard database/sql package. ```Bash go get github.com/vingarcia/ksql/adapters/ksqlserver ``` -------------------------------- ### Go KSQL Adapter Installation: ksqlite3 Source: https://github.com/vingarcia/ksql/blob/master/README.md Instructions for installing the ksqlite3 adapter for SQLite3, which relies on CGO and the mattn/go-sqlite3 driver. ```Bash go get github.com/vingarcia/ksql/adapters/ksqlite3 ``` -------------------------------- ### Run KSQL Tests Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command initiates the test suite for the KSQL project. It assumes that Docker is installed and configured correctly, and that database images have been pre-downloaded. ```bash make test ``` -------------------------------- ### Install kpgx5 Adapter Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command shows how to install the `kpgx5` adapter for KSQL, designed for PostgreSQL using `pgxpool` and `pgx` (version 5). ```bash go get github.com/vingarcia/ksql/adapters/kpgx5 ``` -------------------------------- ### KSQL Overview Example Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This Go code snippet demonstrates a basic usage of the KSQL library for interacting with SQL databases. It showcases how to initialize an adapter and perform a query, highlighting the library's simplicity. The example uses PostgreSQL-style placeholders (`$1`, `$2`, `$3`), but notes that MySQL and SQLServer use `?` and `@p1`, `@p2`, `@p3` respectively. ```Go package main import ( "context" "fmt" "log" "os" "github.com/vingarcia/ksql" "github.com/vingarcia/ksql/adapters/kpgx" ) type User struct { ID int `ksql:"id"` Name string `ksql:"name"` } func main() { ctx := context.Background() // Use DATABASE_URL from environment variables conn, err := kpgx.New(ctx, os.Getenv("DATABASE_URL"), ksql.Config{}) if err != nil { log.Fatalf("Failed to connect to database: %v", err) } defer conn.Close() // Example: Querying data into a struct var users []User query := "SELECT id, name FROM users WHERE id = $1" // Execute the query and scan results into the 'users' slice err = conn.Query(ctx, &users, query, 1) if err != nil { log.Fatalf("Failed to query users: %v", err) } // Print the fetched users for _, user := range users { fmt.Printf("User ID: %d, Name: %s\n", user.ID, user.Name) } } ``` -------------------------------- ### Go KSQL Adapter Installation: kpgx5 Source: https://github.com/vingarcia/ksql/blob/master/README.md Instructions for installing the kpgx5 adapter for PostgreSQL, which works with pgx and pgx version 5. ```Bash go get github.com/vingarcia/ksql/adapters/kpgx5 ``` -------------------------------- ### Install ksqlite3 Adapter Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command demonstrates how to install the `ksqlite3` adapter for KSQL, which works with SQLite3 databases via `database/sql` and `mattn/go-sqlite3`. Note that this adapter relies on CGO. ```bash go get github.com/vingarcia/ksql/adapters/ksqlite3 ``` -------------------------------- ### Go KSQL Adapter Installation: ksqlite Source: https://github.com/vingarcia/ksql/blob/master/README.md Instructions for installing the ksqlite adapter for SQLite, which does not require CGO and uses the modernc.org/sqlite driver. ```Bash go get github.com/vingarcia/ksql/adapters/modernc-ksqlite ``` -------------------------------- ### Go KSQL Adapter Installation: kmysql Source: https://github.com/vingarcia/ksql/blob/master/README.md Instructions for installing the kmysql adapter for MySQL, which works on top of the standard database/sql package. ```Bash go get github.com/vingarcia/ksql/adapters/kmysql ``` -------------------------------- ### Install kmysql Adapter Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command illustrates how to download the `kmysql` adapter for KSQL, which facilitates interaction with MySQL databases using the standard `database/sql` package. ```bash go get github.com/vingarcia/ksql/adapters/kmysql ``` -------------------------------- ### Install kpgx Adapter Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command demonstrates how to download the `kpgx` adapter for KSQL, which is used for interacting with PostgreSQL databases via the `pgxpool` and `pgx` (version 4) libraries. ```bash go get github.com/vingarcia/ksql/adapters/kpgx ``` -------------------------------- ### Go KSQL Adapter Installation: kpgx Source: https://github.com/vingarcia/ksql/blob/master/README.md Instructions for installing the kpgx adapter for PostgreSQL, which works with pgx and pgx version 4. ```Bash go get github.com/vingarcia/ksql/adapters/kpgx ``` -------------------------------- ### Go KSQL Example: Querying Users by Type Source: https://github.com/vingarcia/ksql/blob/master/README.md Demonstrates how to query users and group them by type, counting the number of users in each category. It uses the kpgx adapter for PostgreSQL. ```Go package main import ( "context" "errors" "fmt" "log" "github.com/vingarcia/ksql" "github.com/vingarcia/ksql/adapters/kpgx" ) var UsersTable = ksql.NewTable("users", "user_id") type User struct { ID int `ksql:"user_id" Name string `ksql:"name" Type string `ksql:"type" Posts []Post } // Post have a many to one relationship with User var PostsTable = ksql.NewTable("posts", "post_id") type Post struct { ID int `ksql:"post_id" UserID int `ksql:"user_id" Title string `ksql:"title" Text string `ksql:"text" } // Address have a one to one relationship with User var AddressesTable = ksql.NewTable("addresses", "id") type Address struct { ID int `ksql:"id" UserID int `ksql:"user_id" FullAddr string `ksql:"full_addr" } func main() { ctx := context.Background() dbURL, closeDB := startExampleDB(ctx) defer closeDB() db, err := kpgx.New(ctx, dbURL, ksql.Config{}) if err != nil { log.Fatalf("unable connect to database: %s", err) } defer db.Close() // For querying only some attributes you can // create a custom struct like this: var count []struct { Count int `ksql:"count" Type string `ksql:"type" } err = db.Query(ctx, &count, "SELECT type, count(*) as count FROM users GROUP BY type") if err != nil { log.Fatalf("unable to query users: %s", err) } fmt.Println("number of users by type:", count) // For loading entities from the database KSQL can build // the SELECT part of the query for you if you omit it like this: var adminUsers []User err = db.Query(ctx, &adminUsers, "FROM users WHERE type = $1", "admin") if err != nil { log.Fatalf("unable to query admin users: %s", err) } fmt.Println("admin users:", adminUsers) // A nice way of loading the posts of a user might be like this: var user User err = errors.Join( db.QueryOne(ctx, &user, "FROM users WHERE user_id = $1", 42), db.Query(ctx, &user.Posts, "FROM posts WHERE user_id = $1", user.ID), ) if err != nil { log.Fatalf("unable to query users: %s", err) } fmt.Println("user with posts:", user) // You can retrieve data from joined tables like this // (notice you can either use the name of the table or the alias you choose for it in the query): var rows []struct { OneUser User `tablename:"users" OneAddress Address `tablename:"addr" } err = db.Query(ctx, &rows, `FROM users JOIN addresses addr ON users.user_id = addr.user_id`, ) if err != nil { log.Fatalf("unable to query users: %s", err) } fmt.Println("rows of joined tables:", rows) } ``` -------------------------------- ### Insert Query Example (SQL) Source: https://github.com/vingarcia/ksql/blob/master/README.md An example of an SQL INSERT statement used in the benchmark tests. It inserts a 'name' and 'age' into the 'users' table and returns the generated 'id'. ```SQL INSERT INTO users (name, age) VALUES ($1, $2) RETURNING id ``` -------------------------------- ### Install modernc-ksqlite Adapter Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command shows how to download the `modernc-ksqlite` adapter for KSQL, which supports SQLite databases using `database/sql` and `modernc.org/sqlite`. This adapter does not require CGO. ```bash go get github.com/vingarcia/ksql/adapters/modernc-ksqlite ``` -------------------------------- ### Multiple Rows Query Example (SQL) Source: https://github.com/vingarcia/ksql/blob/master/README.md An example of an SQL SELECT statement used for fetching multiple rows in the benchmark tests. It retrieves 'id', 'name', and 'age' from the 'users' table, using an offset and a limit. ```SQL SELECT id, name, age FROM users OFFSET $1 LIMIT 10 ``` -------------------------------- ### Single Row Query Example (SQL) Source: https://github.com/vingarcia/ksql/blob/master/README.md An example of an SQL SELECT statement used for fetching a single row in the benchmark tests. It retrieves 'id', 'name', and 'age' from the 'users' table, using an offset. ```SQL SELECT id, name, age FROM users OFFSET $1 LIMIT 1 ``` -------------------------------- ### Example User Struct with KSQL Modifiers Source: https://github.com/vingarcia/ksql/wiki/sql.Scan,-sql.Value-and-Modifiers Illustrates a Go struct `User` with various fields tagged for KSQL interaction. It showcases the use of built-in modifiers like `json`, `timeNowUTC`, and `timeNowUTC/skipUpdates` for custom serialization and update behavior. ```Go type User struct { ID uint `ksql:"id"` Name string `ksql:"name"` Age int `ksql:"age"` Address Address `ksql:"address,json"` UpdatedAt time.Time `ksql:"updated_at,timeNowUTC"` CreatedAt time.Time `ksql:"created_at,timeNowUTC/skipUpdates"` } ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/vingarcia/ksql/blob/master/README.md The command to execute the project's test suite after setting up the Docker environment. ```Bash make test ``` -------------------------------- ### Pre-download Docker Images (Bash) Source: https://github.com/vingarcia/ksql/blob/master/README.md A make command to pre-download all necessary Docker images for running the tests. This is a one-time operation. ```Bash make pre-download-all-images ``` -------------------------------- ### Pre-download KSQL Database Images Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command downloads all necessary database images required for running the KSQL tests. It should be executed once before running the tests to avoid timeouts during the test execution. ```bash make pre-download-all-images ``` -------------------------------- ### Run Benchmark Tests (Bash) Source: https://github.com/vingarcia/ksql/blob/master/README.md This command executes the benchmark tests for the ksql project using Go's testing framework. It specifies a benchmark duration of 5 seconds. ```Bash $ make bench TIME=5s sqlc generate go test -bench=. -benchtime=5s ``` -------------------------------- ### Mocking ksql.Provider QueryOneFn Source: https://github.com/vingarcia/ksql/wiki/Testing-Tools-and-ksql.Mock Demonstrates how to instantiate ksql.Mock and mock the QueryOneFn to capture query parameters and simulate an error. ```Go var capturedRecord interface{} var capturedQuery string var capturedParams []interface{} mockDB := ksql.Mock{ QueryOneFn: func(ctx context.Context, record interface{}, query string, params ...interface{}) error { capturedRecord = record capturedQuery = query capturedParams = params // For simulating an error you would do this: return fmt.Errorf("some fake error") }, } var user User err := GetUser(db, &user, otherArgs) assert.NotNil(t, err) assert.Equal(t, user, capturedRecord) assert.Equal(t, `SELECT * FROM user WHERE other_args=$1`, capturedQuery) assert.Equal(t, []interface{}{otherArgs}, capturedParams) ``` -------------------------------- ### Go: Insert and Query User Records with ksql Source: https://github.com/vingarcia/ksql/blob/master/README.md Demonstrates inserting new user records into a 'users' table and querying them using the ksql library. It shows how to define a User struct with ksql tags and modifiers for JSON and timestamps, and how to handle database connections and errors. ```Go package main import ( "context" "fmt" "time" "github.com/vingarcia/ksql" "github.com/vingarcia/ksql/adapters/ksqlite3" "github.com/vingarcia/ksql/nullable" ) type User struct { ID int `ksql:"id" Name string `ksql:"name" Age int `ksql:"age" // The following attributes are making use of the KSQL Modifiers, // you can find more about them on our Wiki: // // - https://github.com/VinGarcia/ksql/wiki/Modifiers // // The `json` modifier will save the address as JSON in the database Address Address `ksql:"address,json" // The timeNowUTC modifier will set this field to `time.Now().UTC()` before saving it: UpdatedAt time.Time `ksql:"updated_at,timeNowUTC" // The timeNowUTC/skipUpdates modifier will set this field to `time.Now().UTC()` only // when first creating it and ignore it during updates. CreatedAt time.Time `ksql:"created_at,timeNowUTC/skipUpdates" } type PartialUpdateUser struct { ID int `ksql:"id" Name *string `ksql:"name" Age *int `ksql:"age" Address *Address `ksql:"address,json" } type Address struct { State string `json:"state" City string `json:"city" } // UsersTable informs KSQL the name of the table and that it can // use the default value for the primary key column name: "id" var UsersTable = ksql.NewTable("users") func main() { ctx := context.Background() // In this example we'll use sqlite3: db, err := ksqlite3.New(ctx, "/tmp/hello.sqlite", ksql.Config{ MaxOpenConns: 1, }) if err != nil { panic(err.Error()) } defer db.Close() // In the definition below, please note that BLOB is // the only type we can use in sqlite for storing JSON. _, err = db.Exec(ctx, `CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, age INTEGER, name TEXT, address BLOB, created_at DATETIME, updated_at DATETIME )`) if err != nil { panic(err.Error()) } var alison = User{ Name: "Alison", Age: 22, Address: Address{ State: "MG", }, } err = db.Insert(ctx, UsersTable, &alison) if err != nil { panic(err.Error()) } fmt.Println("Alison ID:", alison.ID) // Inserting inline: err = db.Insert(ctx, UsersTable, &User{ Name: "Cristina", Age: 27, Address: Address{ State: "SP", }, }) if err != nil { panic(err.Error()) } // Deleting Alison: err = db.Delete(ctx, UsersTable, alison.ID) if err != nil { panic(err.Error()) } // Retrieving Cristina, note that if you omit the SELECT part of the query // KSQL will build it for you (efficiently) based on the fields from the struct: var cris User err = db.QueryOne(ctx, &cris, "FROM users WHERE name = ? ORDER BY id", "Cristina") if err != nil { panic(err.Error()) } fmt.Printf("Cristina: %#v\n", cris) // Updating all fields from Cristina: cris.Name = "Cris" err = db.Patch(ctx, UsersTable, cris) // Changing the age of Cristina but not touching any other fields: // Partial update technique 1: err = db.Patch(ctx, UsersTable, struct { ID int `ksql:"id" Age int `ksql:"age" }{ID: cris.ID, Age: 28}) if err != nil { panic(err.Error()) } // Partial update technique 2: err = db.Patch(ctx, UsersTable, PartialUpdateUser{ ID: cris.ID, Age: nullable.Int(28), // (just a pointer to an int, if null it won't be updated) }) if err != nil { panic(err.Error()) } // Listing first 10 users from the database // (each time you run this example a new Cristina is created) // // Note: Using this function it is recommended to set a LIMIT, since // not doing so can load too many users on your computer's memory or // cause an Out Of Memory Kill. // // If you need to query very big numbers of users we recommend using // the `QueryChunks` function. var users []User err = db.Query(ctx, &users, "FROM users LIMIT 10") if err != nil { panic(err.Error()) } fmt.Printf("Users: %#v\n", users) // Making transactions: err = db.Transaction(ctx, func(db ksql.Provider) error { var cris2 User ``` -------------------------------- ### Mocking ksql.Provider QueryOneFn with Data Filling Source: https://github.com/vingarcia/ksql/wiki/Testing-Tools-and-ksql.Mock Shows how to use ksqltest.FillStructWith to populate a struct with mock data when simulating a successful query. ```Go createdAt := time.Now().Add(10*time.Hour) mockDB := ksql.Mock{ QueryOneFn: func(ctx context.Context, record interface{}, query string, params ...interface{}) error { // For simulating a succesful scenario you can just fillup the struct: return ksqltest.FillStructWith(record, map[string]interface{}{ "id": 42, "name": "fake-name", "age": 32, "created_at": createdAt, }) }, } var user User err := GetUser(db, &user, otherArgs) assert.Nil(t, err) assert.Equal(t, user, User{ ID: 42, Name: "fake-name", Age: 32, CreatedAt: createdAt, }) ``` -------------------------------- ### KSQL Benchmark Results Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md Displays the results of KSQL benchmark tests, comparing its performance against other Go database libraries like database/sql, sqlx, pgx, gorm, sqlc, and sqlboiler. The tests involve insert-one, single-row, and multiple-rows queries. ```Bash $ make bench TIME=5s ``` -------------------------------- ### Logging All KSQL Queries in Go Source: https://github.com/vingarcia/ksql/wiki/Debugging-with-`ksql.InjectLogger` Shows how to inject the built-in ksql.Logger to log all queries executed by KSQL. This includes CREATE TABLE, INSERT, and SELECT statements with their respective parameters. ```Go // After we inject a logger, all subsequent queries // will use this logger. // // You can also inject the ksql.ErrorLogger if you only // care about these logs when a query error happens. ctx = ksql.InjectLogger(ctx, ksql.Logger) // This logs: {"query":"CREATE TABLE IF NOT EXISTS users (\n\t id INTEGER PRIMARY KEY,\n\t\tage INTEGER,\n\t\tname TEXT\n\t)","params":null} _, err = db.Exec(ctx, `CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, age INTEGER, name TEXT ) `) if err != nil { panic(err.Error()) } // This logs: {"query":"INSERT INTO `users` (`name`, `age`) VALUES (?, ?)","params":["Alison",22]} var alison = User{ Name: "Alison", Age: 22, } error = db.Insert(ctx, UsersTable, &alison) if err != nil { panic(err.Error()) } // This logs: {"query":"SELECT `id`, `name`, `age` FROM users LIMIT 10","params":null} var users []User err = db.Query(ctx, &users, "FROM users LIMIT 10") if err != nil { panic(err.Error()) } ``` -------------------------------- ### Add User to Docker Group (Bash) Source: https://github.com/vingarcia/ksql/blob/master/README.md A bash command to add the current user to the 'docker' group, which is necessary for running Docker commands without sudo. ```Bash $ sudo usermod -aG docker ``` -------------------------------- ### Execute Database Query and Patch User Source: https://github.com/vingarcia/ksql/blob/master/README.md This Go code snippet demonstrates querying a user by ID and then patching their age using KSQL's database operations. It includes error handling and transaction management, with automatic rollback on errors and a panic to signal critical failures. ```Go err = db.QueryOne(ctx, &cris2, "FROM users WHERE id = ?", cris.ID) if err != nil { // This will cause an automatic rollback: return err } err = db.Patch(ctx, UsersTable, PartialUpdateUser{ ID: cris2.ID, Age: nullable.Int(29), }) if err != nil { // This will also cause an automatic rollback and then panic again // so that we don't hide the panic inside the KSQL library panic(err.Error()) } // Commits the transaction return nil }) ``` -------------------------------- ### Add User to Docker Group Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md This command adds the current user to the 'docker' group, which is necessary to run Docker commands without sudo privileges. After execution, a new login session or a system reboot is required for the changes to take effect. ```bash sudo usermod -aG docker ``` -------------------------------- ### Define KSQL Provider Interface in Go Source: https://github.com/vingarcia/ksql/blob/master/README.md Defines the public behavior of the KSQL provider, including methods for inserting, patching, deleting, querying records, and executing transactions. Functions like Insert, Patch, Delete, and QueryOne return ksql.ErrRecordNotFound if no record is found or no rows are changed. ```Go package ksql import ( "context" ) // Provider describes the KSQL public behavior // // The Insert, Patch, Delete and QueryOne functions return `ksql.ErrRecordNotFound` // if no record was found or no rows were changed during the operation. type Provider interface { Insert(ctx context.Context, table Table, record interface{}) error Patch(ctx context.Context, table Table, record interface{}) error Delete(ctx context.Context, table Table, idOrRecord interface{}) error Query(ctx context.Context, records interface{}, query string, params ...interface{}) error QueryOne(ctx context.Context, record interface{}, query string, params ...interface{}) error QueryChunks(ctx context.Context, parser ChunkParser) error Exec(ctx context.Context, query string, params ...interface{}) (Result, error) Transaction(ctx context.Context, fn func(Provider) error) error } ``` -------------------------------- ### Define KSQL Provider Interface in Go Source: https://github.com/vingarcia/ksql/blob/master/readme.template.md Defines the public behavior of the KSQL provider, including methods for inserting, patching, deleting, querying records, and executing transactions. It specifies error handling for operations that might not find records. ```Go package ksql import ( "context" ) // Provider describes the KSQL public behavior // // The Insert, Patch, Delete and QueryOne functions return `ksql.ErrRecordNotFound` // if no record was found or no rows were changed during the operation. type Provider interface { Insert(ctx context.Context, table Table, record interface{}) error Patch(ctx context.Context, table Table, record interface{}) error Delete(ctx context.Context, table Table, idOrRecord interface{}) error Query(ctx context.Context, records interface{}, query string, params ...interface{}) error QueryOne(ctx context.Context, record interface{}, query string, params ...interface{}) error QueryChunks(ctx context.Context, parser ChunkParser) error Exec(ctx context.Context, query string, params ...interface{}) (Result, error) Transaction(ctx context.Context, fn func(Provider) error) error } ``` -------------------------------- ### Injecting a Custom Logger in Go Source: https://github.com/vingarcia/ksql/wiki/Debugging-with-`ksql.InjectLogger` Demonstrates how to inject a custom logger function into the KSQL context. The logger prints the query, parameters, and any errors encountered. ```Go ctx := ksql.InjectLogger(ctx, func(ctx context.Context, values LogValues) { fmt.Println("the values are:", values.Query, values.Params, values.Err) }) ``` -------------------------------- ### Use Prepared Statements for ksql CRUD Operations Source: https://github.com/vingarcia/ksql/blob/master/README.md This optimization involves using prepared statements for the Update, Insert, and Delete helper functions within ksql. Prepared statements can improve performance by allowing the database to precompile the query plan, reducing overhead for repeated executions. ```Go // Example of using prepared statements for Update // This is a conceptual example, actual implementation would depend on the ksql library's API. // Assume 'db' is a ksql.Provider instance // Assume 'table' is a ksql.Table instance // Prepare the update statement updateStmt, err := db.Prepare("UPDATE users SET name = $1 WHERE id = $2") if err != nil { // Handle error } defer updateStmt.Close() // Execute the prepared statement _, err = updateStmt.Exec(newName, userID) if err != nil { // Handle error } ``` -------------------------------- ### Query Users in Chunks with KSQL Source: https://github.com/vingarcia/ksql/wiki/Avoiding-Code-Duplication-with-the-Select-Builder Shows how to efficiently query potentially large numbers of users in chunks using KSQL's QueryChunks function. It processes each chunk with a provided callback function and includes error handling. ```Go err = db.QueryChunks(ctx, ksql.ChunkParser{ Query: "FROM users WHERE type = ?", Params: []interface{}{usersType}, ChunkSize: 100, ForEachChunk: func(users []User) error { err := sendUsersSomewhere(users) if err != nil { // This will abort the QueryChunks loop and return this error return err } return nil }, }) if err != nil { panic(err.Error()) } ``` -------------------------------- ### Automatic SELECT Fields in KSQL Source: https://github.com/vingarcia/ksql/wiki/Home KSQL can automatically generate the SELECT ... part of a query when selecting all fields from a struct. This saves significant development time, especially when working with large structs or tables. ```Go package main import ( "fmt" "github.com/vingarcia/ksql" ) type User struct { ID int Name string Email string } func main() { // Example usage of automatic SELECT fields (assuming a ksql.DB instance is available) // db, err := ksql.Connect(...) // if err != nil { // panic(err) // } // defer db.Close() // var user User // // KSQL will infer SELECT ID, Name, Email FROM users WHERE id = ? // err = db.Get(&user, "WHERE id = ?", 1) // if err != nil { // fmt.Println("Error getting user:", err) // return // } // fmt.Printf("User: %+v\n", user) fmt.Println("Automatic SELECT fields example placeholder.") } ``` -------------------------------- ### Query Paginated Users with KSQL Source: https://github.com/vingarcia/ksql/wiki/Avoiding-Code-Duplication-with-the-Select-Builder Illustrates querying a paginated list of users based on specified criteria like type, limit, and offset using KSQL's Query function. Error handling is included. ```Go var users []User err = db.Query(ctx, &users, "FROM users WHERE type = ? ORDER BY id LIMIT ? OFFSET ?", "Cristina", limit, offset) if err != nil { panic(err.Error()) } ``` -------------------------------- ### QueryChunks Method in KSQL Source: https://github.com/vingarcia/ksql/wiki/Home The QueryChunks() method in KSQL is designed to handle situations where a single query might return more data than can fit into memory. This is useful for processing large datasets efficiently. ```Go package main import ( "fmt" "github.com/vingarcia/ksql" ) func main() { // Example usage of QueryChunks (assuming a ksql.DB instance is available) // db, err := ksql.Connect(...) // if err != nil { // panic(err) // } // defer db.Close() // query := "SELECT * FROM large_table" // chunks, err := db.QueryChunks(query) // if err != nil { // fmt.Println("Error querying chunks:", err) // return // } // for _, chunk := range chunks { // // Process each chunk of data // fmt.Printf("Processing chunk with %d rows\n", len(chunk)) // } fmt.Println("QueryChunks example placeholder.") } ``` -------------------------------- ### Query User Teams with PGX Source: https://github.com/vingarcia/ksql/wiki/PGX-Support Demonstrates how to check if a user belongs to specific teams using KSQL with PGX. It utilizes the `QueryOne` function to count matching records and handles PGX special types like `pgtype.Int8`. ```Go func checkIfUserBelongsToTeams(ctx context.Context, db ksql.Provider, userID int, teamIDs []int) { // Check if user belongs to either of the input teams: var row struct { Count pgtype.Int8 `ksql:"c"` } err := db.QueryOne(ctx, &row, `SELECT count(*) as c FROM users AS u JOIN team_members AS tm ON u.id = tm.user_id WHERE u.id = $1 AND tm.team_id = ANY($2)`, userID, []int{1, 2, 42}, // Int slices are supported by PGX ) if err != nil { log.Fatalf("unexpected error: %s", err) } fmt.Printf("Count: %+v\n", row.Count.Int) } ``` -------------------------------- ### Query Single User with KSQL Source: https://github.com/vingarcia/ksql/wiki/Avoiding-Code-Duplication-with-the-Select-Builder Demonstrates how to query a single user record from the database using KSQL's QueryOne function. It includes error handling for the database operation. ```Go var user User err = db.QueryOne(ctx, &user, "FROM users WHERE id = ?", userID) if err != nil { panic(err.Error()) } ``` -------------------------------- ### Execute ksql Query in Chunks (Go) Source: https://github.com/vingarcia/ksql/wiki/Querying-in-Chunks-for-Big-Queries Demonstrates how to use the `QueryChunks` function in Go to retrieve data from a ksql database in manageable chunks. This is useful for handling large datasets that might exceed memory capacity. The function takes a `ChunkParser` struct which includes the SQL query, parameters, chunk size, and a callback function to process each chunk. ```Go err = db.QueryChunks(ctx, ksql.ChunkParser{ Query: "SELECT * FROM users WHERE type = ?", Params: []interface{}{usersType}, ChunkSize: 100, ForEachChunk: func(users []User) error { err := sendUsersSomewhere(users) if err != nil { // This will abort the QueryChunks loop and return this error return err } return nil }, }) if err != nil { panic(err.Error()) } ``` -------------------------------- ### Nested Structs for JOINs in KSQL Source: https://github.com/vingarcia/ksql/wiki/Home KSQL's Nested Structs feature facilitates the reuse of existing structs or models when working with JOIN operations. This simplifies data retrieval and mapping for complex queries involving multiple tables. ```Go package main import ( "fmt" "github.com/vingarcia/ksql" ) type Address struct { Street string City string } type UserWithAddress struct { User User // Embed User struct Address Address // Embed Address struct } func main() { // Example usage of Nested Structs (assuming a ksql.DB instance is available) // db, err := ksql.Connect(...) // if err != nil { // panic(err) // } // defer db.Close() // var userData UserWithAddress // // KSQL will map JOIN results to nested structs // err = db.Get(&userData, "FROM users JOIN addresses ON users.id = addresses.user_id WHERE users.id = ?", 1) // if err != nil { // fmt.Println("Error getting user with address:", err) // return // } // fmt.Printf("User: %+v\n", userData.User) // fmt.Printf("Address: %+v\n", userData.Address) fmt.Println("Nested Structs example placeholder.") } ``` -------------------------------- ### Query Joined Rows in Chunks with `tablename` Tags Source: https://github.com/vingarcia/ksql/wiki/Reusing-Existing-Structs-on-Queries-with-JOINs Shows how to process potentially large datasets from joined tables efficiently using `QueryChunks`. This method iterates over data in manageable chunks, applying a provided callback function for each chunk, and utilizes `tablename` tags for struct mapping. ```Go err = db.QueryChunks(ctx, ksql.ChunkParser{ Query: "FROM users as u JOIN posts as p ON u.id = p.user_id WHERE type = ?", Params: []interface{}{usersType}, ChunkSize: 100, ForEachChunk: func(rows []struct{ User User `tablename:"u"` Post Post `tablename:"p"` }) error { err := sendRowsSomewhere(rows) if err != nil { // This will abort the QueryChunks loop and return this error return err } return nil }, }) if err != nil { panic(err.Error()) } ``` -------------------------------- ### Register KSQL Attribute Modifier in Go Source: https://github.com/vingarcia/ksql/wiki/sql.Scan,-sql.Value-and-Modifiers Demonstrates how to register a new attribute modifier in KSQL using Go. The `init()` function is used to call `ksqlmodifiers.RegisterAttrModifier` with a custom modifier name and configuration, including `SkipInserts`, `SkipUpdates`, and `Scan` and `Value` functions for custom data handling. ```Go func init() { ksqlmodifiers.RegisterAttrModifier("my_modifier_name", ksqlmodifiers.AttrModifier{ // Set SkipInserts to true if you want this modifier to // cause the field to be ignored on inserts. SkipInserts: false, // Set SkipUpdates to true if you want this modifier to // cause the field to be ignored on updates. SkipUpdates: false, Scan: func(ctx context.Context, opInfo ksqlmodifiers.OpInfo, attrPtr interface{}, dbValue interface{}) error { // Read the dbValue, modify it and then save it // into the attrPtr argument using reflection if necessary. }, Value: func(ctx context.Context, opInfo ksqlmodifiers.OpInfo, inputValue interface{}) (outputValue interface{}, _ error) { // Read the inputValue, modify it and then // return it so the database can save it. }, }) } ``` -------------------------------- ### Query Page of Joined Rows with `tablename` Tags Source: https://github.com/vingarcia/ksql/wiki/Reusing-Existing-Structs-on-Queries-with-JOINs Illustrates querying a paginated list of rows from joined tables. It uses anonymous structs with `tablename` tags to define the structure of the joined data, enabling efficient retrieval of multiple records. ```Go var rows []struct{ User User `tablename:"u"` Post Post `tablename:"p"` } err = db.Query(ctx, &rows, "FROM users as u JOIN posts as p ON u.id = p.user_id WHERE name = ? LIMIT ? OFFSET ?", "Cristina", limit, offset, ) if err != nil { panic(err.Error()) } ``` -------------------------------- ### Query Specific Columns from Joined Tables (No `tablename` Tags) Source: https://github.com/vingarcia/ksql/wiki/Reusing-Existing-Structs-on-Queries-with-JOINs Demonstrates an alternative approach for querying joined tables when only specific columns are needed. This method avoids using `tablename` tags and explicitly defines the SELECT clause, which can be more efficient for targeted data retrieval. ```Go var rows []struct{ UserName string `ksql:"name"` PostTitle string `ksql:"title"` } err := db.Query(ctx, &rows, "SELECT u.name, p.title FROM users u JOIN posts p ON u.id = p.user_id LIMIT 10") if err != nil { panic(err.Error()) } ``` -------------------------------- ### Define KSQL Modifier Tag Source: https://github.com/vingarcia/ksql/wiki/sql.Scan,-sql.Value-and-Modifiers Demonstrates how to apply KSQL modifiers to struct attributes using the `ksql` tag. The modifier name is appended after a comma to the column name. ```Go `ksql:"column_name,json"` ``` -------------------------------- ### Query Single Joined Row with `tablename` Tags Source: https://github.com/vingarcia/ksql/wiki/Reusing-Existing-Structs-on-Queries-with-JOINs Demonstrates how to query a single row from joined tables using anonymous structs with `tablename` tags to map aliased table columns to struct fields. This method allows reusing existing struct definitions for joined data. ```Go var row struct{ User User `tablename:"u"` // (here the tablename must match the aliased tablename in the query) Post Post `tablename:"posts"` // (if no alias is used you should use the actual name of the table) } err = db.QueryOne(ctx, &row, "FROM users as u JOIN posts ON u.id = posts.user_id WHERE u.id = ?", userID) if err != nil { panic(err.Error()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.