Skip to content

Instantly share code, notes, and snippets.

@adosib
Last active December 20, 2024 13:33
Show Gist options
  • Save adosib/98873c0c5ffc9a241433c9376c872fc2 to your computer and use it in GitHub Desktop.
Save adosib/98873c0c5ffc9a241433c9376c872fc2 to your computer and use it in GitHub Desktop.
INITCAP function (macro) for DuckDB
/*
Not thoroughly tested. DuckDB version used: 1.0.0
Won't work on NULLs, so input should be coalesced first.
I make no guarantees that this function will produce output equivalent to Postgres' INITCAP function.
Examples:
select INITCAP('do androids dream of electronic sheep?') => 'Do Androids Dream Of Electronic Sheep?'
select INITCAP('dJ D-wayne megens') => 'Dj D-Wayne Megens'
select INITCAP('Sa''ar 5-class corvette') => 'Sa'Ar 5-Class Corvette
select INITCAP(NULL) => SQL Error: Parameter Not Allowed Error: Cannot perform list_reduce on an empty input list
select INITCAP(coalesce(NULL, '')) => ''
*/
CREATE OR REPLACE MACRO CAP(s) AS UPPER(s[1])||LOWER(s[2:]);
CREATE OR REPLACE MACRO INITCAP(s) AS
(WITH cte AS (
SELECT regexp_split_to_array(s, '[^A-Za-z]+') chars,
regexp_split_to_array(s, '[A-Za-z]+') nonchars
)
SELECT list_reduce(
[COALESCE(x[1], '')||CAP(COALESCE(x[2], '')) for x in zipped],
(x, y) -> x||y
)
FROM (SELECT list_zip(nonchars, chars) FROM cte) t(zipped)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment