Tutorial: How to use PostgreSQL

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 using services 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 use in 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 postgresql list databases: \l
within postgresql 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

Before we generate an Xcode project we will have to replace FluentSQLite by FluentPostgreSQL and adjust the target as well as we will change the package name within Package.swift:

// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "projectName", // changed
dependencies: [
// πŸ’§ A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.0-rc"),
.package(url: "https://github.com/vapor/leaf.git", from: "3.0.0-rc"),
.package(url: "https://github.com/vapor/fluent-postgresql.git", from: "1.0.0-rc") // changed
],
targets: [
.target(name: "App", dependencies: ["Vapor", "Leaf", "FluentPostgreSQL"]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App"]),
]
)

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
β”‚ β”‚ β”œβ”€β”€ boot.swift
β”‚ β”‚ β”œβ”€β”€ configure.swift
β”‚ β”‚ └── routes.swift
β”‚ └── Run/
β”‚ └── main.swift
β”œβ”€β”€ Tests/
β”œβ”€β”€ Resources/
β”œβ”€β”€ Public/
β”œβ”€β”€ Dependencies/
└── Products/

Before we can run our project we’ll have to configure PostgreSQL. Let’s go πŸš€


4. Configure your project to use PostgreSQL

Our first step is to change everything FluentSQLite related to our new FluentPostgreSQL and register the database information within our configure.swift:

import Vapor
import Leaf
import FluentPostgreSQL // added
public func configure(
_ config: inout Config,
_ env: inout Environment,
_ services: inout Services
) throws {
  // Register routes to the router
let router = EngineRouter.default()
try routes(router)
services.register(router, as: Router.self)
  let myService = EngineServerConfig.default(port: 8004)
services.register(myService)
  try services.register(LeafProvider())
try services.register(FluentPostgreSQLProvider()) // changed
  config.prefer(LeafRenderer.self, for: TemplateRenderer.self)
  let postgresqlConfig = PostgreSQLDatabaseConfig(
hostname: "127.0.0.1",
port: 3306,
username: "root",
password: "root",
database: "mycooldb"
)
services.register(postgresqlConfig)
  var migrations = MigrationConfig()
migrations.add(model: User.self, database: .psql) // changed
services.register(migrations)
}

The second step before we can run our project is to adjust our User model in User.swift:

import FluentPostgreSQL  // changed
import Vapor
final class User: PostgreSQLModel {
var id: Int?
var username: String
init(id: Int? = nil, username: String) {
self.id = id
self.username = username
}
}
extension User: Content {}
extension User: Migration {}

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

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

And that’s it! You successfully configured your project to use postgresql πŸŽ‰πŸš€


I am really happy you read my article! If you have any suggestions or improvements of any kind let me know! I’d love to hear from you! 😊

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.