Skip to content

Instantly share code, notes, and snippets.

@rallisf1
Forked from kez/slugify.sql
Last active August 11, 2023 21:46
Show Gist options
  • Save rallisf1/679216d8842e06074025c612b3951bd6 to your computer and use it in GitHub Desktop.
Save rallisf1/679216d8842e06074025c612b3951bd6 to your computer and use it in GitHub Desktop.
Generating Slugs in Postgres
CREATE EXTENSION IF NOT EXISTS "unaccent";
CREATE OR REPLACE FUNCTION slugify(t text) RETURNS text
AS $$
BEGIN
t := lower(t);
-- german
t := replace(t, 'ä', 'ae');
t := replace(t, 'ö', 'oe');
t := replace(t, 'ü', 'ue');
t := unaccent(t);
-- cyrillic
t := replace( replace( replace( replace(
replace( replace( replace( replace( translate(t,
'абвгдезийклмнопрстуфхцэы', 'abvgdezijklmnoprstufхcey'), 'ж', 'zh'),
'ч', 'ch'), 'ш', 'sh'), 'щ', 'shh'), 'ъ', ''), 'ю', 'yu'), 'я', 'ya'), 'ь', '');
-- greek
t := replace(t, 'ει', 'i');
t := replace(t, 'οι', 'i');
t := replace(t, 'θ', 'th');
t := replace(t, 'ξ', 'ks');
t := replace(t, 'χ', 'ch');
t := translate(t, 'αβγδεζηικλμνοπρσςτυφω','abgdeziiklmnoprsstyfo');
-- remove symbols
t := regexp_replace(t, '[''"]+', '', 'gi');
t := regexp_replace(t, '[^a-z0-9\\-_]+', '-', 'gi');
t := regexp_replace(t, '\-+$', '');
t := regexp_replace(t, '^\-', '');
RETURN t;
END;
$$ LANGUAGE plpgsql STRICT IMMUTABLE PARALLEL SAFE;
CREATE FUNCTION public.set_slug_from_name() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
NEW.slug := slugify(NEW.name);
RETURN NEW;
END
$$;
CREATE TRIGGER "trg_slug_insert"
BEFORE INSERT ON "my_table_name"
FOR EACH ROW
WHEN (NEW.name IS NOT NULL AND NEW.slug IS NULL)
EXECUTE PROCEDURE set_slug_from_name();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment