Setup Postgres with Vapor 2.0

Ankit
Radar
Published in
2 min readMay 22, 2017
Image credit: Zachary Young

This post assumes that you have Postgres installed on your machine and you have created a database.

Step 1

Create a new vapor project and generate an xcode project.

vapor new dbsetup
vapor xcode

Step 2

Add postgresql-provider repo to dependencies array in Package.swift file.

Package(url: "https://github.com/vapor/postgresql-provider.git", majorVersion: 2, minor: 0)

Step 3

Open Config/fluent.json and replace all the existing code with the code snippet below.

{
"driver": "postgresql"
}

Step 4

Create a new file at Config/secrets/postgresql.json with the following json. Don’t forget to update your username and database name.

{
"hostname": "127.0.0.1",
"user": "$PUT_USERNAME_HERE",
"password": "",
"database": "$PUT_DBNAME_HERE",
"port": 5432
}

Step 5

In App/Config+Setup.swift file import PostgreSQLProvider and add the following line to the setupProviders function:

try addProvider(PostgreSQLProvider.Provider.self)

Step 6

Let’s verify that everything is working. Run the following command to update xcode project:

vapor xcode

Select the “Run” scheme and target “My Mac” and run the project.

The project should build and run and the console logs “Database prepared”. You can use psql to inspect that the post table is created.

If you face any issues, try using the sample project here:

https://github.com/ankit1ank/VaporPostgresSample

We hope you find this helpful. Give it a 💚 and share your thoughts on the comments section — we are always up for a good conversation! To read more articles, just hit that “follow” button.

--

--