Created
January 10, 2024 02:04
-
-
Save nyteshade/1519115f6f05794be85699e01afeff00 to your computer and use it in GitHub Desktop.
PostgreSQL URL Table With Computed Values
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
-- Drop existing trigger and function if they exist | |
DROP TRIGGER IF EXISTS trigger_before_insert_update_url_entry ON url_entries; | |
DROP FUNCTION IF EXISTS before_insert_url_entry(); | |
-- Drop the existing table if it exists | |
DROP TABLE IF EXISTS url_entries; | |
-- Create the new table | |
CREATE TABLE url_entries ( | |
id SERIAL PRIMARY KEY, | |
href TEXT NOT NULL, | |
name VARCHAR(255), | |
protocol TEXT, | |
username TEXT, | |
password TEXT, | |
host TEXT, | |
port TEXT, | |
pathname TEXT, | |
search TEXT, | |
hash TEXT, | |
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, | |
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP | |
); | |
-- Create the function for parsing URLs | |
CREATE OR REPLACE FUNCTION before_insert_url_entry() RETURNS TRIGGER AS $$ | |
DECLARE | |
v_regex_pattern CONSTANT text := '^([a-zA-Z][a-zA-Z0-9+\-.]*:)//(([^:/?#]+)(:([^:/?#]*))?@)?([^:/?#]+)(:(\d+))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$'; | |
v_matches text[]; | |
BEGIN | |
v_matches := regexp_matches(NEW.href, v_regex_pattern); | |
IF v_matches IS NOT NULL THEN | |
NEW.protocol := v_matches[1]; | |
NEW.username := v_matches[3]; | |
NEW.password := v_matches[5]; | |
NEW.host := v_matches[6]; | |
NEW.port := v_matches[8]; | |
NEW.pathname := v_matches[9]; | |
NEW.search := v_matches[10]; | |
NEW.hash := v_matches[11]; | |
END IF; | |
RETURN NEW; | |
END; | |
$$ LANGUAGE plpgsql; | |
-- Create the trigger | |
CREATE TRIGGER trigger_before_insert_update_url_entry | |
BEFORE INSERT OR UPDATE ON url_entries | |
FOR EACH ROW EXECUTE FUNCTION before_insert_url_entry(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment