Cookies management by TermsFeed Cookie Consent

Run the demo procedure for pgx-based repository

18/21

To run our demo procedure with the created pgx client-based repository, we need to make a new app. Create a new pgx directory in the cmd and add a new main.go file.

As you can see in the code, the main.go file, in this case, is also very similar to the version with the classic repository. The difference is the initialization of the pgxpool.Pool instead of the sql.DB, but note that we are using the same connection string as before and also have to take care of closing the connection at the end. Also, in imports section, you does not have to import the database/sql compatible driver. The rest of the code is analogous to the classic version.

Remember that our previous application has already inserted data into the websites table. So to clean the database, just close the running PostgreSQL Docker container and restart it using docker run as in the beginning.

If you run the cmd/pgx/main.go, you will see the same output as for the cmd/classic/main.go:

1. MIGRATE REPOSITORY
2. CREATE RECORDS OF REPOSITORY
&{ID:1 Name:GOSAMPLES URL:https://gosamples.dev Rank:2}
&{ID:2 Name:Golang official website URL:https://golang.org Rank:1}
3. GET RECORD BY NAME
&{ID:1 Name:GOSAMPLES URL:https://gosamples.dev Rank:2}
4. UPDATE RECORD
5. GET ALL
{ID:2 Name:Golang official website URL:https://golang.org Rank:1}
{ID:1 Name:GOSAMPLES URL:https://gosamples.dev Rank:1}
6. DELETE RECORD
7. GET ALL
{ID:1 Name:GOSAMPLES URL:https://gosamples.dev Rank:1}

cmd/pgx/main.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
    "context"
    "log"
    "postgresql-intro/app"
    "postgresql-intro/website"
    "time"

    "github.com/jackc/pgx/v4/pgxpool"
)

func main() {
    dbpool, err := pgxpool.Connect(context.Background(), "postgres://postgres:mysecretpassword@localhost:5432/website")
    if err != nil {
        log.Fatal(err)
    }
    defer dbpool.Close()

    websiteRepository := website.NewPostgreSQLPGXRepository(dbpool)

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    app.RunRepositoryDemo(ctx, websiteRepository)
}
18/21