Last active
July 19, 2021 08:10
-
-
Save andrewp-as-is/ecbb87a71c2875af7036a12731a9aa7a to your computer and use it in GitHub Desktop.
postgres select basename
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
CREATE OR REPLACE FUNCTION basename(path text) RETURNS text AS $$ | |
SELECT reverse((regexp_split_to_array(reverse($1), '/'))[1]) | |
$$ | |
LANGUAGE SQL IMMUTABLE; | |
SELECT basename('/Users/username/git/owner/repo'); | |
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
CREATE TABLE t( | |
path text PRIMARY KEY, | |
basename text | |
); | |
CREATE OR REPLACE FUNCTION basename(path text) RETURNS text AS $$ | |
SELECT reverse((regexp_split_to_array(reverse($1), '/'))[1]) | |
$$ | |
LANGUAGE SQL IMMUTABLE; | |
CREATE OR REPLACE FUNCTION update() | |
RETURNS trigger AS | |
$BODY$ | |
BEGIN | |
NEW.basename:=basename(NEW.path); | |
RETURN NEW; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE; | |
DROP TRIGGER IF EXISTS update ON t CASCADE; | |
CREATE TRIGGER update | |
BEFORE INSERT OR UPDATE ON t | |
FOR EACH ROW | |
EXECUTE PROCEDURE update(); | |
INSERT INTO t(path) VALUES ('path/to/file.txt'), ('path/to/image.png'); | |
SELECT * FROM t; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment