2

I've been trying to link up my PostgreSQL database to a Swift Vapor project so I create routes to it. The first table I want to access is a table in my_database calls users. It has the properties user_id (primary integer key) and created_on (timestamp with time zone).

I've linked my Vapor project to my_database so that I can create new models. However, what if I want access to the pre-existing table users. Here's what I've cobbled together from the documentation and a few tutorials:

My initial model:

final class Users: Model {

static let name = "users"

typealias ID = Int
typealias Database = PostgreSQLDatabase

static let idKey: WritableKeyPath<Users, Int?> = \.user_id

var user_id: Int?
var created_on: Date
}

extension Users: Content { }

My migration (which I think is just a 'blank' migration, just to hook the project to the table?):

struct FirstMigration: PostgreSQLMigration {
static func prepare(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
    return conn.future()
}

static func revert(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
    return Future<Void>.done(on: conn)
   }
}

And my configuration:

var migrations = MigrationConfig()
migrations.add(migration: FirstMigration.self, database: .psql)
services.register(migrations)

Any guidance much appreciated!

ADB
  • 591
  • 7
  • 21

1 Answers1

2

You don't need the migration. You either need to make your model confirm to Migration and add the model as a migration or set the static defaultDatabase property. Then you should be good to go.

PS - I think you want entity not name to tell it what the table name is.

0xTim
  • 5,146
  • 11
  • 23
  • Thanks for your help again @0xTim (you helped getting started with this on Discord too!) I've tried doing that and it all looks good, but when I run it in Xcode I get the following warning: `Fatal error: Error raised at top level: ⚠️ PostgreSQL Error: relation "users" already exists` How do I overcome that please? – ADB Feb 08 '20 at 09:12
  • Are you trying to create the table anywhere? Do you know what line it throws the error on? – 0xTim Feb 08 '20 at 21:46