Skip to content

Instantly share code, notes, and snippets.

@bjeanes
Last active May 31, 2016 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjeanes/aba48fd363c74dbc7e6ab27561e96d89 to your computer and use it in GitHub Desktop.
Save bjeanes/aba48fd363c74dbc7e6ab27561e96d89 to your computer and use it in GitHub Desktop.
QUery to find all `varchar` columns in the database and return query strings that can be run to change them to `text` types Raw
WITH targets AS (
SELECT 'ALTER TABLE "'||table_name||'"' as "table",
string_agg(
'ALTER COLUMN "'||column_name||'" TYPE text'||CASE
WHEN character_maximum_length IS NULL THEN ''
WHEN character_maximum_length >= 255 THEN ''
ELSE
E',\n ADD CONSTRAINT '||column_name||E'_length \n '||
'CHECK (LENGTH("'||column_name||'") <= '||character_maximum_length||') '||
'NOT VALID'
END
, E',\n ' ORDER BY column_name) as "changes"
FROM information_schema.columns
WHERE table_schema = 'public'
AND data_type = 'character varying'
GROUP BY 1
ORDER BY 1
)
SELECT "table" || E'\n ' || "changes" || E';\n' as query
FROM targets
;
ALTER TABLE "users"
ALTER COLUMN "email" TYPE text,
ALTER COLUMN "encrypted_password" TYPE text,
ADD CONSTRAINT encrypted_password_length
CHECK (LENGTH("encrypted_password") <= 128) NOT VALID,
ALTER COLUMN "first_name" TYPE text,
ALTER COLUMN "last_name" TYPE text,
ALTER COLUMN "salt" TYPE text,
ADD CONSTRAINT salt_length
CHECK (LENGTH("salt") <= 128) NOT VALID,
ALTER COLUMN "title" TYPE text;
-- ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment