Using Oracle’s official MySQL with the Perfect framework, on macOS

By now, I’m sure there’s very few people in the Cocoa community that haven’t at least dipped a toe into the warm pool of goodness that is Swift. Apple’s (now, not so) new language is not only just that — a really great, extremely flexible and safe language — for all Apple platforms but also a very competitive option for server-side development.

I’ve been intrigued by the possibilities of Swift on the server since it was announced and been an enthusiastic user of the Perfect framework since it came out. Currently, I’ve been using Perfect for the upcoming version 2.0 of the API for a custom LMS system deployed in SFU university in Vancouver, BC.

Perfect’s MySQL database connector works out of the box for Linux and on macOS using the Homebrew version of MySQL.

It’s a little more involved to get a Perfect Xcode project to build using the standard Oracle MySQL distro on macOS. I couldn’t find detailed instructions on it so here’s a step-by-step guide on what needs to be done to make it happen.

1. Add the MySQL dependency to ‘package.swift’

Package(url:”https://github.com/PerfectlySoft/Perfect-MySQL.git", majorVersion: 2, minor: 0)

2. In Packages -> MySQL-<version> create a folder ‘mysqlclient

Inside it, add a module.modulemap file with the following contents:

module mysqlclient [system] {
header “/usr/local/mysql/include/mysql.h”
link “mysqlclient”
export *
}

What we’re doing here is creating a module that gives us access to libmysql.

Read here for a more detailed discussion.

3. Generate an Xcode project to build Perfect-MySQL

From a terminal, cd to the folder for Perfect-MySQL and run:

swift package generate-xcodeproject

4. Modify build settings for Perfect-MySQL

Add the following settings:

Library Search Paths -> add: /usr/local/mysql/lib

Import Paths -> add: path->to->module.modulemap (step 2)

5. Add the Perfect-MySQL Xcode project as a dependeny in your Perfect project

Then add the following setting to the build settings of your main Perfect project:

Library Search Paths -> add: /usr/local/mysql/lib

Don’t forget to add the MySQL target dependecy and add it to your linked libraries, in the build phases section.

That’s it. Build and run your Perfect project.

One final note. Perfect mentions the need to edit the mysqlclient.pc file on macOS. I didn’t have to do this on my Mac using Oracle’s MySQL distro. Conversely, I needed to make these changes on Ubuntu 16.10.

I’m taking the opportunity to thank the people behind Perfect for providing such a great tool to the community and strongly urge Swift developers to give it a try.