Now is the time to implement your first PostgreSQL repository. We will start with a repository based on the classic
database/sql package. In the
website package, create a new file
repository_postgresql_classic.go and copy the code of the repository structure
PostgreSQLClassicRepository with its constructor and the
You may wonder why we named the file
repository_postgresql_classic.gowhen inside we have a
PostgreSQLClassicRepositorystruct. Why is the name not
postgresql_classic_repository.go? Well, this way of naming helps in locating repository files in the IDE more easily. Take a look at the project tree:
postgresql-intro ├── app ├── cmd ├── go.mod └── website ├── repository.go ├── repository_postgresql_classic.go └── website.go
The files are sorted by name, so the
repository_postgresql_classic.gois next to the
repository.gofile, and so all other future repository variants will be next to each other thanks to this naming style.
Locating specific files in a package can be difficult when the package contains a lot of files, so it is a good idea to take care of the naming convention that will help with this from the beginning of the project.
In the next parts, we will be using the
pgx driver objects, so we need to add this package to the project.
go get command in our project directory:
go get github.com/jackc/pgx/v4
go get github.com/jackc/pgconn
to get the low-level package internally used by the
Now you are ready to understand what we just added and develop the project further.
The repository constructor
8-16, we define the
PostgreSQLClassicRepository struct and its
NewPostgreSQLClassicRepository() constructor. It accepts only one dependency as an argument:
sql.DB, which represents the database connection pool for all drivers compatible with the
database/sql interface. Using
sql.DB, we will perform direct database operations in the repository methods.
As we already mentioned, the
Migrate() function in our project is used to create a schema for the
websites table where we will store our data. Using the
DB.ExecContext() method, we execute a SQL query that creates the table. Note that we use here a variant with passing the
context.Context (there is also an analogous
DB.Exec() function that omits the context), which will allow us to stop the execution of the query, for example, in case of a timeout.