til
til copied to clipboard
PostgreSQL - Fake data for testing
So many methods for fake data:
- SQL
- PL/pgSQL
- PL/Python
We have a table with schema.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE users (
id uuid NOT NULL,
email character varying DEFAULT ''::character varying NOT NULL,
encrypted_password character varying DEFAULT ''::character varying NOT NULL,
activated boolean,
created_at timestamp without time zone,
updated_at timestamp without time zone
);
I want to create many data for testing. We can use the loop function in plpgsql
DO $$
DECLARE
max_id bigint := 3000;
counter bigint := 0;
BEGIN
WHILE counter <= max_id LOOP
RAISE NOTICE 'INSERT fake data from % to %', counter, counter + 1;
INSERT INTO users (id, email, encrypted_password, activated, created_at, updated_at) VALUES (gen_random_uuid(), 'faker' || (SELECT floor(random()*(3000-1+1))+1) || '@meomeo.com', crypt('ahihi@123', gen_salt('bf')), True, (SELECT NOW()::timestamp), (SELECT NOW()::timestamp));
counter := counter + 1;
END LOOP;
RAISE NOTICE 'Total INSERT records: %', counter;
END
$$ LANGUAGE plpgsql;
CREATE TABLE heroes (
id SERIAL PRIMARY KEY,
name VARCHAR (50) NOT NULL,
description VARCHAR (255),
created_at timestamp without time zone NOT NULL DEFAULT NOW(),
updated_at timestamp without time zone NOT NULL DEFAULT NOW()
);
INSERT INTO heroes (name, description) SELECT (array['abaddon', 'alchemist', 'axe', 'bane', 'bristleback', 'brewmaster', 'huskar', 'mirana', 'snapfire', 'undying', 'windranger', 'zues', 'tiny'])[floor(random() * 13 + 1)], substr (md5 (random ()::text), 0, 255) FROM generate_series (1, 10);