Closed brntphish closed 6 years ago
I'm also seeing this issue. I wouldn't expect to be able to save a new model with an arbitrary ID but I would expect it to return an error–not success.
@ezfe @brntphish you need to use model.create()
instead of model.save()
when supplying the ID. Fluent uses the presence of an ID to determine whether to do a update or create
@0xTim Ah, then shouldn't model.save()
return an error if you supply an ID that doesn't exist yet?
@ezfe depends on the DB - normal you want to hand that off to a DB
@0xTim Isnt that kinda counter intuitive...... I mean that would indicate I have to query the db before I need to add an entry to see if it exists (since an error is not reported and I cant read to the error to know "it would create a duplicate key") and swap from create to update
like wise if I called update on a row that didnt exist it would not get created.
Use case, a json file of employees with employee numbers provided daily with lots of info for each record that changes, as well as new employees.
Read each json entry as an employee Get employee number as pk create or update (in order to determine if I should create or update, I am forced to query to determine the method needed)
I think this is confusing and should be handled more quietly kinda like a hybrid between SQL insert (Fluent create) and and SQL update(Fluent update)
We need a single method that will If Exists Update, else Create ..... maybe an upsert command (update or insert)
Failing Use Case (or at least needs to be changed to determine if exists first):
let object = MyStringModel(id: "EMP12345678K47", name: "John Doe") object.save(on: req).map(to: User.self, {user in print(user.id) < Prints Succesfully ... but nothing is in the db })
Use case needed:
let object = MyStringModel(id: "EMP12345678K47", name: "John Doe") object.upsert(on: req).map(to: User.self, {user in /// update if exists, create if doesnt exist print(user.id) })
UPDATE: (Feel Free to Close) put here for others that have the same issue. apparently this now exists as : object.create(orUpdate: true, on: req)
My solution to this problem was to define a willCreate
on PostgreSQLModel
that checks the ID field, and to exclusively use create
when making new elements. You could also just set the ID field to nil.
extension PostgreSQLModel {
func willCreate(on connection: PostgreSQLConnection) throws -> EventLoopFuture<Self> {
if self.id != nil {
throw Abort(.forbidden, reason: "Cannot create model with ID")
}
return Future.map(on: connection) { self }
}
}
No Data is Saved to the Database, The Table is empty. I have dropped the table and let it get recreated. Result is the same. no data in table despite reporting success.
The when.Success Handler fires and prints:
Note: For Some Reason I could not get the "code block" to format correctly