vapor / fluent-postgres-driver

🐘 PostgreSQL driver for Fluent.
MIT License
149 stars 53 forks source link

Model is not being saved when supplying ID, Does not save, Reports Success #65

Closed brntphish closed 6 years ago

brntphish commented 6 years ago
func foo(objects: [Int:[Int]]) {
  for object in objects {
    let new_object = MyObjectModel(id: object.key, object.value)
    let result = createNewObject(db, new_object)

    result.whenSuccess( {object in
      print(object.id)
      print(object.indexList)
    })

    result.whenFailure ({error in
      print(error.localizedDescription)
    })
  }
}

func createNewObject(_ db: DatabaseConnectable, _ new_object: MyObjectModel) -> Future<MyObjectModel> {
  return new_object.save(on: db)
}

//MyObjectModel.swift
import Vapor
import Foundation
import FluentPostgreSQL

final class MyObjectModel: Codable {
  var id: OtherObject.ID? //Type = Int
  var indexList: [ADiffObject.ID] //Type = Int
  var createdAt: Date?
  var updatedAt: Date?

  init(id: OtherObject.ID, _ indexList: [ADiffObject.ID]) {
    self.id = id
    self.indexList = indexList
  }
}

// MARK: Required Extensions
extension MyObjectModel: PostgreSQLModel{}

extension MyObjectModel: Content {}
extension MyObjectModel: Migration {}
extension MyObjectModel: Parameter {}

extension MyObjectModel: Timestampable {
  static var createdAtKey: WritableKeyPath<MyObjectModel, Date?> {return \.createdAt}
  static var updatedAtKey: WritableKeyPath<MyObjectModel, Date?> {return \.updatedAt}
}

// MARK: Relationships
extension MyObjectModel {}

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:

    /// 275940
    /// [31, 43, 39, 75, 30, 319, 163, 1113, 28, 90, 34]
    /// 275938
    /// [31, 280, 39, 41, 28, 43, 75, 78, 30, 115, 42333]
    /// 275939
    /// [31, 280, 39, 28, 178, 43, 34, 29, 75, 42333]
    /// 279987
    /// [4077]
    /// 275946
    /// [336, 90, 31, 128, 43, 368]

Note: For Some Reason I could not get the "code block" to format correctly

ezfe commented 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.

0xTim commented 6 years ago

@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

ezfe commented 6 years ago

@0xTim Ah, then shouldn't model.save() return an error if you supply an ID that doesn't exist yet?

0xTim commented 6 years ago

@ezfe depends on the DB - normal you want to hand that off to a DB

brntphish commented 6 years ago

@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) })

brntphish commented 6 years ago

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)

ezfe commented 6 years ago

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 }
    }
}