2

How to add data to SQLite database manually in Vapor project so that at startup there's already some data in it?

jonaszmclaren
  • 2,459
  • 20
  • 30
  • What do you mean exactly because it sounds that you have already answered your own question, you add data manually by adding it manually. I know that wasn't what you meant so please clarify. – Joakim Danielson Dec 21 '18 at 13:41
  • I mean adding objects programmatically to the database, I didn't find solution how to do that. – jonaszmclaren Dec 21 '18 at 13:51

1 Answers1

2

I use this:

struct CreateAdminUser: Migration {

    static func prepare(on connection: SQLiteConnection) -> Future<Void> {
        let password = try? BCrypt.hash("secret")
        let user = User(email: "me@example.co.uk", password: password!)
        return user.save(on: connection).transform(to: ())
    }

    static func revert(on connection: SQLiteConnection) -> Future<Void> {
        return Future.map(on: connection) {}
    }
}

I then put this line into configure.swift migrations:

migrations.add(migration: CreateAdminUser.self, database: .sqlite)
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Nick
  • 4,820
  • 18
  • 31
  • 47