Skip to content

Instantly share code, notes, and snippets.

@littlebobert
Created May 24, 2020 15:25
Show Gist options
  • Save littlebobert/01ebfc585b780c173f34f3b7796664a9 to your computer and use it in GitHub Desktop.
Save littlebobert/01ebfc585b780c173f34f3b7796664a9 to your computer and use it in GitHub Desktop.
Adding records to my Movie table
// I have one table: Movie. To add records, after the Movie migration I’m doing:
let worker = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let conn = sqliteDatabase.newConnection(on: worker)
let _ = conn.map { connection in
// Open the CSV file
for line in lines {
// Parse the line to get the title, etc.
let movie = Movie(id: id, title: title)
dispatchGroup.enter()
let future = movie.save(on: connection)
future.whenFailure { (error) in
dispatchGroup.leave()
}
future.whenSuccess { _ in
dispatchGroup.leave()
}
// ...etc.
}
dispatchGroup.notify(queue: .global()) {
worker.shutdownGracefully { error in
// etc.
}
}
}
@littlebobert
Copy link
Author

To figure out when migrations are finished, I’m doing:

extension Movie: Migration {
    static func prepare(on connection: SQLiteConnection) -> EventLoopFuture<Void> {
        let future = Database.create(Movie.self, on: connection) { creator in
            creator.field(for: \.id, isIdentifier: true)
            creator.field(for: \.title)
            creator.field(for: \.format)
            creator.field(for: \.posterURLString)
        }
        future.whenComplete {
            MovieDatabase.shared.populateFromCSV()
        }
        return future
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment