Skip to content

Implement ON CONFLICT for postgres 9.5 - #6325

Closed
inDream wants to merge 5 commits into
sequelize:masterfrom
inDream:postgres-on-conflict
Closed

inDream wants to merge 5 commits into
sequelize:masterfrom
inDream:postgres-on-conflict

Conversation

@inDream

@inDream inDream commented Jul 22, 2016 •

Copy link
Copy Markdown
Contributor

Pull Request check-list

  • Does npm run test or npm run test-DIALECT pass with this change (including linting)?
  • Does your issue contain a link to existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Have you added new tests to prevent regressions?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)?
  • Have you added an entry under Future in the changelog?

NOTE: these things are not required to open a PR and can be done afterwards / while the PR is open.

Description of change

Implement `ON CONFLICT for postgres 9.5, Fix #4132 #3354.
It's a draft version since it's a breaking change.

I've used @ncwhale suggestion on .upsert(), but review is needed.

API: Model.upsert()

/**
   * @param  {Object}          values
   * @param  {Object}          [options]
   * ...
   * @param  {Object}          [options.conflict] Actions on conflict
   * @param  {String}          [options.conflict.constraint=[primaryKey]] constraint_name
   * @param  {String}          [options.conflict.target] index_column_name OR index_expression
   * @param  {Object}          [options.conflict.where] constraint_name
   * @param  {Boolean|Array}   [options.update=[Columns exclude options.conflict.target]] "DO UPDATE SET" if provided an array of column name or not specific this option, "DO NOTHING" if false. 
   * @param  {Boolean}         [options.returning] Return updated instance if true
   *
   * @return {Promise<created>} Returns a boolean indicating whether the row was created or updated or updated instance.
   */

Usage

// Use id as conflict target
Model.upsert(instance, {
  conflict: {
    target: 'id'
  }
});

// Use composite key as constraint
Model.upsert(instance, {
  conflict: {
    constraint: 'users_foo_bar_key'
  }
});

// Use complex primary key as constraint
Model.upsert(instance, {
  conflict: {
    constraint: 'users_pkey'
  }
});

// Choose which field to be updated
Model.upsert(instance, {
  conflict: {
    update: ['foo', 'bar']
  }
});

// Do nothing when conflicted
Model.upsert(instance, {
  conflict: {
    update: false
  }
});

Todo

  • Auto generate constraint_name for options.conflict.constraint
  • More test cases after API is confirmed

Comment thread .travis.yml Outdated
- CXX=clang++
- npm_config_clang=1
- COVERALLS_REPO_TOKEN=751SiA6QhY5EH4P2ygq7JFWulqiD2ETXO
- COVERALLS_PARALLEL=true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

uh?

@inDream

inDream commented Jul 22, 2016 •

Copy link
Copy Markdown
Contributor Author

@mickhansen This pull request is mainly for ON CONFLICT usage before API is confirmed,
so .travis.yml & README.md changed to test postgres 9.5 only.

For lib/dialects/postgres/index.js, is there any version detection can be made?

Please focus on API design first.

@inDream

inDream commented Jul 27, 2016

Copy link
Copy Markdown
Contributor Author

Anyone would like to review the proposed API?

@mickhansen

Copy link
Copy Markdown
Contributor

@inDream @janmeier is on holiday atm, he's the original implementer of UPSERT so i'm sure he'll be happy to take a look when he gets back.

@inDream

inDream commented Aug 8, 2016

Copy link
Copy Markdown
Contributor Author

@janmeier ping

@ncwhale

ncwhale commented Aug 9, 2016

Copy link
Copy Markdown

Great! THX for the update! Have a try now.

@janmeier

janmeier commented Aug 9, 2016

Copy link
Copy Markdown
Member

Maybe use returning instead of returnItem, to keep consistent with the rest of the API - Otherwise LGTM.

Also, yay travis-ci/travis-cookbooks#651!

@inDream

inDream commented Aug 9, 2016 •

Copy link
Copy Markdown
Contributor Author

@janmeier Changed back to returning, but as returning is required for postgres to return item, I've assigned '*' to returning if user not provided this option, item only return when returning === true.

If options.returning = false it will always return undefined, is it something not expected by user?

@JLHwung

JLHwung commented Aug 17, 2016

Copy link
Copy Markdown
Contributor

@mickhansen Any plans on backporting this feature to 3.x ?

@felixfbecker

Copy link
Copy Markdown
Contributor

@inDream I don't fully understand what target and constraint mean. Could you elaborate?

@inDream

inDream commented Aug 17, 2016

Copy link
Copy Markdown
Contributor Author

@JLHwung I can also work on v3 branch.
@felixfbecker target = column name, constraint = key of unique index contains multiple columns.

@janmeier @mickhansen where can I get the generated unique index key so user don't need to specify it.

@janmeier

Copy link
Copy Markdown
Member

nameIndexes

nameIndexes(indexes, rawTablename) {
(you could refactor it out so you don't need to call it with an array)

@IanGrainger

Copy link
Copy Markdown

Arrived from: http://stackoverflow.com/questions/29063232/sequelize-upsert/29071422?noredirect=1#comment68297657_29071422 - I'm looking for a way to create or update an object and return it. At the moment I'm using findOrCreate with where and defaults the same, then setting the fields I want to set manually and calling save once that's finished.

This seems like something the library should just do for me? Or am I asking too much?

@inDream
inDream force-pushed the postgres-on-conflict branch from 52d5980 to d04a8db Compare November 20, 2016 13:18
@ShimShamSam

Copy link
Copy Markdown

Any update on this?

@andrewgbliss

Copy link
Copy Markdown

It would be so awesome if this got merged in. Now I have to implement something on my own instead of using sequelize.

@felixfbecker

Copy link
Copy Markdown
Contributor

Tests are failing

@inDream

inDream commented Dec 10, 2016

Copy link
Copy Markdown
Contributor Author

@felixfbecker Tests are failing due to reasons not related to my codes.
Do I need to add back old upsert codes for postgres version < 9.5?

@felixfbecker

Copy link
Copy Markdown
Contributor

It must be related to the code, the failures are all related to upsert():

  [MYSQL] Model
    upsert
      1) works with upsert on id
      2) works with upsert on a composite key
      ✓ should work with UUIDs wth default values (38ms)
      3) works with upsert on a composite primary key
      ✓ supports validations
      4) works with BLOBs
      5) works with .field
      6) works with primary key using .field
      7) works with database functions
      ✓ does not overwrite createdAt time on update
      ✓ does not update using default values
      ✓ Works when two separate uniqueKeys are passed (52ms)

@felixfbecker

Copy link
Copy Markdown
Contributor
 [POSTGRES-NATIVE] Model
    upsert
      ✓ works with upsert on id
      ✓ works with upsert on a composite key
      ✓ should work with UUIDs wth default values
      ✓ works with upsert on a composite primary key
      ✓ supports validations
      ✓ works with BLOBs
      ✓ works with .field
      ✓ works with primary key using .field
      ✓ works with database functions
      ✓ does not overwrite createdAt time on update
      ✓ does not update using default values
An unhandled exception occured:
/home/travis/build/sequelize/sequelize/test/support.js:23
  throw e;
  ^

TypeError: Cannot convert undefined or null to object

@felixfbecker

Copy link
Copy Markdown
Contributor
[MSSQL] Model
    upsert
      1) works with upsert on id
      2) works with upsert on a composite key
      √ should work with UUIDs wth default values
      3) works with upsert on a composite primary key
      √ supports validations
      4) works with BLOBs
      5) works with .field
      6) works with primary key using .field
      7) works with database functions
      √ does not overwrite createdAt time on update
      √ does not update using default values
      √ Works when two separate uniqueKeys are passed (47ms)

@inDream
inDream force-pushed the postgres-on-conflict branch from 72202c9 to 44fc829 Compare June 27, 2018 18:33
@inDream
inDream force-pushed the postgres-on-conflict branch from 44fc829 to 5676a3e Compare July 14, 2018 07:02
@davidadas

Copy link
Copy Markdown

@inDream have you been continuing work on this? I'd be interested in seeing this get merged.

@ghost

ghost commented Aug 29, 2018

Copy link
Copy Markdown

After 2 years - don't hold your breath! 😉

@inDream

inDream commented Aug 30, 2018

Copy link
Copy Markdown
Contributor Author

@davidadas @IanIsFluent I would be available to work on it after next week.

@rcrogers

Copy link
Copy Markdown

Excited to see some recent movement on this!

@inDream
inDream force-pushed the postgres-on-conflict branch from 5676a3e to 3735c5c Compare September 13, 2018 10:50
@glesperance

Copy link
Copy Markdown

Any updates on this?

1 similar comment
@rsaphala

Copy link
Copy Markdown

Any updates on this?

@Fjandin

Fjandin commented Jan 28, 2019

Copy link
Copy Markdown

wow.... any chance this will make it into sequelize?

@inDream
inDream force-pushed the postgres-on-conflict branch from 3735c5c to 577231d Compare January 30, 2019 05:30
@inDream
inDream force-pushed the postgres-on-conflict branch from 577231d to cf4ddd9 Compare February 8, 2019 15:34
@AlecTroemel

Copy link
Copy Markdown

I'll give another +1 on hoping this someday makes it into sequelize. Looking at the failing travis-ci, seems like the only failing test is

[POSTGRES-NATIVE] Model
       upsert
         works with primary key using .field:

specifically it looks like upsert creates, but doesnt update the test column. Im pretty new to this (awesome) project, but I'll help how I can

@Restuta

Restuta commented Mar 4, 2019

Copy link
Copy Markdown

Yeah, I would like to know if I can actually help to deliver this faster? What needs to be done? @inDream

@bmeriaux

bmeriaux commented Apr 2, 2019

Copy link
Copy Markdown
Contributor

i think this PR should be really looked, the gain of performance with postgres is impressive and now v9.5 is not young anymore

@tsheaff

tsheaff commented Apr 4, 2019 •

Copy link
Copy Markdown

Is there an update on this issue? I know people maintain Sequelize without compensation, which is incredible, but as heavy users of Sequelize in production, this issue is by far our number one ask and has been for years. Sounds like we're not alone

We have seen database instability (Postgres on RDS), with rising CPUs due to blocking queries. This was AWS's official support response:

1. In the long term I recommend you to adjust your workload to avoid session blocking. I would focus on investigating what, when and why is executing those problematic "CREATE FUNCTION" queries.

We're at the point where we're going to wrap all of our upserts in a custom function that performs a native postgres upsert directly (and properly calls the hooks afterwards), which is definitely gross. We feel that this is a more effective use of our team's time than (1) onboarding ourselves to the entire Seuqelize codebase, (2) submitting a substantial PR like #6325, and most critically (3) getting the community to accept it without nitpicking it like they did with this one for so long.

We're also going to try out forking sequelize and merge this PR to our fork to see if it works properly.

Reading through this whole thread, I'm still not fully clear on why this is not able to be merged.

@tsheaff

tsheaff commented Apr 4, 2019

Copy link
Copy Markdown

There was also #7174 which @sushantdhiman closed in favor of this PR over two years ago

@papb

papb commented Jul 26, 2019

Copy link
Copy Markdown
Member

Looks like if #11163 is merged this PR may be closed, does anyone disagree?

We are waiting for @thaddeusmt on that PR.

@papb papb added dialect: postgres For issues and PRs. Things that involve PostgreSQL (and do not involve all dialects). status: awaiting response For issues and PRs. OP must respond (or change something, if it is a PR). Maintainers have no action type: feature DEPRECATED: replace with the "feature" issue type labels Jul 26, 2019
@papb

papb commented Jul 27, 2019 •

Copy link
Copy Markdown
Member

Closing this in favor of #11163, if anyone disagrees please ping me.

@papb papb closed this Jul 27, 2019
@sushantdhiman

Copy link
Copy Markdown
Contributor

@papb This PR was actually targeting Model.upsert as well which is different from what #11163 implemented. But I think this PR in current state is not ready for merge. New PR should be opened to target just the Model.upsert

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dialect: postgres For issues and PRs. Things that involve PostgreSQL (and do not involve all dialects). status: awaiting response For issues and PRs. OP must respond (or change something, if it is a PR). Maintainers have no action type: feature DEPRECATED: replace with the "feature" issue type

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Postgres UPSERT native support