Cookies management by TermsFeed Cookie Consent

Run the demo procedure for GORM repository

20/21

To run our demo procedure for the GORM repository, create a new gorm directory in cmd and put a new main.go file in it. Then copy the code there, most of which you should already know well.

In the main() function, we do almost the same as in the previous applications: open the connection to the DB, create the repository, and run the demo procedure. The main difference is in the initialization of the database connection. GORM has a function gorm.Open() which opens the DB using a set SQL dialect. In our case, we want to use the PostgreSQL dialect, so we create it using the GORM’s PostgreSQL driver function postgres.Open() with the same connection string as in the previous apps. The postgres driver is a separate package, and be sure to add it to our project:

go get gorm.io/driver/postgres

In the main(), we open the connection in the simplest way, but GORM has a lot of configuration options. You can read about them here.

Then, we create a new GORM Website repository (PostgreSQLGORMRepository) and run our demo procedure. The output should be the same as for the previous apps.

Remember that our previous applications have 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.

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}

As always, we encourage you to experiment, change the code, see what comes out, get errors and find their solution.

cmd/gorm/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"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

func main() {
    gormDB, err := gorm.Open(postgres.Open("postgres://postgres:mysecretpassword@localhost:5432/website"))
    if err != nil {
        log.Fatal(err)
    }

    websiteRepository := website.NewPostgreSQLGORMRepository(gormDB)

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

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