Run the demo procedure for GORM repository
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 usingdocker 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
|
|