Skip to content

Commit

Permalink
Added more about pgx in golang
Browse files Browse the repository at this point in the history
  • Loading branch information
k8s4 committed Nov 3, 2024
1 parent 020b3b7 commit 08a91cc
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 3 deletions.
72 changes: 70 additions & 2 deletions examples/golang/cource/06g_databases/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (
"context"
"os"
"github.com/jackc/pgx/v4"
// "github.com/jackc/pgx/v4/pgxpool"
// "github.com/georgysavva/scany/pgxscan"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/georgysavva/scany/pgxscan"
)

func PostgresSimpleQuery() (name string, position string) {
Expand All @@ -30,6 +30,74 @@ func PostgresSimpleQuery() (name string, position string) {
return name, position
}

func PostgresScanToObject() {
ctx := context.Background()
db, err := pgxpool.Connect(ctx, "postgres://postgres:some@localhost:5432/postgres")
if err != nil {
fmt.Fprintf(os.Stderr, "Can't connect to db: %v\n", err)
os.Exit(1)
}

type User struct {
Name string
Rank string
Id int
}
defer db.Close()

var users []User
pgxscan.Select(ctx, db, &users, "select * from users")
fmt.Println(users)

var user User
pgxscan.Get(ctx, db, &user, "select * from users where id=$1", 2)
fmt.Println(user)
}

func PostgresJoinQuery() {
ctx := context.Background()
db, err := pgxpool.Connect(ctx, "postgres://postgres:some@localhost:5432/postgres")
if err != nil {
fmt.Fprintf(os.Stderr, "Can't connect to db: %v\n", err)
os.Exit(1)
}
defer db.Close()

query := "SELECT users.name, users.rank, cr.brand, cr.colour, cr.license_plate "+
"FROM users "+
"JOIN cars cr ON users.id = cr.user_id "+
"WHERE users.rank = $1"

type UserCar struct {
Name string
Rank string
Brand string
Colour string
LicensePlate string
}
var carBounds []UserCar

pgxscan.Select(ctx, db, &carBounds, query, "Manager")
fmt.Println(carBounds)
}

func PostgresAddCar(userId int, colour string, brand string, licensePlate string) {
ctx := context.Background()
conn, err := pgx.Connect(ctx, "postgres://postgres:some@localhost:5432/postgres")
if err != nil {
fmt.Fprintf(os.Stderr, "Can't connect to db: %v\n", err)
os.Exit(1)
}
defer conn.Close(ctx)

_, err = conn.Exec(ctx, "INSERT INTO cars(user_id, colour, brand, license_plate) "+
"VALUES ($1,$2,$3,$4)", userId, colour, brand, licensePlate)
fmt.Println(err)
}

func main() {
fmt.Println(PostgresSimpleQuery())
PostgresScanToObject()
PostgresJoinQuery()
// PostgresAddCar(1,"SomeShit","Kaiyi","A666G4")
}
2 changes: 1 addition & 1 deletion examples/golang/cource/06g_databases/postgres.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ CREATE TABLE users (
rank VARCHAR(255)
);

CREATE UNIQUE INDEX users_id_uindex ON cars(id);
CREATE UNIQUE INDEX users_id_uindex ON users(id);

CREATE TABLE cars (
id SERIAL PRIMARY KEY,
Expand Down

0 comments on commit 08a91cc

Please sign in to comment.