vapor / fluent-kit

Swift ORM (queries, models, and relations) for NoSQL and SQL databases
MIT License
218 stars 116 forks source link

how to use? Is there a document here #546

Closed DanielLiuCD closed 1 year ago

DanielLiuCD commented 1 year ago

no documentation

martinlasek commented 1 year ago

@DanielLiuCD I am not sure if you're trying to use FluentKit directly or if you're looking to use Fluent. In the latter case there's docs here: https://docs.vapor.codes/fluent/overview/ 🙂

0xTim commented 1 year ago

To use FluentKit without Fluent or Vapor you'll need something like

/// Encapsulates the state maintained by clients of FluentKit.
public final class FluentKitContext {
    public let threadPool: NIOThreadPool
    public let eventLoopGroup: EventLoopGroup
    public let logger: Logger
    public let databases: Databases
    public let migrations: Migrations

    public init(eventLoopGroup: EventLoopGroup, logger: Logger = .init(label: "Fluent")) {
        self.threadPool = .init(numberOfThreads: 1)
        self.eventLoopGroup = eventLoopGroup
        self.logger = logger
        self.databases = .init(threadPool: threadPool, on: eventLoopGroup)
        self.migrations = .init()
    }

    deinit {
        self.databases.shutdown()
        try! self.threadPool.syncShutdownGracefully()
    }

    public func use(database factory: DatabaseConfigurationFactory, as id: DatabaseID, isDefault: Bool? = nil) {
        self.databases.use(factory, as: id, isDefault: isDefault)
    }

    public func use(database driver: DatabaseConfiguration, as id: DatabaseID, isDefault: Bool? = nil) {
        self.databases.use(driver, as: id, isDefault: isDefault)
    }

    public func add(migration: Migration, to id: DatabaseID? = nil) {
        self.migrations.add(migration, to: id)
    }

    public func migrate() -> EventLoopFuture<Void> {
        let migrator = Migrator(databases: self.databases, migrations: self.migrations, logger: self.logger, on: self.eventLoopGroup.any())

        return migrator.setupIfNeeded().flatMap { migrator.prepareBatch() }
    }

    public func revert() -> EventLoopFuture<Void> {
        let migrator = Migrator(databases: self.databases, migrations: self.migrations, logger: self.logger, on: self.eventLoopGroup.any())

        return migrator.setupIfNeeded().flatMap { migrator.revertAllBatches() }
    }
}