Created
May 20, 2023 12:55
-
-
Save FazelMan/55808566a5f46f2258f2126df20f16ea to your computer and use it in GitHub Desktop.
Rename PascalCase tables and columns to snake_case in PostgreSQL
This file contains 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
-- Rename tables | |
DO $$ | |
DECLARE | |
table_record RECORD; | |
BEGIN | |
-- Loop through each table | |
FOR table_record IN (SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE') LOOP | |
EXECUTE FORMAT('ALTER TABLE public.%I RENAME TO %I', table_record.table_name, lower(regexp_replace(table_record.table_name, '(.)([A-Z])', '\1_\2', 'g'))); | |
END LOOP; | |
END $$; | |
-- Rename columns | |
DO $$ | |
DECLARE | |
table_record RECORD; | |
column_record RECORD; | |
BEGIN | |
-- Loop through each table | |
FOR table_record IN (SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE') LOOP | |
-- Loop through each column in the table | |
FOR column_record IN (SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = table_record.table_name) LOOP | |
EXECUTE FORMAT('ALTER TABLE public.%I RENAME COLUMN %I TO %I', table_record.table_name, column_record.column_name, lower(regexp_replace(column_record.column_name, '(.)([A-Z])', '\1_\2', 'g'))); | |
END LOOP; | |
END LOOP; | |
END $$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment