Reputation: 1839
I am using Vapor to write a simple web app. I have an entity to save session info into a database. The code for this entity is as follows:
struct SessionToken: Model{
var exists: Bool = false
var id: Node?
var username: String
var accessToken: String
var expiryDate: String
init(username: String, accessToken: String, expiryDate: String) {
self.username = username
self.accessToken = accessToken
self.expiryDate = expiryDate
}
init(node: Node, in context: Context) throws {
try self.id = node.extract("id")
try self.username = node.extract("username")
try self.accessToken = node.extract("accessToken")
try self.expiryDate = node.extract("expiryDate")
}
func makeNode(context: Context) throws -> Node {
let sessionToken = try Node(node:["id": id, "username": username, "accessToken": accessToken, "expiryDate": expiryDate])
return sessionToken
}
static func prepare(_ database: Database) throws {
try database.create("sessiontokens"){ sessiontokens in
sessiontokens.id()
sessiontokens.string("username")
sessiontokens.string("accessToken")
sessiontokens.string("expiryDate")
}
}
static func revert(_ database: Database) throws {
try database.delete("sessiontokens")
}
}
I enter some fake info into the database, but when I query the database with the following code:
let token = try SessionToken.query().filter("username", "[email protected]").first()
I get an error: Could not initialize SessionToken, skipping: unableToConvert(node: nil, expected: "String")
The funny thing is that when I replace SessionToken
with any other entity in the project the code works just fine. The only entity I am having trouble fetching any info from the database is SessionToken
and it has been frustrating me since last night!
I would really appreciate it if someone could point me in the right direction to solve this problem.
P.S. I am using Postgres.
Upvotes: 2
Views: 338
Reputation: 1839
I found the source of the problem. As mentioned by the error Could not initialize SessionToken
there is a problem with initialization of the entity. Postgres creates column names with all lower case letters so if you create an "accessToken" column, it is saved as "accesstoken" in the table without the capital T. As you can see I am querying the table with "accessToken" and no such column exists; therefore, the source of the problem was naming discrepancies between the table and the query.
You can read more about Postgres case sensitivity here: Are PostgreSQL column names case-sensitive?
Upvotes: 3