Created
May 25, 2023 09:31
-
-
Save samuelchanx/112be1f662fba44dfd1133262409dcea to your computer and use it in GitHub Desktop.
Create #SQL function based on input for loalization computed field
This file contains hidden or 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
| function generateSQLFunction(schemaName, tableName, columnName, isNullable) { | |
| const nonNullableScript = `CREATE OR REPLACE FUNCTION ${schemaName}.${tableName}_${columnName}(data_row ${schemaName}.${tableName}, hasura_session json) | |
| RETURNS text | |
| LANGUAGE sql | |
| STABLE | |
| AS | |
| $function$ | |
| SELECT CASE | |
| WHEN (hasura_session ->> 'x-hasura-preferred-lang' = 'en') THEN data_row."${columnName}En" | |
| WHEN (hasura_session ->> 'x-hasura-preferred-lang' = 'zh_HK') THEN data_row."${columnName}Zh" | |
| ELSE data_row."${columnName}Zh" | |
| END; | |
| $function$`; | |
| const nullableScript = `CREATE OR REPLACE FUNCTION ${schemaName}.${tableName}_${columnName}(data_row ${schemaName}.${tableName}, hasura_session json) | |
| RETURNS text | |
| LANGUAGE sql | |
| STABLE | |
| AS | |
| $function$ | |
| SELECT CASE | |
| WHEN (hasura_session ->> 'x-hasura-preferred-lang' = 'en') AND (data_row."${columnName}En" IS NOT NULL) | |
| THEN data_row."${columnName}En" | |
| WHEN (hasura_session ->> 'x-hasura-preferred-lang' = 'zh_HK') AND | |
| (data_row."${columnName}Zh" IS NOT NULL) THEN data_row."${columnName}Zh" | |
| ELSE COALESCE(COALESCE(data_row."${columnName}Zh", data_row."${columnName}En"), '') | |
| END; | |
| $function$`; | |
| return isNullable ? nullableScript : nonNullableScript; | |
| } | |
| // Example usage | |
| const schemaName = 'shop'; | |
| const tableName = 'promotion'; | |
| const columnName = 'title'; | |
| const isNullable = false; | |
| const sqlFunctionScript = generateSQLFunction(schemaName, tableName, columnName, isNullable); | |
| console.log(sqlFunctionScript); | |
| pbcopy(sqlFunctionScript); | |
| function pbcopy(data) { | |
| var proc = require('child_process').spawn('pbcopy'); | |
| proc.stdin.write(data); proc.stdin.end(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment