vapor-fluent

Guide for using Vapor's Fluent ORM framework in Swift server-side applications

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "vapor-fluent" with this command: npx skills add thepianokid/vapor-fluent-skill/thepianokid-vapor-fluent-skill-vapor-fluent

Vapor Fluent ORM

Fluent is an ORM framework for Swift used with the Vapor web framework. It leverages Swift's strong type system to provide a type-safe interface for database operations. Instead of writing raw queries, you define model types that represent database structures and use them for CRUD operations.

When to use

Use this skill when:

  • Setting up Fluent in a new or existing Vapor project
  • Defining database models with property wrappers (@ID, @Field, @Parent, @Children, etc.)
  • Writing database migrations
  • Performing CRUD operations (create, read, update, delete)
  • Setting up relations between models (one-to-many, many-to-many)
  • Querying the database with Fluent's query builder
  • Configuring database drivers (PostgreSQL, SQLite, MySQL, MongoDB)

Instructions

1. Add Dependencies

For a new project, use vapor new and answer "yes" to including Fluent. For an existing project, add the Fluent package and a database driver to Package.swift:

// Package dependencies
.package(url: "https://github.com/vapor/fluent.git", from: "4.0.0"),
.package(url: "https://github.com/vapor/fluent-<db>-driver.git", from: "<version>"),

// Target dependencies
.target(name: "App", dependencies: [
    .product(name: "Fluent", package: "fluent"),
    .product(name: "Fluent<Db>Driver", package: "fluent-<db>-driver"),
    .product(name: "Vapor", package: "vapor"),
]),

2. Configure the Database Driver

In configure.swift, import Fluent and the driver, then configure the database connection.

PostgreSQL (recommended):

import Fluent
import FluentPostgresDriver

app.databases.use(
    .postgres(
        configuration: .init(
            hostname: "localhost",
            username: "vapor",
            password: "vapor",
            database: "vapor",
            tls: .disable
        )
    ),
    as: .psql
)

SQLite (good for prototyping):

import Fluent
import FluentSQLiteDriver

// File-based
app.databases.use(.sqlite(.file("db.sqlite")), as: .sqlite)

// In-memory (ephemeral, useful for testing)
app.databases.use(.sqlite(.memory), as: .sqlite)

MySQL / MariaDB:

import Fluent
import FluentMySQLDriver

app.databases.use(.mysql(
    hostname: "localhost",
    username: "vapor",
    password: "vapor",
    database: "vapor"
), as: .mysql)

MongoDB:

import Fluent
import FluentMongoDriver

try app.databases.use(.mongo(connectionString: "<connection string>"), as: .mongo)

PostgreSQL, MySQL, and MongoDB also support connection string URLs:

try app.databases.use(.postgres(url: "<connection string>"), as: .psql)

3. Define Models

Create model classes conforming to Model. Mark them final for performance. Every model needs:

  • A static schema property (table/collection name, snake_case and plural)
  • An @ID field
  • An empty init()
final class Galaxy: Model, Content {
    static let schema = "galaxies"

    @ID(key: .id)
    var id: UUID?

    @Field(key: "name")
    var name: String

    init() { }

    init(id: UUID? = nil, name: String) {
        self.id = id
        self.name = name
    }
}

Key property wrappers for fields:

  • @ID(key: .id) -- unique identifier, use UUID? by default
  • @Field(key: "db_column") -- required stored field
  • @OptionalField(key: "db_column") -- optional stored field
  • @Parent(key: "foreign_key_id") -- belongs-to relation (stores a foreign key)
  • @Children(for: \.$parentField) -- has-many relation (inverse of @Parent)
  • @Siblings(...) -- many-to-many relation via a pivot table
  • @Timestamp(key: "created_at", on: .create) -- auto-managed timestamp

Add Content conformance to return models directly from route handlers.

4. Define Relations

One-to-many (Parent/Children):

On the child model, add a @Parent field:

final class Star: Model, Content {
    static let schema = "stars"

    @ID(key: .id)
    var id: UUID?

    @Field(key: "name")
    var name: String

    @Parent(key: "galaxy_id")
    var galaxy: Galaxy

    init() { }

    init(id: UUID? = nil, name: String, galaxyID: UUID) {
        self.id = id
        self.name = name
        self.$galaxy.id = galaxyID
    }
}

On the parent model, add a @Children property:

// Add to Galaxy model
@Children(for: \.$galaxy)
var stars: [Star]

Note: Access the underlying property wrapper with $ prefix (e.g., self.$galaxy.id = galaxyID).

5. Write Migrations

Create migrations conforming to AsyncMigration to set up database schemas. The prepare method creates/modifies the schema, and revert undoes those changes.

struct CreateGalaxy: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema("galaxies")
            .id()
            .field("name", .string)
            .create()
    }

    func revert(on database: Database) async throws {
        try await database.schema("galaxies").delete()
    }
}

For models with foreign keys, add a .references constraint:

struct CreateStar: AsyncMigration {
    func prepare(on database: Database) async throws {
        try await database.schema("stars")
            .id()
            .field("name", .string)
            .field("galaxy_id", .uuid, .references("galaxies", "id"))
            .create()
    }

    func revert(on database: Database) async throws {
        try await database.schema("stars").delete()
    }
}

Register migrations in configure.swift in dependency order (parent tables first):

app.migrations.add(CreateGalaxy())
app.migrations.add(CreateStar())

Run migrations from the command line:

swift run App migrate

For in-memory SQLite databases, auto-migrate on startup:

try await app.autoMigrate()

6. Perform CRUD Operations

Create:

app.post("galaxies") { req async throws -> Galaxy in
    let galaxy = try req.content.decode(Galaxy.self)
    try await galaxy.create(on: req.db)
    return galaxy
}

Read all:

app.get("galaxies") { req async throws in
    try await Galaxy.query(on: req.db).all()
}

Read one by ID:

app.get("galaxies", ":id") { req async throws -> Galaxy in
    guard let galaxy = try await Galaxy.find(req.parameters.get("id"), on: req.db) else {
        throw Abort(.notFound)
    }
    return galaxy
}

Update:

app.put("galaxies", ":id") { req async throws -> Galaxy in
    guard let galaxy = try await Galaxy.find(req.parameters.get("id"), on: req.db) else {
        throw Abort(.notFound)
    }
    let updated = try req.content.decode(Galaxy.self)
    galaxy.name = updated.name
    try await galaxy.save(on: req.db)
    return galaxy
}

Delete:

app.delete("galaxies", ":id") { req async throws -> HTTPStatus in
    guard let galaxy = try await Galaxy.find(req.parameters.get("id"), on: req.db) else {
        throw Abort(.notFound)
    }
    try await galaxy.delete(on: req.db)
    return .noContent
}

7. Use Eager Loading for Relations

Use .with(\.$relation) on the query builder to load related models:

app.get("galaxies") { req async throws in
    try await Galaxy.query(on: req.db).with(\.$stars).all()
}

This returns galaxies with their stars nested in the response:

[
    {
        "id": "...",
        "name": "Milky Way",
        "stars": [
            { "id": "...", "name": "Sun", "galaxy": { "id": "..." } }
        ]
    }
]

8. Enable Query Logging (Optional)

To see the generated SQL statements in the console, set the log level to debug in configure.swift:

app.logger.logLevel = .debug

Key Reminders

  • Always mark model classes as final.
  • Every model must have an empty init() { }.
  • Use snake_case and plural names for schema values (e.g., "galaxies", "star_tags").
  • Database field keys in property wrappers should use snake_case (e.g., "galaxy_id").
  • Register migrations in dependency order -- parent tables before child tables.
  • Use $ prefix to access the underlying property wrapper (e.g., $galaxy.id).
  • Add Content conformance to models you want to return directly from route handlers.
  • Do not disable TLS certificate verification in production (MySQL/PostgreSQL).

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

test_skill

import json import tkinter as tk from tkinter import messagebox, simpledialog

Archived SourceRecently Updated
General

neo

Browse websites, read web pages, interact with web apps, call website APIs, and automate web tasks. Use Neo when: user asks to check a website, read a web page, post on social media (Twitter/X), interact with any web app, look up information on a specific site, scrape data from websites, automate browser tasks, or when you need to call any website's API. Keywords: website, web page, browse, URL, http, API, twitter, tweet, post, scrape, web app, open site, check site, read page, social media, online service.

Archived SourceRecently Updated
General

image-gen

Generate AI images from text prompts. Triggers on: "生成图片", "画一张", "AI图", "generate image", "配图", "create picture", "draw", "visualize", "generate an image".

Archived SourceRecently Updated
General

explainer

Create explainer videos with narration and AI-generated visuals. Triggers on: "解说视频", "explainer video", "explain this as a video", "tutorial video", "introduce X (video)", "解释一下XX(视频形式)".

Archived SourceRecently Updated