How to Handle Trigger-Based Duplicates in Snaplet? #29603
Unanswered
yilverdeja
asked this question in
Questions
Replies: 1 comment
-
Rather than manually updating the command into an upsert, this is how I updated it in my import { createSeedClient, MinMaxOption } from '@snaplet/seed';
import { copycat } from '@snaplet/copycat';
import capcon from 'capture-console';
// Updates the INSERT to public users as an UPSERT to avoid duplicated keys issue
function processOutput(output: string) {
return output
.split('\r\n')
.map((o) => {
const trimmed = o.trim();
if (trimmed.startsWith('INSERT INTO public.users')) {
return (
trimmed.substring(0, trimmed.length - 1) +
'ON CONFLICT(id) DO UPDATE SET name = EXCLUDED.name
);
}
return trimmed;
})
.join('\r\n');
}
const main = async () => {
// start intercepting and capturing stdout
let output = '';
capcon.startCapture(process.stdout, { quiet: true }, (stdout) => {
output += stdout.toString();
});
// With DryRun set to True, the Seed Client will not execute any database operations, it will log the generated SQL queries to stdout instead
const seed = await createSeedClient({ dryRun: true, connect: true });
// Sample seeding that inserts auth_users, public_users and posts - for example purposes haven't tested it here
await seed.public_users((x) => x(3, ({index}) =>({
name: `Name ${index}`,
posts: (y) => y(5),
})))
// stops capturing from stdout
capcon.stopCapture(process.stdout);
// Process and log the new captured output to stdout
const processedOutput = processOutput(output);
console.log(processedOutput);
process.exit();
};
main(); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm new to using Supabase and Snaplet, and I'm facing a challenge while setting up a local development environment in collaboration with an external company. It seems there might be a configuration issue related to database seeding.
Issue
I'm working with a project that has two user tables:
auth.users
andpublic.users
. Our setup is designed such that an insert intoauth.users
automatically triggers an insert intopublic.users
using the sameuser_id
. However, when I try to create a record inpublic.post
, which referencesuser_id
, it generates a duplicate key error inpublic.users
.Configuration
Sample Seed Script
Running the generated sql causes a duplicate key error since the insert into
public.users
is happening twice:auth.users
is createdINSERT into public.users
is executed.Quick Solution
As I want to be able to set some of the values of
public.users
, I'm adapting theINSERT INTO public.users
line into an upsert:Questions
public.users
?auth.users
during the seed script execution?Beta Was this translation helpful? Give feedback.
All reactions