Tutorial: How to use MySQL
In this tutorial youβll learn how to install and use MySQL 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 MySQL
3. Create and generate a new project
4. Configure your project to use MySQL
5. Where to go from here
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 MySQL. 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 MySQL server and let it start alongside with your mac! Thatβs awesome β¨!
brew tap homebrew/services
Now whenever you want to know what services are running just execute:
brew services list
2. Install MySQL
Installing MySQL with Homebrew is so easy, what am I even here for π?
brew install mysql@5.7
Weβre installing version 5.7 because only saying
brew install mysql
installs most likely version 10 which wonβt βjust workβ out of the box right now.
Thatβs it. Now to start mysql just execute the following command:
brew services start mysql
See how easy brew services makes it? mysql now starts alongside your mac!
We will now set a password for the root user by simply executing:
mysql_secure_installation
Itβs a weird command but go for it and answer as the following:
- VALIDATE PASSWORD PLUGIN: no
- When asked for a password I used: root (use whatever feels save π)
- Remove anonymous user: yes
- Disallow root login from remote: yes
- Remove the test database: yes
- Reload privilege tables now: yes
Thatβs it for the installation!
Now letβs create a database that we want to be used by our project. To create a new database we will need to login into our mysql server with:
mysql -uroot -proot
NOTE: -u stands for user and -p for password. I know, captain obvious π¨πΌβπ
Now that we are within our mysql server create a database with:
CREATE DATABASE `mycooldb` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
You could have created a database also by just typing:
CREATE DATABASE `mycooldb`;
But we use the command with utf8 in it. Itβs considered best practice π€
Terminal Cheatsheet:
connect to mysql server: mysql -uroot -proot
within server list databases: SHOW DATABASES;
within server to exit server: exit
Finally youβd have to install cmysql which is needed for the MySQLProvider:
brew install vapor/tap/cmysql
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 FluentMySQL and adjust the target as well as we will change the package name within Package.swift:
// swift-tools-version:4.0
import PackageDescriptionlet package = Package(
name: "projectName", // changed
dependencies: [
// π§ A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"),
.package(url: "https://github.com/vapor/leaf.git", from: "3.0.0-rc"),
.package(url: "https://github.com/vapor/fluent-mysql.git", from: "3.0.0-rc") // changed
],
targets: [
.target(name: "App", dependencies: ["Vapor", "Leaf", "FluentMySQL"]),
.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
β β βββ app.swift
β β βββ boot.swift
β β βββ configure.swift
β β βββ routes.swift
β βββ Run/
β βββ main.swift
βββ Tests/
βββ Resources/
βββ Public/
βββ Dependencies/
βββ Products/
Before we can run our project we will have to configure MySQL β letβs go π
4. Configure your project to use MySQL
Our first step is to change everything FluentSQLite related to FluentMySQL and register the database information within our configure.swift:
import Vapor
import Leaf
import FluentMySQL // addedpublic 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 leafProvider = LeafProvider()
try services.register(leafProvider)
config.prefer(LeafRenderer.self, for: ViewRenderer.self) try services.register(FluentMySQLProvider()) // changed let mysqlConfig = MySQLDatabaseConfig(
hostname: "127.0.0.1",
port: 3306,
username: "root",
password: "root",
database: "mycooldb"
)
services.register(mysqlConfig) var migrations = MigrationConfig()
migrations.add(model: User.self, database: .mysql) // changed
services.register(migrations)
}
The second step before we can run our project is to adjust our User model in User.swift:
import FluentMySQL // changed
import Vaporfinal class User: MySQLModel {
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 π!
And thatβs it! You successfully configured your project to use mysql π π π
5. Where to go from here
You can find a list of all tutorials with example projects on Github here:
ππ» https://github.com/vaporberlin/vaporschool