Fluent SQLite

Fluent SQLite (vapor/fluent-sqlite) is a type-safe, fast, and easy-to-use ORM for SQLite built on top of Fluent.

!!! seealso The Fluent SQLite package is built on top of Fluent and the pure Swift, NIO-based SQLite core. You should refer to their guides for more information about subjects not covered here.

Getting Started

This section will show you how to add Fluent SQLite to your project and create your first SQLiteModel.

Package

The first step to using Fluent SQLite is adding it as a dependency to your project in your SPM package manifest file.

  1. // swift-tools-version:4.0
  2. import PackageDescription
  3. let package = Package(
  4. name: "MyApp",
  5. dependencies: [
  6. /// Any other dependencies ...
  7. // 🖋🐬 Swift ORM (queries, models, relations, etc) built on SQLite.
  8. .package(url: "https://github.com/vapor/fluent-sqlite.git", from: "3.0.0-rc"),
  9. ],
  10. targets: [
  11. .target(name: "App", dependencies: ["FluentSQLite", ...]),
  12. .target(name: "Run", dependencies: ["App"]),
  13. .testTarget(name: "AppTests", dependencies: ["App"]),
  14. ]
  15. )

Don’t forget to add the module as a dependency in the targets array. Once you have added the dependency, regenerate your Xcode project with the following command:

  1. vapor xcode

Model

Now let’s create our first SQLiteModel. Models represent tables in your SQLite database and they are the primary method of interacting with your data.

  1. /// A simple user.
  2. final class User: SQLiteModel {
  3. /// The unique identifier for this user.
  4. var id: Int?
  5. /// The user's full name.
  6. var name: String
  7. /// The user's current age in years.
  8. var age: Int
  9. /// Creates a new user.
  10. init(id: Int? = nil, name: String, age: Int) {
  11. self.id = id
  12. self.name = name
  13. self.age = age
  14. }
  15. }

The example above shows a SQLiteModel for a simple model representing a user. You can make both structs and classes a model. You can even conform types that come from external modules. The only requirement is that these types conform to Codable, which must be declared on the base type for synthesized (automatic) conformance.

Standard practice with SQLite databases is using an auto-generated INTEGER for creating and storing unique identifiers in the id column. It’s also possible to use UUIDs or even Strings for your identifiers. There are convenience protocol for that.

protocol type key
SQLiteModel Int id
SQLiteUUIDModel UUID id
SQLiteStringModel String id

!!! seealso Take a look at Fluent → Model for more information on creating models with custom ID types and keys.

Migration

All of your models (with some rare exceptions) should have a corresponding table—or schema—in your database. You can use a Fluent → Migration to automatically generate this schema in a testable, maintainable way. Fluent makes it easy to automatically generate a migration for your model

!!! tip If you are creating models to represent an existing table or database, you can skip this step.

  1. /// Allows `User` to be used as a migration.
  2. extension User: Migration { }

That’s all it takes. Fluent uses Codable to analyze your model and will attempt to create the best possible schema for it.

Take a look at Fluent → Migration if you are interested in customizing this migration.

Configure

The final step is to configure your database. At a minimum, this requires adding two things to your configure.swift file.

  • FluentSQLiteProvider
  • MigrationConfig

Let’s take a look.

  1. import FluentSQLite
  2. /// ...
  3. /// Register providers first
  4. try services.register(FluentSQLiteProvider())
  5. /// Configure migrations
  6. var migrations = MigrationConfig()
  7. migrations.add(model: User.self, database: .sqlite)
  8. services.register(migrations)
  9. /// Other services....

Registering the provider will add all of the services required for Fluent SQLite to work properly. It also includes a default database config struct that uses typical development environment credentials.

You can of course override this config struct if you have non-standard credentials.

  1. /// Register custom SQLite Config
  2. let sqliteConfig = SQLiteDatabaseConfig(hostname: "localhost", port: 5432, username: "vapor")
  3. services.register(sqliteConfig)

Once you have the MigrationConfig added, you should be able to run your application and see the following:

  1. Migrating sqlite DB
  2. Migrations complete
  3. Server starting on http://localhost:8080

Query

Now that you have created a model and a corresponding schema in your database, let’s make your first query.

  1. router.get("users") { req in
  2. return User.query(on: req).all()
  3. }

If you run your app, and query that route, you should see an empty array returned. Now you just need to add some users! Congratulations on getting your first Fluent SQLite model and migration working.

Connection

With Fluent, you always have access to the underlying database driver. Using this underlying driver to perform a query is sometimes called a “raw query”.

Let’s take a look at a raw SQLite query.

  1. router.get("sqlite-version") { req -> Future<String> in
  2. return req.withPooledConnection(to: .sqlite) { conn in
  3. return try conn.query("select sqlite_version() as v;").map(to: String.self) { rows in
  4. return try rows[0].firstValue(forColumn: "v")?.decode(String.self) ?? "n/a"
  5. }
  6. }
  7. }

In the above example, withPooledConnection(to:) is used to create a connection to the database identified by .sqlite. This is the default database identifier. See Fluent → Database to learn more.

Once we have the SQLiteConnection, we can perform a query on it. You can learn more about the methods available in SQLite → Core.