title: Validate @versionColumn value before saving an entity with TypeORM
body: <p>I'm currently working on saving data in a postgres DB using TypeORM with the NestJS integration. I'm saving data which keeps track of a version property using TypeORM's <a href="https://typeorm.io/#/decorator-reference/versioncolumn" rel="nofollow noreferrer">@VersionColumn</a> feature, which increments a number each time <code>save()</code> is called on a repository.</p>
  <p>For my feature it is important to check this version number before updating the records.</p>
  <p><strong>Important</strong></p>
  <p>I know I could technically achieve this by retrieving the record before updating it and checking the versions, but this leaves a small window for errors. If a 2nd user updates the same record in that millisecond between the get and save or if it would take longer for some weird reason, it would up the version and make the data in the first call invalid. TypeORM doesn't check the version value, so even if a call has a lower value than what is in the database, it still saves the data eventhough it should be seen as out of date.</p>
  <pre><code>1: User A checks latest version =&gt; TypeORM gives back the latest version: 1
  
  2: User B updates record =&gt; TypeORM ups the version: 2
  
  3: User A saves their data with version 1     &lt;-- This needs to validate the versions first.
  
  4: TypeORM  overwrites User B's record with User A's data
  </code></pre>
  <p>What I'm looking for is a way to make TypeORM decline step 3 as the latest version in the database is 2 and User A tries to save with version 1.</p>
  <p>I've tried using the querybuilder and update statements to make this work, but the build-in @VersionColumn only up the version on every <code>save()</code> call from a repository or entity manager.</p>
  <p>Besides this I also got a tip to look into database triggers, but as far as  I could find, this feature is <a href="https://github.com/typeorm/typeorm/issues/1082" rel="nofollow noreferrer">not yet supported</a> by TypeORM</p>
  <p>Here is an example of the setup:</p>
  <pre><code>async update(entity: Foo): Promise&lt;boolean&gt; {
  
    const value = await this._configurationRepository.save(entity);
  
    if (value === entity) {
      return true;
    }
  
    return false;
  }
  </code></pre>