Querying Models

Once you have a model (and optionally a migration) you can start querying your database to create, read, update, and delete data.

Connection

The first thing you need to query your database, is a connection to it. Luckily, they are easy to get.

You can use either the application or an incoming request to create a database connection. You just need access to the database identifier.

Request

The preferred method for getting access to a database connection is via an incoming request.

  1. router.get(...) { req in
  2. return req.withConnection(to: .foo) { db in
  3. // use the db here
  4. }
  5. }

The first parameter is the database’s identifier. The second parameter is a closure that accepts a connection to that database.

!!! tip Although the closure to .withConnection(to: ...) accepts a database connection, we often use just db for short.

The closure is expected to return a Future<Void>. When this future is completed, the connection will be released back into Fluent’s connection pool. This is usually acheived by simply returning the query as we will soon see.

Application

You can also create a database connection using the application. This is useful for cases where you must access the database from outside a request/response event.

  1. let res = app.withConnection(to: .foo) { db in
  2. // use the db here
  3. }
  4. print(res) // Future<T>

This is usually done in the boot section of your application.

!!! warning Do not use database connections created by the application in a route closure (when responding to a request). Always use the incoming request to create a connection to avoid threading issues.

Create

To create (save) a model to the database, first initialize an instance of your model, then call .save(on: ).

  1. router.post(...) { req in
  2. return req.withConnection(to: .foo) { db -> Future<User> in
  3. let user = User(name: "Vapor", age: 3)
  4. return user.save(on: db).transform(to: user) // Future<User>
  5. }
  6. }

Response

.save(on: ) returns a Future<Void> that completes when the user has finished saving. In this example, we then map that Future<Void> to a Future<User> by calling .map and passing in the recently-saved user.

You can also use .map to return a simple success response.

  1. router.post(...) { req in
  2. return req.withConnection(to: .foo) { db -> Future<HTTPResponse> in
  3. let user = User(name: "Vapor", age: 3)
  4. return user.save(on: db).map(to: HTTPResponse.self) {
  5. return HTTPResponse(status: .created)
  6. }
  7. }
  8. }

Multiple

If you have multiple instances to save, do so using an array. Arrays containing only futures behave like futures.

  1. router.post(...) { req in
  2. return req.withConnection(to: .foo) { db -> Future<HTTPResponse> in
  3. let marie = User(name: "Marie Curie", age: 66)
  4. let charles = User(name: "Charles Darwin", age: 73)
  5. return [
  6. marie.save(on: db),
  7. charles.save(on: db)
  8. ].map(to: HTTPResponse.self) {
  9. return HTTPResponse(status: .created)
  10. }
  11. }
  12. }

Read

To read models from the database, use .query() on the database connection to create a QueryBuilder.

All

Fetch all instances of a model from the database using .all().

  1. router.get(...) { req in
  2. return req.withConnection(to: .foo) { db -> Future<[User]> in
  3. return db.query(User.self).all()
  4. }
  5. }

Filter

Use .filter(...) to apply filters to your query.

  1. router.get(...) { req in
  2. return req.withConnection(to: .foo) { db -> Future<[User]> in
  3. return try db.query(User.self).filter(\User.age > 50).all()
  4. }
  5. }

First

You can also use .first() to just get the first result.

  1. router.get(...) { req in
  2. return req.withConnection(to: .foo) { db -> Future<User> in
  3. return try db.query(User.self).filter(\User.name == "Vapor").first().map(to: User.self) { user in
  4. guard let user = user else {
  5. throw Abort(.notFound, reason: "Could not find user.")
  6. }
  7. return user
  8. }
  9. }
  10. }

Notice we use .map(to:) here to convert the optional user returned by .first() to a non-optional user, or we throw an error.

Update

  1. router.put(...) { req in
  2. return req.withConnection(to: .foo) { db -> Future<User> in
  3. return db.query(User.self).first().map(to: User.self) { user in
  4. guard let user = $0 else {
  5. throw Abort(.notFound, reason: "Could not find user.")
  6. }
  7. return user
  8. }.flatMap(to: User.self) { user in
  9. user.age += 1
  10. return user.update(on: db).map(to: User.self) { user }
  11. }
  12. }
  13. }

Notice we use .map(to:) here to convert the optional user returned by .first() to a non-optional user, or we throw an error.

Delete

  1. router.delete(...) { req in
  2. return req.withConnection(to: .foo) { db -> Future<User> in
  3. return db.query(User.self).first().map(to: User.self) { user in
  4. guard let user = $0 else {
  5. throw Abort(.notFound, reason: "Could not find user.")
  6. }
  7. return user
  8. }.flatMap(to: User.self) { user in
  9. return user.delete(on: db).transfom(to: user)
  10. }
  11. }
  12. }

Notice we use .map(to:) here to convert the optional user returned by .first() to a non-optional user, or we throw an error.