Up and Running with Server Side Swift: Part 3 — postgrSQL and StORM
Ive wanted a basic, browser based todo list for a while. Something free of any distractions. Building this with Swift, and getting to know some of the libraries involved seemed like a great place to start.
This is a 4 part series outlining how to set up the project, getting started with routing, setting up the database and finally creating the model and controllers of our application. To see part 1 click here.
Introduction
Our application will use a postgrSQL database, and a library called StORM to access it. Below, we’ll set up the database and the user the application will use to access it.
Installing postgrSQL
first, update brew.
brew update
Then install libxml2 as its a dependency for Perfect.
brew install libxml2
Next, install postgres.
brew install postgres
Ok, so now we need to start postgresql server, so that you can create databases, users etc.
brew services start postgresql
If theres an issue you can replace start
here with restart
or stop
.
Our application will need a user to access the database. So lets create one.
createuser -D -P todolist
Above we see the command to create a user. -D
means that they cannot create databases. -P
means that they requite a password. Finally, todolist
is the name of the user. This can be anything you want. Once you hit enter on the above command, you’ll be asked to enter a password and password confirmation. This is the password for the user todolist_password
Next, lets create a database for the todolist
users to access.
createdb -O todolist todolist_database
We have the command to create a database above, assigned the user todolist
as the databases owner, -O
and given the database a name, todolist_database
.
Finally, lets access the database as the todolist
user.
psql -d todolist_database -U todolist
If you want to quit, just type /q
and hit enter.
StORM
Lets add StORM as a dependancy to access our DB. Update package.swift
with the following dependancy.
.package(url: "https://github.com/SwiftORM/Postgres-StORM.git", from: "3.0.0")
and dont forget to add PostgresStORM
as a target dependancy. Run swift package update
and swift package generate-xcodeproj
back in our terminal and we should be ready to add import PostgresStORM
into our Main.swift
.
Next up…
Now that we have the database setup, the next part will tackle some basic database actions and will set up routes to perform these actions via a webpage. We’ll also create a model for our database object that our application can interact with. Click this link to see more.