Quantcast
Viewing all articles
Browse latest Browse all 207

How to perform dummy multi-inserts with generate_series()?

Given the tables like this: https://dbfiddle.uk/Z8hOhnYG

CREATE TABLE accounts (  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,);CREATE TABLE profiles (  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY);CREATE TABLE account_profiles (  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,  account_id bigint NOT NULL REFERENCES accounts,  profile_id bigint NOT NULL REFERENCES profiles);

The requirements are:

  • every account must always have at least one profile tied to it.
  • therefore a new account must always create a new profile and add their relation row to the database
  • nothing is created when the entire operation fails for any reason.

So for the purpose of batching I'd like to write it as a multi-insert query and so I came up with this algorithm:

  1. create a series of IDs with the same length as the number of accounts
  2. add accounts
  3. join new accounts with the series
  4. add profiles
  5. join new profiles with the series
  6. join account and profile series tables on their series id and insert the result into the relations table
  7. return new accounts

Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>