Guest User

Untitled

a guest
Jun 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. -- "title" column should be in table which will be converted to slug.
  2. -- Add column "slug" varchar unique null in table.
  3.  
  4.  
  5. -- FUNCTION TO CREATE SLUG
  6. -- also takes unicode
  7.  
  8. CREATE OR REPLACE FUNCTION public.slugify(title_text character varying)
  9. RETURNS character varying
  10. AS $function$
  11. DECLARE
  12. result varchar;
  13. BEGIN
  14. result := replace(title_text, '?', '');
  15. result := replace(result , ':', '');
  16. result := replace(result , '.', '');
  17. result := replace(result , '“', '');
  18. result := replace(result , '”', '');
  19. result := replace(result , '"', '');
  20. result := replace(result , ')', '');
  21. result := replace(result , '(', '');
  22. result := replace(result , ',', '');
  23. result := replace(result , '\', ' ');
  24. result := replace(result , '/', ' ');
  25. result := regexp_replace(replace(lower(result), ' ', '-'), E'[^\\w[[:alpha:]] -', '#', 'g');
  26. RETURN result;
  27. end
  28. $function$
  29. LANGUAGE 'plpgsql'
  30.  
  31.  
  32.  
  33. -- FUNCTION TO GET UNIQUE SLUG
  34. create or replace function slugify_on_insert()
  35. returns trigger as
  36. $$
  37. DECLARE
  38. slug_text varchar;
  39. res varchar;
  40. temp_text varchar;
  41. c integer;
  42. done boolean;
  43. begin
  44. slug_text := slugify(new.title);
  45. temp_text := slug_text;
  46. c := 1;
  47. done := false;
  48. while not done loop
  49. EXECUTE format('SELECT * FROM %I '
  50. 'WHERE slug = $1', TG_TABLE_NAME)
  51. INTO res
  52. USING temp_text;
  53. if res is not null then
  54. c := c+1;
  55. temp_text = slug_text || '-' || c;
  56. done := false;
  57. else
  58. if c > 1 then
  59. slug_text := slug_text || '-' || c;
  60. end if;
  61. done := true;
  62. end if;
  63. end loop;
  64.  
  65. new.slug = slug_text;
  66. Return new;
  67. end
  68. $$
  69. language 'plpgsql'
  70.  
  71. -- TRIGGER ON INSERT
  72. create trigger before_insert_trigger
  73. before insert on table_name
  74. for each row
  75. execute procedure slugify_on_insert()
Add Comment
Please, Sign In to add comment