In this post we are going to cover JavaScript UDFs in Snowflake.
A SQL function body is one expression. A JavaScript body is real code: it can have variables, loops, branches and a try/catch in it. You write LANGUAGE JAVASCRIPT, put the code between dollar signs, and call the function from SQL like any other.
But before any of your JavaScript runs, Snowflake decides what the argument is called and what type it arrives as. Both of those bite, and neither of them bites at create time.
We will start with the smallest function there is and build it up step by step. Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 143 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's write the smallest JavaScript function there is
- Now the first trap: what is the argument called?
- Now the second trap: what type does it arrive as?
- So let's declare it FLOAT and see what that costs
- The way round it is text
- Now the reason you would reach for JavaScript
- Let's run one over the table
- What comes back when the body does not return a number?
- And what happens when the body throws?
- The null clause, which behaves differently from last episode
- VARIANT, in both directions
- What a JavaScript UDF cannot do, and when it finds out
- One last thing: a JavaScript table function
- And the teardown
Let's create some sample data
A small table to run the functions over later. One row has a NULL amount, on purpose.
-- Sample data for this post.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE SALES_T143 (
SALE_ID INT,
REGION VARCHAR(10),
AMOUNT NUMBER(10,2)
);
INSERT INTO SALES_T143 (SALE_ID, REGION, AMOUNT) VALUES
(1, 'north', 95.00), (2, 'south', 75.00), (3, 'east', 55.00),
(4, 'west', 10.00), (5, 'north', NULL);INSERT INTO SALES_T143 (SALE_ID, REGION, AMOUNT)
VALUES (1, 'north', 95.00), (2, 'south', 75.00),
(3, 'east', 55.00), (4, 'west', 10.00),
(5, 'north', NULL);| number of rows inserted |
|---|
| 5 |
Five rows, and one missing amount.
Let's write the smallest JavaScript function there is
Notice the argument is declared FLOAT, and so is the return. We come back to why in a minute.
CREATE OR REPLACE FUNCTION DOUBLE_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return N * 2;
$$;| status |
|---|
| Function DOUBLE_T143 successfully created. |
Created. Three calls: one doubled, zero doubled, and a negative.
SELECT DOUBLE_T143(21) AS TWENTY_ONE_DOUBLED,
DOUBLE_T143(0) AS NOTHING_DOUBLED,
DOUBLE_T143(-1.5) AS A_NEGATIVE_DOUBLED;| TWENTY_ONE_DOUBLED | NOTHING_DOUBLED | A_NEGATIVE_DOUBLED |
|---|---|---|
| 42.0 | 0.0 | -3.0 |
42.0, not 42. A JavaScript UDF hands back a float, and the result shows it.
And the catalog knows what language it is.
SELECT FUNCTION_NAME,
ARGUMENT_SIGNATURE,
DATA_TYPE,
FUNCTION_LANGUAGE
FROM INFORMATION_SCHEMA.FUNCTIONS
WHERE FUNCTION_SCHEMA = 'PUBLIC'
AND ENDSWITH(FUNCTION_NAME, '_T143')
ORDER BY FUNCTION_NAME;| FUNCTION_NAME | ARGUMENT_SIGNATURE | DATA_TYPE | FUNCTION_LANGUAGE |
|---|---|---|---|
| DOUBLE_T143 | (N FLOAT) | FLOAT | JAVASCRIPT |
JAVASCRIPT, right there beside the signature and the return type.
Now the first trap: what is the argument called?
Here the SQL argument is lower case amount and the body says amount too. They match. Let's see what happens.
CREATE OR REPLACE FUNCTION LOWERARG_T143(amount FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return amount * 2;
$$;| status |
|---|
| Function LOWERARG_T143 successfully created. |
Created without a complaint. So let's call it.
SELECT LOWERARG_T143(10) AS WHAT_CAME_BACK;100132 (P0000): JavaScript execution error: Uncaught ReferenceError: amount is not defined in LOWERARG_T143 at ' return amount * 2;' position 4 stackstrace: LOWERARG_T143 line: 2
100132, a reference error. amount is not defined.
Here is the same declaration with a body that shouts the name instead.
CREATE OR REPLACE FUNCTION UPPERARG_T143(amount FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return AMOUNT * 2;
$$;| status |
|---|
| Function UPPERARG_T143 successfully created. |
SELECT UPPERARG_T143(10) AS WHAT_CAME_BACK;| WHAT_CAME_BACK |
|---|
| 20.0 |
20.0. That one works.
So an unquoted SQL identifier is folded to upper case before JavaScript ever sees it. And JavaScript is case sensitive. Which leaves one more option: quote the argument in the declaration.
CREATE OR REPLACE FUNCTION QUOTEDARG_T143("amount" FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return amount * 2;
$$;| status |
|---|
| Function QUOTEDARG_T143 successfully created. |
SELECT QUOTEDARG_T143(10) AS WHAT_CAME_BACK;| WHAT_CAME_BACK |
|---|
| 20.0 |
20.0 again. So shout it in the body, or quote it in the declaration. Pick one.
The version that does neither is created happily and fails only when somebody calls it. Nothing at create time looks at the names in your body at all.
That is the shape of almost every mistake in this episode.
Now the second trap: what type does it arrive as?
First, the number that matters. This is the largest integer a JavaScript number holds exactly.
SELECT 9007199254740991 AS TWO_TO_THE_FIFTY_THREE_MINUS_ONE;| TWO_TO_THE_FIFTY_THREE_MINUS_ONE |
|---|
| 9007199254740991 |
So let's write a function that takes a NUMBER(38,0) and hands it straight back, and see how it copes.
CREATE OR REPLACE FUNCTION ECHO_T143(N NUMBER(38,0))
RETURNS NUMBER(38,0)
LANGUAGE JAVASCRIPT
AS
$$
return N;
$$;090215 (42601): Language JAVASCRIPT does not support type 'NUMBER(38,0)' for argument or return type.
090215. Language JavaScript does not support that type, for an argument or for a return. The function was never created at all, which we can prove by calling it.
SELECT ECHO_T143(9007199254740991) AS WENT_IN_AND_CAME_BACK;002139 (02000): SQL compilation error: Unknown function ECHO_T143.
Unknown function. Every other call to that name in the demo script came back the same way, so none of them tell us anything new and none of them are on this page.
Now that message named one specific type, so the obvious question is how far it goes. A narrower number first.
CREATE OR REPLACE FUNCTION NARROW_T143B(N NUMBER(10,2))
RETURNS NUMBER(10,2)
LANGUAGE JAVASCRIPT
AS
$$
return N;
$$;090215 (42601): Language JAVASCRIPT does not support type 'NUMBER(10,2)' for argument or return type.
Refused as well, and named as the narrow type this time. A plain INT next.
CREATE OR REPLACE FUNCTION PLAININT_T143B(N INT)
RETURNS INT
LANGUAGE JAVASCRIPT
AS
$$
return N;
$$;090215 (42601): Language JAVASCRIPT does not support type 'NUMBER(38,0)' for argument or return type.
And a NUMBER with no precision written at all.
CREATE OR REPLACE FUNCTION BARENUM_T143B(N NUMBER)
RETURNS NUMBER
LANGUAGE JAVASCRIPT
AS
$$
return N;
$$;090215 (42601): Language JAVASCRIPT does not support type 'NUMBER(38,0)' for argument or return type.
Both refused, and both reported as the same wide type, because that is what Snowflake expands them to.
SHOW USER FUNCTIONS LIKE '%\\_T143B';| created_on | name | schema_name | is_builtin | is_aggregate | is_ansi | min_num_arguments | max_num_arguments | arguments | description | catalog_name | is_table_function | valid_for_clustering | is_secure | secrets | external_access_integrations | is_external_function | language | is_memoizable | is_data_metric | is_ai_function |
|---|
Nothing. No rows. All three refusals were refusals.
So JavaScript takes no NUMBER type at all. Not a wide one, not a narrow one, not INT.
Your choices are FLOAT, VARCHAR and VARIANT. That is why the first function in this post declared FLOAT.
So let's declare it FLOAT and see what that costs
Two functions this time, so we have something to compare against. The same echo in JavaScript with a FLOAT argument, and one in plain SQL that can take the wide number.
CREATE OR REPLACE FUNCTION ECHO_T143B(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return N;
$$;| status |
|---|
| Function ECHO_T143B successfully created. |
CREATE OR REPLACE FUNCTION SQLECHO_T143B(N NUMBER(38,0))
RETURNS NUMBER(38,0)
AS
$$
N
$$;| status |
|---|
| Function SQLECHO_T143B successfully created. |
Let's send in the largest safe integer.
SELECT 9007199254740991 AS WHAT_I_SENT,
ECHO_T143B(9007199254740991) AS WHAT_CAME_BACK;| WHAT_I_SENT | WHAT_CAME_BACK |
|---|---|
| 9007199254740991 | 9007199254740991.0 |
It came back exactly, with a .0 on the end because the return type is a float. Now the very next odd integer above it.
SELECT 9007199254740993 AS WHAT_I_SENT,
ECHO_T143B(9007199254740993) AS WHAT_CAME_BACK;| WHAT_I_SENT | WHAT_CAME_BACK |
|---|---|
| 9007199254740993 | 9007199254740992.0 |
Read the two cells against each other. What went in ends in a three. What came back ends in a two. The function did nothing but hand the number back, and the number changed on the way through.
And here is the same number through both functions, side by side in one grid.
SELECT SQLECHO_T143B(9007199254740993) AS THROUGH_A_SQL_FUNCTION,
ECHO_T143B(9007199254740993) AS THROUGH_A_JAVASCRIPT_ONE;| THROUGH_A_SQL_FUNCTION | THROUGH_A_JAVASCRIPT_ONE |
|---|---|
| 9007199254740993 | 9007199254740992.0 |
The SQL one is exact. The JavaScript one is one lower. Same account, same query, same number. That is the whole finding.
Let's try a number far too big for a float to hold at all.
SELECT 123456789012345678901234567890 AS WHAT_I_SENT,
ECHO_T143B(123456789012345678901234567890) AS WHAT_CAME_BACK;| WHAT_I_SENT | WHAT_CAME_BACK |
|---|---|
| 123456789012345678901234567890 | 1.2345678901234568e+29 |
Scientific notation, with the tail of the number gone. And through the SQL function?
SELECT SQLECHO_T143B(123456789012345678901234567890) AS THROUGH_A_SQL_FUNCTION;| THROUGH_A_SQL_FUNCTION |
|---|
| 123456789012345678901234567890 |
Every digit, intact.
And one honest caveat
I also wrote a subtraction, to put a number on the loss.
SELECT 9007199254740993 AS WHAT_I_SENT,
ECHO_T143B(9007199254740993) AS WHAT_CAME_BACK,
9007199254740993 - ECHO_T143B(9007199254740993) AS THE_DIFFERENCE;| WHAT_I_SENT | WHAT_CAME_BACK | THE_DIFFERENCE |
|---|---|---|
| 9007199254740993 | 9007199254740992.0 | 0.0 |
The difference column reads 0.0, which is wrong, and it is my mistake. The subtraction was done in floating point as well, so it cannot see the gap it is supposed to be measuring.
Look at that grid again. The first two columns disagree with each other, and the third column says they do not. The side-by-side grid above is the evidence here. My difference column is not, and it is on the page so you can see why that kind of check does not work.
The way round it is text
If the number matters, do not let it be a number on the way in. Let's hand JavaScript a string and take a string back.
CREATE OR REPLACE FUNCTION STRECHO_T143(N VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
return N;
$$;| status |
|---|
| Function STRECHO_T143 successfully created. |
SELECT STRECHO_T143('9007199254740993') AS SENT_AS_TEXT;| SENT_AS_TEXT |
|---|
| 9007199254740993 |
Intact. Every digit. Nothing happened to it, because nothing treated it as a number.
And we can do arithmetic on it too, with BigInt.
CREATE OR REPLACE FUNCTION STRADD_T143B(N VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
return BigInt(N) + 1n + '';
$$;| status |
|---|
| Function STRADD_T143B successfully created. |
SELECT '9007199254740993' AS WHAT_I_SENT,
STRADD_T143B('9007199254740993') AS PLUS_ONE_IN_JAVASCRIPT;| WHAT_I_SENT | PLUS_ONE_IN_JAVASCRIPT |
|---|---|
| 9007199254740993 | 9007199254740994 |
One more than what we sent, exactly. Not one more than the nearest float.
SELECT STRADD_T143B('123456789012345678901234567890') AS PLUS_ONE_IN_JAVASCRIPT;| PLUS_ONE_IN_JAVASCRIPT |
|---|
| 123456789012345678901234567891 |
Also exact, on a number a float could not hold at all.
Now the reason you would reach for JavaScript
An array, a for loop, an if and four returns. None of that is possible in a SQL function body, because a SQL body is one expression.
CREATE OR REPLACE FUNCTION GRADE_T143(SCORE FLOAT)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
var bands = [[90, 'excellent'], [70, 'good'], [50, 'fair']];
for (var i = 0; i < bands.length; i++) {
if (SCORE >= bands[i][0]) {
return bands[i][1];
}
}
return 'poor';
$$;| status |
|---|
| Function GRADE_T143 successfully created. |
SELECT GRADE_T143(95) AS NINETY_FIVE,
GRADE_T143(75) AS SEVENTY_FIVE,
GRADE_T143(55) AS FIFTY_FIVE,
GRADE_T143(10) AS TEN;| NINETY_FIVE | SEVENTY_FIVE | FIFTY_FIVE | TEN |
|---|---|---|---|
| excellent | good | fair | poor |
The loop ran and the branch chose, four times over.
And a try/catch, which is the other thing you cannot do in SQL.
CREATE OR REPLACE FUNCTION SAFE_PARSE_T143(S VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
try {
var o = JSON.parse(S);
return 'parsed, and it has ' + Object.keys(o).length + ' keys';
} catch (e) {
return 'could not parse it: ' + e.name;
}
$$;| status |
|---|
| Function SAFE_PARSE_T143 successfully created. |
SELECT SAFE_PARSE_T143('{"a":1,"b":2}') AS GOOD_INPUT,
SAFE_PARSE_T143('not json') AS BAD_INPUT;| GOOD_INPUT | BAD_INPUT |
|---|---|
| parsed, and it has 2 keys | could not parse it: SyntaxError |
Parsed, with its key count. Then caught, with the name of JavaScript's own exception in the message. The function did not fail. It handled it.
Let's run one over the table
SELECT SALE_ID,
AMOUNT,
GRADE_T143(AMOUNT) AS THE_GRADE
FROM SALES_T143
ORDER BY SALE_ID;| SALE_ID | AMOUNT | THE_GRADE |
|---|---|---|
| 1 | 95.00 | excellent |
| 2 | 75.00 | good |
| 3 | 55.00 | fair |
| 4 | 10.00 | poor |
| 5 | NULL | poor |
Five rows, graded. And look at the row with no amount. It came back poor, not NULL, because undefined is not greater than any of the three bands and the loop fell through to the last return.
And in a WHERE clause, Snowflake runs it to decide which rows to keep.
SELECT SALE_ID, AMOUNT
FROM SALES_T143
WHERE GRADE_T143(AMOUNT) IN ('excellent', 'good')
ORDER BY SALE_ID;| SALE_ID | AMOUNT |
|---|---|
| 1 | 95.00 |
| 2 | 75.00 |
Two rows, chosen by JavaScript.
What comes back when the body does not return a number?
Three cases. First, a body that computes something and never returns it.
CREATE OR REPLACE FUNCTION RETURNSNOTHING_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
var x = N * 2;
$$;| status |
|---|
| Function RETURNSNOTHING_T143 successfully created. |
SELECT RETURNSNOTHING_T143(5) AS WHAT_CAME_BACK,
RETURNSNOTHING_T143(5) IS NULL AS IS_IT_NULL;| WHAT_CAME_BACK | IS_IT_NULL |
|---|---|
| NULL | TRUE |
A real NULL, and IS NULL says TRUE. Falling off the end of the function gives you a null.
Now one that returns JavaScript's own null, and one that returns zero divided by zero.
CREATE OR REPLACE FUNCTION RETURNSNULL_T143()
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return null;
$$;| status |
|---|
| Function RETURNSNULL_T143 successfully created. |
CREATE OR REPLACE FUNCTION RETURNSNAN_T143()
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return 0 / 0;
$$;| status |
|---|
| Function RETURNSNAN_T143 successfully created. |
SELECT RETURNSNULL_T143() AS THE_NULL_ONE,
RETURNSNAN_T143() AS THE_NAN_ONE;| THE_NULL_ONE | THE_NAN_ONE |
|---|---|
| NULL | nan |
Two different kinds of answer in one grid. The first cell is a real SQL NULL. The second is the four characters nan, sitting in a column declared FLOAT.
And what happens when the body throws?
CREATE OR REPLACE FUNCTION THROWS_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
if (N < 0) {
throw "I will not take a negative number";
}
return Math.sqrt(N);
$$;| status |
|---|
| Function THROWS_T143 successfully created. |
First the path that does not throw.
SELECT THROWS_T143(16) AS SIXTEEN_ROOTED;| SIXTEEN_ROOTED |
|---|
| 4.0 |
4.0. Now the one that does.
SELECT THROWS_T143(-1) AS A_NEGATIVE;100132 (P0000): JavaScript execution error: Uncaught I will not take a negative number in THROWS_T143 at ' throw "I will not take a negative number";' position 8 stackstrace: THROWS_T143 line: 3
100132, and read the pane. Our own message is in there, word for word, with the function name and the line it came from.
So a thrown string comes back to SQL inside Snowflake's own error wrapper. Which makes a thrown message a genuinely useful place to say what went wrong.
The null clause, which behaves differently from last episode
Two functions, identical apart from the strictness clause, with bodies that report what they saw.
CREATE OR REPLACE FUNCTION CALLED_T143(N FLOAT)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
CALLED ON NULL INPUT
AS
$$
if (N === null) { return 'the body ran and N was null'; }
if (N === undefined) { return 'the body ran and N was undefined'; }
return 'the body ran and N was ' + N;
$$;| status |
|---|
| Function CALLED_T143 successfully created. |
CREATE OR REPLACE FUNCTION STRICT_T143(N FLOAT)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
RETURNS NULL ON NULL INPUT
AS
$$
if (N === null) { return 'the body ran and N was null'; }
return 'the body ran and N was ' + N;
$$;| status |
|---|
| Function STRICT_T143 successfully created. |
With a three first.
SELECT CALLED_T143(3) AS THE_CALLED_ONE,
STRICT_T143(3) AS THE_STRICT_ONE;| THE_CALLED_ONE | THE_STRICT_ONE |
|---|---|
| the body ran and N was 3 | the body ran and N was 3 |
Both ran and both saw a three. No surprise. Now with a NULL.
SELECT CALLED_T143(NULL) AS THE_CALLED_ONE,
STRICT_T143(NULL) AS THE_STRICT_ONE;| THE_CALLED_ONE | THE_STRICT_ONE |
|---|---|
| the body ran and N was undefined | NULL |
Two different things happened. The first one ran, and it saw undefined. Not null. undefined.
The second one returned a NULL and never ran at all. The clause is honoured here.
Episode 141 ran this identical experiment on a SQL UDF. There, RETURNS NULL ON NULL INPUT was recorded in the catalog and not honoured, and both bodies ran.
Same account, same version, two languages, two answers. So this is a property of the language, not of Snowflake in general.
VARIANT, in both directions
A VARIANT argument, with a body that reports what JavaScript made of it.
CREATE OR REPLACE FUNCTION INSIDE_T143(DOC VARIANT)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
if (DOC === null) { return 'nothing came in'; }
return 'a ' + (typeof DOC) + ' with keys: ' + Object.keys(DOC).join(',');
$$;| status |
|---|
| Function INSIDE_T143 successfully created. |
SELECT INSIDE_T143(PARSE_JSON('{"region":"north","amount":100}')) AS WHAT_IT_SAW;| WHAT_IT_SAW |
|---|
| a object with keys: amount,region |
An object, with readable keys. So a VARIANT arrives as a real JavaScript object, not as a string you have to parse.
Now an array instead.
SELECT INSIDE_T143(PARSE_JSON('[1,2,3]')) AS WHAT_IT_SAW;| WHAT_IT_SAW |
|---|
| a object with keys: 0,1,2 |
Also an object, and its keys are the indexes. So typeof on its own will not tell an array from an object inside a JavaScript UDF.
And the other direction
CREATE OR REPLACE FUNCTION BUILD_T143(R VARCHAR, A FLOAT)
RETURNS VARIANT
LANGUAGE JAVASCRIPT
AS
$$
return { region: R, amount: A, taxed: A * 1.2 };
$$;| status |
|---|
| Function BUILD_T143 successfully created. |
SELECT BUILD_T143('north', 100) AS THE_OBJECT;| THE_OBJECT |
|---|
| { "amount": 100, "region": "north", "taxed": 120 } |
Printed as JSON. But is it a real variant or a string that looks like one? Let's reach inside it from SQL.
SELECT BUILD_T143('north', 100):region AS THE_REGION,
BUILD_T143('north', 100):taxed AS THE_TAXED_AMOUNT,
TYPEOF(BUILD_T143('north', 100)) AS WHAT_SQL_THINKS_IT_IS;| THE_REGION | THE_TAXED_AMOUNT | WHAT_SQL_THINKS_IT_IS |
|---|---|---|
| "north" | 120 | OBJECT |
Colon notation works, the arithmetic the body did is in there, and TYPEOF says OBJECT. So it is a real variant.
And an array works the same way.
CREATE OR REPLACE FUNCTION SPLIT_T143(S VARCHAR)
RETURNS ARRAY
LANGUAGE JAVASCRIPT
AS
$$
return S.split(',');
$$;| status |
|---|
| Function SPLIT_T143 successfully created. |
SELECT SPLIT_T143('north,south,east') AS THE_ARRAY,
ARRAY_SIZE(SPLIT_T143('north,south,east')) AS HOW_MANY;| THE_ARRAY | HOW_MANY |
|---|---|
| [ "north", "south", "east" ] | 3 |
A real array, and ARRAY_SIZE can count it.
What a JavaScript UDF cannot do, and when it finds out
First, the one everybody tries. A body that reads a table. If you have written a Snowflake stored procedure, this will look familiar.
CREATE OR REPLACE FUNCTION READSATABLE_T143()
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
var stmt = snowflake.createStatement({sqlText: "SELECT COUNT(*) FROM SALES_T143"});
var rs = stmt.execute();
rs.next();
return rs.getColumnValue(1);
$$;| status |
|---|
| Function READSATABLE_T143 successfully created. |
Created without complaint. Now let's call it.
SELECT READSATABLE_T143() AS WHAT_CAME_BACK;100132 (P0000): JavaScript execution error: Uncaught TypeError: snowflake.createStatement is not a function in READSATABLE_T143 at ' var stmt = snowflake.createStatement({sqlText: "SELECT COUNT(*) FROM SALES_T143"});' position 25
stackstrace:
READSATABLE_T143 line: 2A type error: that is not a function. The snowflake object exists in stored procedures. It does not exist in a UDF. There is no SQL in here at all.
Next, a body whose JavaScript does not parse.
CREATE OR REPLACE FUNCTION BROKEN_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return N *;
$$;| status |
|---|
| Function BROKEN_T143 successfully created. |
Function created successfully. Snowflake accepted that. So let's call it.
SELECT BROKEN_T143(1) AS WHAT_CAME_BACK;100131 (P0000): JavaScript compilation error: Uncaught SyntaxError: Unexpected token ';' in BROKEN_T143 at ' return N *;' position 14
100131, a JavaScript compilation error, at call time.
CREATE does not compile your body. A typo sits in the catalog looking like a working function until somebody calls it.
Which is the same shape as the argument name trap at the top of this post, and the reason to call every JavaScript UDF once before you trust it.
Same again with a variable that was never declared.
CREATE OR REPLACE FUNCTION UNDECLARED_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return N * MULTIPLIER;
$$;| status |
|---|
| Function UNDECLARED_T143 successfully created. |
SELECT UNDECLARED_T143(1) AS WHAT_CAME_BACK;100132 (P0000): JavaScript execution error: Uncaught ReferenceError: MULTIPLIER is not defined in UNDECLARED_T143 at ' return N * MULTIPLIER;' position 15 stackstrace: UNDECLARED_T143 line: 2
Created, then a reference error at call time.
And a language that is not a thing at all.
CREATE OR REPLACE FUNCTION BADLANG_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE COBOL
AS
$$
return N;
$$;002072 (42601): SQL compilation error: Unknown function language: COBOL.
002072, unknown function language. That one is caught at create time, because the language is Snowflake's business and the body is not.
One last thing: a JavaScript table function
Everything so far has been scalar. A JavaScript UDTF is written differently: the body is an object literal with a processRow function in it, and you write rows out through a rowWriter.
CREATE OR REPLACE FUNCTION SPLITROWS_T143(S VARCHAR)
RETURNS TABLE (THE_PIECE VARCHAR, WHICH_ONE FLOAT)
LANGUAGE JAVASCRIPT
AS
$$
{
processRow: function (row, rowWriter, context) {
var pieces = row.S.split(',');
for (var i = 0; i < pieces.length; i++) {
rowWriter.writeRow({THE_PIECE: pieces[i], WHICH_ONE: i});
}
}
}
$$;| status |
|---|
| Function SPLITROWS_T143 successfully created. |
SELECT THE_PIECE, WHICH_ONE
FROM TABLE(SPLITROWS_T143('north,south,east'))
ORDER BY WHICH_ONE;| THE_PIECE | WHICH_ONE |
|---|---|
| north | 0.0 |
| south | 1.0 |
| east | 2.0 |
Three rows, with their positions. The row writer wrote one row per piece of the string we handed it.
And it correlates with a comma, exactly like the SQL table functions in Episode 142.
SELECT s.SALE_ID, p.THE_PIECE
FROM SALES_T143 s,
TABLE(SPLITROWS_T143(s.REGION || ',everywhere')) p
WHERE s.SALE_ID <= 2
ORDER BY s.SALE_ID, p.WHICH_ONE;| SALE_ID | THE_PIECE |
|---|---|
| 1 | north |
| 1 | everywhere |
| 2 | south |
| 2 | everywhere |
Four rows. Each row of the table supplied its own string, and got its own pieces back.
And the teardown
DROP FUNCTION IF EXISTS DOUBLE_T143(FLOAT);| status |
|---|
| DOUBLE_T143 successfully dropped. |
DROP FUNCTION IF EXISTS ECHO_T143(NUMBER(38,0));| status |
|---|
| Drop statement executed successfully (ECHO_T143 already dropped). |
That message reads differently because the wide-number echo was refused at create time, so there was nothing to drop.
DROP FUNCTION IF EXISTS SPLITROWS_T143(VARCHAR);| status |
|---|
| SPLITROWS_T143 successfully dropped. |
DROP TABLE IF EXISTS SALES_T143;| status |
|---|
| SALES_T143 successfully dropped. |
DROP FUNCTION IF EXISTS ECHO_T143B(FLOAT);| status |
|---|
| ECHO_T143B successfully dropped. |
DROP FUNCTION IF EXISTS STRADD_T143B(VARCHAR);| status |
|---|
| STRADD_T143B successfully dropped. |
And the checks.
SELECT CURRENT_DATABASE() AS THE_DATABASE,
CURRENT_SCHEMA() AS THE_SCHEMA;| THE_DATABASE | THE_SCHEMA |
|---|---|
| DEMO_DB | PUBLIC |
SHOW USER FUNCTIONS LIKE '%\\_T143';| created_on | name | schema_name | is_builtin | is_aggregate | is_ansi | min_num_arguments | max_num_arguments | arguments | description | catalog_name | is_table_function | valid_for_clustering | is_secure | secrets | external_access_integrations | is_external_function | language | is_memoizable | is_data_metric | is_ai_function |
|---|
SELECT COUNT(*) AS PROBE_TABLES_LEFT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC'
AND ENDSWITH(TABLE_NAME, '_T143');| PROBE_TABLES_LEFT |
|---|
| 0 |
Still in PUBLIC, no functions of ours left and no tables of ours left. Back where we started.
Key points
LANGUAGE JAVASCRIPT, a body between dollar signs, and areturnin it. The function hands back a float, so42prints as42.0.- The argument's name is folded to upper case before JavaScript sees it. A lower case body cannot find it.
- Shout the name in the body, or quote it in the declaration. Either works. Doing neither fails at call time, not at create time.
- JavaScript accepts no
NUMBERtype at all. A wide one, a narrow one,INTand a bareNUMBERare all090215. - So it is
FLOAT,VARCHARorVARIANT, andFLOATloses large integers. - The side-by-side grid is the evidence for that: a SQL UDF returns the number intact and the JavaScript one returns it one lower.
- The difference column in this episode reads
0.0, because that subtraction was done in floating point too. It is not evidence. - If the number matters, pass it as text.
BigIntarithmetic survives the round trip exactly. - Falling off the end of the body gives a
NULL.return nullgives aNULL. Returning0 / 0gives the four charactersnan. - A thrown string comes back inside Snowflake's error, word for word, with the function name and line.
RETURNS NULL ON NULL INPUTis honoured here, and a null reaches the body asundefinedrather thannull. On a SQL UDF in Episode 141 it was not honoured at all.- A
VARIANTarrives as a real JavaScript object, and an array arrives as an object keyed by its indexes. - Returning an object gives you a real
VARIANTback, whichTYPEOFcallsOBJECTand colon notation can read. CREATEdoes not compile your body. Broken JavaScript is created happily and fails at call time with100131.- There is no SQL in a UDF.
snowflake.createStatementis a stored procedure thing and is not a function here. LANGUAGE COBOLis the one thing caught at create time:002072, unknown function language.- A JavaScript UDTF is an object literal with a
processRowfunction and arowWriter, and it correlates with a comma like any other table function.
Episode 144 — Python UDFs. A third language with a third set of rules about types, names and what the body can reach.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.35.101) running the demo script for this episode. The large-integer work uses the FLOAT echo function, because the one declared as a wide number was refused at create time, and the post keeps those two apart where it matters. The difference column that reads zero is on the page on purpose, with an explanation of why it is not evidence. The last three grids show the session back in PUBLIC with nothing of its own left behind. Nothing is timed and no performance claims are made anywhere in this series. Behaviour follows the Snowflake JavaScript UDF documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.