Snowflake SQL Tutorial 143 - My JavaScript UDF Could Not See Its Own Argument

Snowflake SQL · Episode 143

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

A small table to run the functions over later. One row has a NULL amount, on purpose.

Sample data
-- 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);
Query
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);
Result1 row · 1 column
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.

Query
CREATE OR REPLACE FUNCTION DOUBLE_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return N * 2;
$$;
Result1 row · 1 column
status
Function DOUBLE_T143 successfully created.

Created. Three calls: one doubled, zero doubled, and a negative.

Query
SELECT DOUBLE_T143(21)   AS TWENTY_ONE_DOUBLED,
       DOUBLE_T143(0)    AS NOTHING_DOUBLED,
       DOUBLE_T143(-1.5) AS A_NEGATIVE_DOUBLED;
Result1 row · 3 columns
TWENTY_ONE_DOUBLEDNOTHING_DOUBLEDA_NEGATIVE_DOUBLED
42.00.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.

Query
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;
Result1 row · 4 columns
FUNCTION_NAMEARGUMENT_SIGNATUREDATA_TYPEFUNCTION_LANGUAGE
DOUBLE_T143(N FLOAT)FLOATJAVASCRIPT

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.

Query
CREATE OR REPLACE FUNCTION LOWERARG_T143(amount FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return amount * 2;
$$;
Result1 row · 1 column
status
Function LOWERARG_T143 successfully created.

Created without a complaint. So let's call it.

Query
SELECT LOWERARG_T143(10) AS WHAT_CAME_BACK;
Query failed — Snowflake returned an error
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.

Query
CREATE OR REPLACE FUNCTION UPPERARG_T143(amount FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return AMOUNT * 2;
$$;
Result1 row · 1 column
status
Function UPPERARG_T143 successfully created.
And what it gives
SELECT UPPERARG_T143(10) AS WHAT_CAME_BACK;
Result1 row · 1 column
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.

Query
CREATE OR REPLACE FUNCTION QUOTEDARG_T143("amount" FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return amount * 2;
$$;
Result1 row · 1 column
status
Function QUOTEDARG_T143 successfully created.
And what it gives
SELECT QUOTEDARG_T143(10) AS WHAT_CAME_BACK;
Result1 row · 1 column
WHAT_CAME_BACK
20.0

20.0 again. So shout it in the body, or quote it in the declaration. Pick one.

Created happily, broken quietly

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.

Query
SELECT 9007199254740991 AS TWO_TO_THE_FIFTY_THREE_MINUS_ONE;
Result1 row · 1 column
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.

Query
CREATE OR REPLACE FUNCTION ECHO_T143(N NUMBER(38,0))
RETURNS NUMBER(38,0)
LANGUAGE JAVASCRIPT
AS
$$
    return N;
$$;
Query failed — Snowflake returned an error
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.

Query
SELECT ECHO_T143(9007199254740991) AS WENT_IN_AND_CAME_BACK;
Query failed — Snowflake returned an error
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.

Query
CREATE OR REPLACE FUNCTION NARROW_T143B(N NUMBER(10,2))
RETURNS NUMBER(10,2)
LANGUAGE JAVASCRIPT
AS
$$
    return N;
$$;
Query failed — Snowflake returned an error
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.

Query
CREATE OR REPLACE FUNCTION PLAININT_T143B(N INT)
RETURNS INT
LANGUAGE JAVASCRIPT
AS
$$
    return N;
$$;
Query failed — Snowflake returned an error
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.

Query
CREATE OR REPLACE FUNCTION BARENUM_T143B(N NUMBER)
RETURNS NUMBER
LANGUAGE JAVASCRIPT
AS
$$
    return N;
$$;
Query failed — Snowflake returned an error
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.

And what survived
SHOW USER FUNCTIONS LIKE '%\\_T143B';
Result0 rows · 21 columns · scroll →
created_onnameschema_nameis_builtinis_aggregateis_ansimin_num_argumentsmax_num_argumentsargumentsdescriptioncatalog_nameis_table_functionvalid_for_clusteringis_securesecretsexternal_access_integrationsis_external_functionlanguageis_memoizableis_data_metricis_ai_function

Nothing. No rows. All three refusals were refusals.

The whole rule, in one line

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.

The JavaScript one
CREATE OR REPLACE FUNCTION ECHO_T143B(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return N;
$$;
Result1 row · 1 column
status
Function ECHO_T143B successfully created.
The SQL one
CREATE OR REPLACE FUNCTION SQLECHO_T143B(N NUMBER(38,0))
RETURNS NUMBER(38,0)
AS
$$
    N
$$;
Result1 row · 1 column
status
Function SQLECHO_T143B successfully created.

Let's send in the largest safe integer.

Query
SELECT 9007199254740991            AS WHAT_I_SENT,
       ECHO_T143B(9007199254740991) AS WHAT_CAME_BACK;
Result1 row · 2 columns
WHAT_I_SENTWHAT_CAME_BACK
90071992547409919007199254740991.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.

Query
SELECT 9007199254740993            AS WHAT_I_SENT,
       ECHO_T143B(9007199254740993) AS WHAT_CAME_BACK;
Result1 row · 2 columns
WHAT_I_SENTWHAT_CAME_BACK
90071992547409939007199254740992.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.

Query
SELECT SQLECHO_T143B(9007199254740993) AS THROUGH_A_SQL_FUNCTION,
       ECHO_T143B(9007199254740993)    AS THROUGH_A_JAVASCRIPT_ONE;
Result1 row · 2 columns
THROUGH_A_SQL_FUNCTIONTHROUGH_A_JAVASCRIPT_ONE
90071992547409939007199254740992.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.

Query
SELECT 123456789012345678901234567890             AS WHAT_I_SENT,
       ECHO_T143B(123456789012345678901234567890) AS WHAT_CAME_BACK;
Result1 row · 2 columns
WHAT_I_SENTWHAT_CAME_BACK
1234567890123456789012345678901.2345678901234568e+29

Scientific notation, with the tail of the number gone. And through the SQL function?

Query
SELECT SQLECHO_T143B(123456789012345678901234567890) AS THROUGH_A_SQL_FUNCTION;
Result1 row · 1 column
THROUGH_A_SQL_FUNCTION
123456789012345678901234567890

Every digit, intact.

And one honest caveat

I also wrote a subtraction, to put a number on the loss.

Query
SELECT 9007199254740993                             AS WHAT_I_SENT,
       ECHO_T143B(9007199254740993)                 AS WHAT_CAME_BACK,
       9007199254740993 - ECHO_T143B(9007199254740993) AS THE_DIFFERENCE;
Result1 row · 3 columns
WHAT_I_SENTWHAT_CAME_BACKTHE_DIFFERENCE
90071992547409939007199254740992.00.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.

A measurement that cannot measure

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.

Query
CREATE OR REPLACE FUNCTION STRECHO_T143(N VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
    return N;
$$;
Result1 row · 1 column
status
Function STRECHO_T143 successfully created.
And what it gives
SELECT STRECHO_T143('9007199254740993') AS SENT_AS_TEXT;
Result1 row · 1 column
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.

Query
CREATE OR REPLACE FUNCTION STRADD_T143B(N VARCHAR)
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
    return BigInt(N) + 1n + '';
$$;
Result1 row · 1 column
status
Function STRADD_T143B successfully created.
And adding one
SELECT '9007199254740993'                 AS WHAT_I_SENT,
       STRADD_T143B('9007199254740993')    AS PLUS_ONE_IN_JAVASCRIPT;
Result1 row · 2 columns
WHAT_I_SENTPLUS_ONE_IN_JAVASCRIPT
90071992547409939007199254740994

One more than what we sent, exactly. Not one more than the nearest float.

And the big one
SELECT STRADD_T143B('123456789012345678901234567890') AS PLUS_ONE_IN_JAVASCRIPT;
Result1 row · 1 column
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.

Query
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';
$$;
Result1 row · 1 column
status
Function GRADE_T143 successfully created.
Four scores through it
SELECT GRADE_T143(95) AS NINETY_FIVE,
       GRADE_T143(75) AS SEVENTY_FIVE,
       GRADE_T143(55) AS FIFTY_FIVE,
       GRADE_T143(10) AS TEN;
Result1 row · 4 columns
NINETY_FIVESEVENTY_FIVEFIFTY_FIVETEN
excellentgoodfairpoor

The loop ran and the branch chose, four times over.

And a try/catch, which is the other thing you cannot do in SQL.

Query
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;
    }
$$;
Result1 row · 1 column
status
Function SAFE_PARSE_T143 successfully created.
Good JSON, then something that is not JSON
SELECT SAFE_PARSE_T143('{"a":1,"b":2}') AS GOOD_INPUT,
       SAFE_PARSE_T143('not json')      AS BAD_INPUT;
Result1 row · 2 columns
GOOD_INPUTBAD_INPUT
parsed, and it has 2 keyscould 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

Query
SELECT SALE_ID,
       AMOUNT,
       GRADE_T143(AMOUNT) AS THE_GRADE
FROM SALES_T143
ORDER BY SALE_ID;
Result5 rows · 3 columns
SALE_IDAMOUNTTHE_GRADE
195.00excellent
275.00good
355.00fair
410.00poor
5NULLpoor

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.

Query
SELECT SALE_ID, AMOUNT
FROM SALES_T143
WHERE GRADE_T143(AMOUNT) IN ('excellent', 'good')
ORDER BY SALE_ID;
Result2 rows · 2 columns
SALE_IDAMOUNT
195.00
275.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.

Query
CREATE OR REPLACE FUNCTION RETURNSNOTHING_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    var x = N * 2;
$$;
Result1 row · 1 column
status
Function RETURNSNOTHING_T143 successfully created.
And what it gives
SELECT RETURNSNOTHING_T143(5)            AS WHAT_CAME_BACK,
       RETURNSNOTHING_T143(5) IS NULL    AS IS_IT_NULL;
Result1 row · 2 columns
WHAT_CAME_BACKIS_IT_NULL
NULLTRUE

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.

The null one
CREATE OR REPLACE FUNCTION RETURNSNULL_T143()
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return null;
$$;
Result1 row · 1 column
status
Function RETURNSNULL_T143 successfully created.
The NaN one
CREATE OR REPLACE FUNCTION RETURNSNAN_T143()
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return 0 / 0;
$$;
Result1 row · 1 column
status
Function RETURNSNAN_T143 successfully created.
And what they give
SELECT RETURNSNULL_T143() AS THE_NULL_ONE,
       RETURNSNAN_T143()  AS THE_NAN_ONE;
Result1 row · 2 columns
THE_NULL_ONETHE_NAN_ONE
NULLnan

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?

Query
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);
$$;
Result1 row · 1 column
status
Function THROWS_T143 successfully created.

First the path that does not throw.

Query
SELECT THROWS_T143(16) AS SIXTEEN_ROOTED;
Result1 row · 1 column
SIXTEEN_ROOTED
4.0

4.0. Now the one that does.

Query
SELECT THROWS_T143(-1) AS A_NEGATIVE;
Query failed — Snowflake returned an error
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.

CALLED ON NULL INPUT
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;
$$;
Result1 row · 1 column
status
Function CALLED_T143 successfully created.
RETURNS NULL ON NULL INPUT
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;
$$;
Result1 row · 1 column
status
Function STRICT_T143 successfully created.

With a three first.

Query
SELECT CALLED_T143(3) AS THE_CALLED_ONE,
       STRICT_T143(3) AS THE_STRICT_ONE;
Result1 row · 2 columns
THE_CALLED_ONETHE_STRICT_ONE
the body ran and N was 3the body ran and N was 3

Both ran and both saw a three. No surprise. Now with a NULL.

Query
SELECT CALLED_T143(NULL) AS THE_CALLED_ONE,
       STRICT_T143(NULL) AS THE_STRICT_ONE;
Result1 row · 2 columns
THE_CALLED_ONETHE_STRICT_ONE
the body ran and N was undefinedNULL

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.

Worth stopping on

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.

Query
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(',');
$$;
Result1 row · 1 column
status
Function INSIDE_T143 successfully created.
Given a JSON object
SELECT INSIDE_T143(PARSE_JSON('{"region":"north","amount":100}')) AS WHAT_IT_SAW;
Result1 row · 1 column
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.

Given an array
SELECT INSIDE_T143(PARSE_JSON('[1,2,3]')) AS WHAT_IT_SAW;
Result1 row · 1 column
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

Query
CREATE OR REPLACE FUNCTION BUILD_T143(R VARCHAR, A FLOAT)
RETURNS VARIANT
LANGUAGE JAVASCRIPT
AS
$$
    return { region: R, amount: A, taxed: A * 1.2 };
$$;
Result1 row · 1 column
status
Function BUILD_T143 successfully created.
And what comes back
SELECT BUILD_T143('north', 100) AS THE_OBJECT;
Result1 row · 1 column
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.

Query
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;
Result1 row · 3 columns
THE_REGIONTHE_TAXED_AMOUNTWHAT_SQL_THINKS_IT_IS
"north"120OBJECT

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.

Query
CREATE OR REPLACE FUNCTION SPLIT_T143(S VARCHAR)
RETURNS ARRAY
LANGUAGE JAVASCRIPT
AS
$$
    return S.split(',');
$$;
Result1 row · 1 column
status
Function SPLIT_T143 successfully created.
And what it gives
SELECT SPLIT_T143('north,south,east') AS THE_ARRAY,
       ARRAY_SIZE(SPLIT_T143('north,south,east')) AS HOW_MANY;
Result1 row · 2 columns
THE_ARRAYHOW_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.

Query
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);
$$;
Result1 row · 1 column
status
Function READSATABLE_T143 successfully created.

Created without complaint. Now let's call it.

Query
SELECT READSATABLE_T143() AS WHAT_CAME_BACK;
Query failed — Snowflake returned an error
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: 2

A 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.

Query
CREATE OR REPLACE FUNCTION BROKEN_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return N *;
$$;
Result1 row · 1 column
status
Function BROKEN_T143 successfully created.

Function created successfully. Snowflake accepted that. So let's call it.

Query
SELECT BROKEN_T143(1) AS WHAT_CAME_BACK;
Query failed — Snowflake returned an error
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 is not a compile

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.

Query
CREATE OR REPLACE FUNCTION UNDECLARED_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return N * MULTIPLIER;
$$;
Result1 row · 1 column
status
Function UNDECLARED_T143 successfully created.
And calling it
SELECT UNDECLARED_T143(1) AS WHAT_CAME_BACK;
Query failed — Snowflake returned an error
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.

Query
CREATE OR REPLACE FUNCTION BADLANG_T143(N FLOAT)
RETURNS FLOAT
LANGUAGE COBOL
AS
$$
    return N;
$$;
Query failed — Snowflake returned an error
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.

Query
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});
        }
    }
}
$$;
Result1 row · 1 column
status
Function SPLITROWS_T143 successfully created.
And what it gives
SELECT THE_PIECE, WHICH_ONE
FROM TABLE(SPLITROWS_T143('north,south,east'))
ORDER BY WHICH_ONE;
Result3 rows · 2 columns
THE_PIECEWHICH_ONE
north0.0
south1.0
east2.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.

Query
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;
Result4 rows · 2 columns
SALE_IDTHE_PIECE
1north
1everywhere
2south
2everywhere

Four rows. Each row of the table supplied its own string, and got its own pieces back.

And the teardown

Teardown
DROP FUNCTION IF EXISTS DOUBLE_T143(FLOAT);
Result1 row · 1 column
status
DOUBLE_T143 successfully dropped.
Teardown, for one that was never created
DROP FUNCTION IF EXISTS ECHO_T143(NUMBER(38,0));
Result1 row · 1 column
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.

Teardown
DROP FUNCTION IF EXISTS SPLITROWS_T143(VARCHAR);
Result1 row · 1 column
status
SPLITROWS_T143 successfully dropped.
Teardown
DROP TABLE IF EXISTS SALES_T143;
Result1 row · 1 column
status
SALES_T143 successfully dropped.
Teardown, the FLOAT echo
DROP FUNCTION IF EXISTS ECHO_T143B(FLOAT);
Result1 row · 1 column
status
ECHO_T143B successfully dropped.
Teardown
DROP FUNCTION IF EXISTS STRADD_T143B(VARCHAR);
Result1 row · 1 column
status
STRADD_T143B successfully dropped.

And the checks.

Where we are
SELECT CURRENT_DATABASE() AS THE_DATABASE,
       CURRENT_SCHEMA()   AS THE_SCHEMA;
Result1 row · 2 columns
THE_DATABASETHE_SCHEMA
DEMO_DBPUBLIC
And what is left
SHOW USER FUNCTIONS LIKE '%\\_T143';
Result0 rows · 21 columns · scroll →
created_onnameschema_nameis_builtinis_aggregateis_ansimin_num_argumentsmax_num_argumentsargumentsdescriptioncatalog_nameis_table_functionvalid_for_clusteringis_securesecretsexternal_access_integrationsis_external_functionlanguageis_memoizableis_data_metricis_ai_function
And the tables
SELECT COUNT(*) AS PROBE_TABLES_LEFT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC'
  AND ENDSWITH(TABLE_NAME, '_T143');
Result1 row · 1 column
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 a return in it. The function hands back a float, so 42 prints as 42.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 NUMBER type at all. A wide one, a narrow one, INT and a bare NUMBER are all 090215.
  • So it is FLOAT, VARCHAR or VARIANT, and FLOAT loses 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. BigInt arithmetic survives the round trip exactly.
  • Falling off the end of the body gives a NULL. return null gives a NULL. Returning 0 / 0 gives the four characters nan.
  • A thrown string comes back inside Snowflake's error, word for word, with the function name and line.
  • RETURNS NULL ON NULL INPUT is honoured here, and a null reaches the body as undefined rather than null. On a SQL UDF in Episode 141 it was not honoured at all.
  • A VARIANT arrives as a real JavaScript object, and an array arrives as an object keyed by its indexes.
  • Returning an object gives you a real VARIANT back, which TYPEOF calls OBJECT and colon notation can read.
  • CREATE does not compile your body. Broken JavaScript is created happily and fails at call time with 100131.
  • There is no SQL in a UDF. snowflake.createStatement is a stored procedure thing and is not a function here.
  • LANGUAGE COBOL is the one thing caught at create time: 002072, unknown function language.
  • A JavaScript UDTF is an object literal with a processRow function and a rowWriter, and it correlates with a comma like any other table function.
Next in this series

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.