Tutorial: How to use PostgreSQL

Martin Lasek
Jan 6, 2018 Β· 4 min read
Image for post
Image for post

In this tutorial you’ll learn how to use PostgreSQL with your project ✨ πŸš€ 😊

You can find the result of this tutorial on github here

This tutorial is a natural follow-up of How to write Controllers. You can either go for that tutorial first and come back later or be a rebel, skip it and read on 😊

Index

1. Install Homebrew
2. Install PostgreSQL
3. Create and generate a new project
4. Configure your project to use PostgreSQL

1. Install Homebrew

If you don’t have it yet I highly recommend to get it. It makes it super easy for you to install dependencies like PostgreSQL. To install Homebrew execute the following in your terminal:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

We will also install brew services. It will make it incredibly easy to start the PostgreSQL server and let it start alongside with your mac! It’s awesome ✨!

brew tap homebrew/services

Now whenever you want to know what services are running just execute:

brew services list

2. Install PostgreSQL

Installing PostgreSQL with Homebrew is so easy, what am I even here for πŸ˜„?

brew install postgresql

That’s it. Done. Now to init postgresql just execute the following command:

initdb /usr/local/var/postgres

Next start postgresql with:

brew services start postgresql

See how easy brew services makes it? postgresql now starts alongside your mac!

Now let’s create a database that we want to be used by our project. To create a new database we stay in our terminal and just execute:

createdb mycooldb;

Terminal Cheatsheet:

connect to mycooldb database: psql mycooldb
within server list databases: \l
within server to exit server: \q

Alrighty! You are ready for step 3. Create and generate a new project 😊

3. Create and generate a new project

We will use the outcome of the tutorial mentioned in the beginning as a template to create our new project:

vapor new projectName --template=vaporberlin/my-first-controller --branch=vapor-2

Before we generate an Xcode project we would have to change the package name within Package.swift:

// swift-tools-version:4.0import PackageDescriptionlet package = Package(
name: "projectName", // changed
products: [
.library(name: "App", targets: ["App"]),
.executable(name: "Run", targets: ["Run"])
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.1.0")),
.package(url: "https://github.com/vapor/leaf-provider.git", .upToNextMajor(from: "1.1.0")),
.package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.3.0")),
.package(url: "https://github.com/vapor-community/postgresql-provider.git", .upToNextMajor(from: "2.1.0")) // added
],
targets: [
.target(name: "App", dependencies: ["Vapor", "LeafProvider", "FluentProvider", "PostgreSQLProvider"],
exclude: [
"Config",
"Public",
"Resources",
]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App", "Testing"])
]
)

Now in the terminal at the root directory projectName/ execute:

vapor update -y

It may take a bit fetching the dependency, but when done you should have a project structure like this:

projectName/
β”œβ”€β”€ Package.swift
β”œβ”€β”€ Sources/
β”‚ β”œβ”€β”€ App/
β”‚ β”‚ β”œβ”€β”€ Controllers/
β”‚ β”‚ β”‚ └── UserController.swift
β”‚ β”‚ β”œβ”€β”€ Models/
β”‚ β”‚ β”‚ └── User.swift
β”‚ β”‚ β”œβ”€β”€ Routes/
β”‚ β”‚ β”‚ └── Routes.swift
β”‚ β”‚ └── Setup/
β”‚ β”‚ β”œβ”€β”€ Config+Setup.swift
β”‚ β”‚ └── Droplet+Setup.swift
β”‚ └── Run/
β”œβ”€β”€ Tests/
β”œβ”€β”€ Config/
β”œβ”€β”€ Resources/
β”œβ”€β”€ Public/
β”œβ”€β”€ Dependencies/
└── Products/

If you now cmd+r or run we should be able to access the /user route 😊!

Image for post
Image for post
Note: make sure to select Run as a scheme next to your button before running the app

4. Configure your project to use PostgreSQL

Now all we need is a configuration file that holds our database information. Create a new Folder within Config/ and name it secrets/ so all our sensitive configuration files won’t be tracked by git.

Within Config/secrets/ create a file and name it postgresql.json and insert the following configuration:

{
"hostname": "127.0.0.1",
"user": "martinlasek", // use your own mac user
"password": "",
"database": "mycooldb",
"port": 5432
}

NOTE: To find out your mac user execute the following in terminal: whoami

Then we will tell fluent to use postgresql as a driver. In Config/fluent.json:

{
...
"driver": "postgresql", ...
}

Lastly we’ll add the PostgreSQLProvider within Setup/Config+Setup.swift:

import LeafProvider
import FluentProvider
import PostgreSQLProvider // added
extension Config {
public func setup() throws {
try setupProviders()
try setupPreparations()
}
private func setupProviders() throws {
try addProvider(LeafProvider.Provider.self)
try addProvider(FluentProvider.Provider.self)
try addProvider(PostgreSQLProvider.Provider.self) // added
}
private func setupPreparations() throws {
preparations.append(User.self)
}
}

Our final cmd+r or run and refresh of /user and that’s it! You successfully configured your project to use a postgresql database πŸŽ‰ πŸš€ πŸŽ‰

Thank you a lot for reading! If you have any questions or improvements β€” write a comment! I would love to hear from you! 😊

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium β€” and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store