Created
June 19, 2019 12:19
-
-
Save iaingray/82eec970886fd9bf30cd9b3837d64ad2 to your computer and use it in GitHub Desktop.
Redshift utility functions
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
-- Collection of functions to safely cast data from one type to another | |
-- Cast a VARCHAR to an INT and return NULL if it doesn't match accepted regexp | |
-- Prevents ETL dying due to data quality errors | |
-- Purpose: This UDF takes a VARCHAR argument, | |
-- and returns an INT, or NULL if regexp doesn't match accepted format for INT | |
-- Internal dependencies: None | |
-- External dependencies: None | |
-- 2019-16-19: written by Iain Gray | |
CREATE OR REPLACE FUNCTION f_sql_safe_cast_int(varchar) | |
RETURNS INT | |
IMMUTABLE | |
AS $$ | |
SELECT CASE | |
WHEN TRIM($1) ~ '^[0-9]+$' | |
THEN TRIM($1) | |
ELSE NULL END::INT | |
$$ | |
LANGUAGE SQL; | |
-- Purpose: This UDF takes a VARCHAR argument, | |
-- and returns a DATE, or NULL if if regexp doesn't match accepted format for DATE | |
-- NB DATE type is mutable so we can't use IMMUTABLE | |
-- Internal dependencies: None | |
-- External dependencies: None | |
-- 2019-16-19: written by Iain Gray | |
CREATE OR REPLACE FUNCTION f_sql_safe_cast_date(varchar) | |
RETURNS DATE | |
STABLE | |
AS $$ | |
SELECT CASE | |
WHEN TRIM($1) ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}' | |
THEN TRIM($1) | |
ELSE NULL END::DATE | |
$$ | |
LANGUAGE SQL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment