Last active
January 6, 2023 22:08
-
-
Save stephanGarland/d9efbd5ffcbaabedc2c8171d783cebeb to your computer and use it in GitHub Desktop.
MySQL stored procedure to generate 1E6 rows from another table - horrible performance, would not recommend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DELIMITER // -- This is needed so that the individual commands don't end the stored procedure | |
CREATE PROCEDURE insert_zaps(IN num_rows int, IN pct_shared float) -- Two input args are needed | |
BEGIN | |
DECLARE loop_count bigint; -- Variables are initialized with a type | |
DECLARE len_table bigint; | |
DECLARE rand_base float; | |
DECLARE rand_offset float; | |
DECLARE rand_ts timestamp; | |
DECLARE rand_user bigint; | |
DECLARE shared_with_user bigint; | |
SELECT id INTO len_table FROM test.ref_users ORDER BY id DESC LIMIT 1; -- SELECT INTO can be used | |
SET loop_count = 1; -- Or, if the value is simple, simply assigned | |
WHILE loop_count <= num_rows DO | |
SET rand_base = RAND(); | |
SET rand_offset = RAND(); | |
SET rand_ts = TIMESTAMP( | |
FROM_UNIXTIME( | |
UNIX_TIMESTAMP(NOW()) - FLOOR( | |
0 + ( | |
RAND() * 86400 * 365 * 10 | |
) | |
) | |
) | |
); -- This creates a random timestamp between now and 10 years ago | |
WITH rand AS ( | |
SELECT | |
FLOOR( | |
( | |
SELECT | |
rand_base * len_table | |
) | |
) | |
) | |
SELECT | |
id | |
INTO rand_user | |
FROM | |
test.ref_users | |
WHERE | |
id IN (TABLE rand); -- This is the CTE demonstrated earlier to determine the table length | |
INSERT INTO zaps (zap_id, created_at, owned_by) VALUES (loop_count, rand_ts, rand_user); | |
IF ROUND(rand_base, 1) > (1 - pct_shared) THEN -- Roughly determine the amount of shared Zaps | |
SELECT CAST(FLOOR(rand_base * rand_offset * len_table) AS unsigned) INTO shared_with_user; | |
UPDATE | |
zaps | |
SET | |
shared_with = JSON_ARRAY_APPEND( | |
shared_with, | |
'$', | |
shared_with_user | |
) -- JSON_ARRAY_APPEND(array, key, value) | |
WHERE | |
id = loop_count; | |
END IF; | |
SET loop_count = loop_count + 1; | |
END WHILE; | |
END // | |
DELIMITER ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment