Improve pgxsupport example

pull/42/head
Vinícius Garcia 2023-07-02 22:16:17 -03:00
parent e9cf2c5f32
commit c810da865e
1 changed files with 13 additions and 14 deletions

View File

@ -6,6 +6,7 @@ import (
"log" "log"
"os" "os"
"github.com/jackc/pgtype"
"github.com/vingarcia/ksql" "github.com/vingarcia/ksql"
"github.com/vingarcia/ksql/adapters/kpgx" "github.com/vingarcia/ksql/adapters/kpgx"
) )
@ -84,29 +85,27 @@ func main() {
panic(err.Error()) panic(err.Error())
} }
userID := u.ID checkIfUserBelongsToTeams(ctx, db, u.ID, []int{1, 2, 42})
}
// The example below illustrates how it is possible to use pgx func checkIfUserBelongsToTeams(ctx context.Context, db ksql.Provider, userID int, teamIDs []int) {
// special support to slices Inside a query: // Check if user belongs to either of the input teams:
var row struct {
// Find user iff user belongs to either team on the input list: Count pgtype.Int8 `ksql:"c"`
var user User }
err = db.QueryOne(ctx, &user, err := db.QueryOne(ctx, &row,
`SELECT u.* `SELECT count(*) as c
FROM users AS u FROM users AS u
JOIN team_members AS tm JOIN team_members AS tm
ON u.id = tm.user_id ON u.id = tm.user_id
WHERE u.id = $1 WHERE u.id = $1
AND tm.team_id = ANY($2)`, AND tm.team_id = ANY($2)`,
userID, userID,
[]int{1, 2, 42}, []int{1, 2, 42}, // Int slices are supported by PGX
) )
if err == ksql.ErrRecordNotFound { if err != nil {
fmt.Println("Input user does not exist or does not belong to any of the provided teams")
return
} else if err != nil {
log.Fatalf("unexpected error: %s", err) log.Fatalf("unexpected error: %s", err)
} }
fmt.Printf("Found user: %+v\n", user) fmt.Printf("Count: %+v\n", row.Count.Int)
} }