PhilWaldmann / openrecord

Make ORMs great again!
https://openrecord.js.org
MIT License
486 stars 38 forks source link

can't create array of records with manually-generated primary keys #70

Closed MrGrinst closed 6 years ago

MrGrinst commented 6 years ago

Thanks for making such a great library!

Found a small issue that affects my use case. I've got a table that has a single text column that is a primary key. The text is generated on the client and I want to save multiple rows to the table at once. However, this isn't working because it thinks the records already exist.

Table: CREATE TABLE "my_table" ("str" varchar, PRIMARY KEY ("str"));

Attempted record creation: store.Model('my_table').create([{ str: 'thing1' }, { str: 'thing2' }])

The problem is with the conditional at lib/base/collection.js:242.

if (mapKey.length > 0 && mapKey.length === primaryKeys.length) {
  record._exists()

Works great for tables that have auto-generated/sequential primary keys, but is preventing the save from happening for these manually generated primary keys.

PhilWaldmann commented 6 years ago

Hi @MrGrinst thanks for your feedback. By default openrecord does not write primary keys. If primary key values are present, it tries to update existing records. In you example, only one column is present (the primary key), so it wont do anything -> nothing to update!

But you could overwrite this behaviour via

  // inside your model definition
  this.attributes.str.primary = false

So your database will handle the primary key constraint and openrecord will handle your field as a normal string. The only downside is, that you can't query via MyTable.find('thing1') anymore. Only via MyTable.where({str: 'thing1'})

Does this solve your problem? Or do you think the API has to be adopted for this use case.

Thanks, Philipp

PhilWaldmann commented 6 years ago

@MrGrinst do you need any more help?

MrGrinst commented 6 years ago

Nope, your recommendation should work perfectly. Thanks!