Documentation Home
MySQL 9.3 Reference Manual
Related Documentation Download this Manual
PDF (US Ltr) - 40.8Mb
PDF (A4) - 40.9Mb
Man Pages (TGZ) - 261.1Kb
Man Pages (Zip) - 368.3Kb
Info (Gzip) - 4.1Mb
Info (Zip) - 4.1Mb


MySQL 9.3 Reference Manual  / ...  / Stored Objects  / JavaScript Stored Programs  /  JavaScript Stored Program Data Types and Argument Handling

27.3.4 JavaScript Stored Program Data Types and Argument Handling

Most MySQL data types are supported for MLE stored program input and output arguments, as well as for return data types. The data types are listed here:

  • Integer: All variants and aliases of MySQL integer data types are supported, includingTINYINT,SMALLINT,MEDIUMINT,INT, andBIGINT.

    SIGNED andUNSIGNED are supported for all these types.

    BOOL andSERIAL are also supported, and treated as integer types.

  • String: TheCHAR,VARCHAR,TEXT, andBLOB string types are supported.

    These types are supported as in the MySQL server with the following exceptions:

    1. String argument and return types can use theutf8mb4 or binary character sets; use of other character sets for these raises an error. This restriction applies to argument and return type declarations; the server attempts to convert argumentvalues using other character sets toutfmb4 whenever necessary, as with SQL stored programs.

    2. The maximum supported length for aLONGTEXT value is 1073741799 (230 - 24 - 23 - 1) characters; forLONGBLOB, the maximum supported length is 2147483639 (231 - 28 - 1).

    Support forBLOB types includes support forBINARY andVARBINARY.

    The MySQLJSON data type is also supported.

  • Floating point:FLOAT andDOUBLE are supported along with their aliases.REAL is also treated as floating point, butUNSIGNED FLOAT andUNSIGNED DOUBLE are deprecated in MySQL, and are not supported by MLE.

  • Temporal types:DATE,DATETIME, andTIMESTAMP are supported, and are converted to JavaScriptDate values.TIME values are treated as strings;YEAR values are treated as numbers.

    The first time a given JavaScript stored procedure is executed, it is associated with the current MySQL session time zone, and this time zone continues to be used by the stored program, even if the MySQL session time zone is changed concurrently, for the duration of the MLE component session, or untilmle_session_reset() is invoked. More more information, seeTime zone support, later in this section.

  • VECTOR is supported in MySQL 9.1 and later.

  • DECIMAL andNUMERIC are supported in MySQL 9.3 and later.

Input arguments (IN andINOUT parameters) are automatically converted into JavaScript types based on the mapping shown in the following table:

Table 27.1 Conversion of MySQL data types to JavaScript types

MySQL TypeJavaScript Type
TINYINT,SMALLINT,MEDIUMINT,INT,BOOL,BIGINT, orSERIALIf safe:Number; otherwise:String
FLOAT orDOUBLENumber
CHAR,VARCHAR,TINYTEXT,TEXT,MEDIUMTEXT, orLONGTEXTString
TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB,BINARY, orVARBINARYUint8Array
DATE,DATETIME, orTIMESTAMPDate
TIMEString
YEARNumber
VECTORFloat32Array

Conversion to or from a MySQL integer whose value lies outside the range -(253-1) (-9007199254740991) to 253-1 (9007199254740991) is lossy. How conversion from MySQL integers to JavaScript is performed can be changed for the current session usingmle_set_session_state(); the default behavior is equivalent to calling this function usingUNSAFE_STRING as the value forinteger_type. See the description of that function for more information.

SQLNULL is supported for all the types listed, and is converted to and from JavaScriptnull as required.

JavaScript (unlike SQL) is a dynamically typed language, which means that return types are known only at execution time. JavaScript return value and output arguments (OUT andINOUT parameters) are automatically converted back into the expected MySQL type based on the mappings shown in the following table:

Table 27.2 Type Conversion: JavaScript to MySQL

From JavaScript TypeTo MySQLTINYINT,SMALLINT,MEDIUMINT,INT,BIGINT,BOOLEAN, orSERIALTo MySQLCHAR orVARCHARTo MySQLFLOAT orDOUBLETo MySQLTINYTEXT,TEXT,MEDIUMTEXT, orLONGTEXTTo MySQLTINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB,BINARY,VARBINARYTo MySQLVECTORTo MySQLDECIMAL (NUMERIC)
BooleanCast toIntegerConvert toString; check whether length of result is within expected rangeCast toFloatIf JavaScriptBooleantrue: convert totrue; if JavaScriptBooleanfalse: convert tofalseErrorErrorConvert toString orNumber (defaultString)
NumberRound value toInteger; check whether value is out of rangeConvert toString; check whether length of result is within expected rangeRetain value; check whether this is out of rangeConvert toString; check whether length of result is within expected rangeErrorErrorConvert toString orNumber (defaultString)
BigIntegerRetain value; check whether out of rangeConvert toString; check whether length of result is within expected rangeCast toFloat; check whether result is out of rangeConvert toString; check whether length of result is within expected rangeErrorErrorConvert toString orNumber (defaultString)
StringParse as number and round toInteger; check for value out of rangeRetain value; check whether length is within rangeParse value toFloat; check for value out of range valuesUse existing string value; check whether length of string is within expected rangeErrorErrorConvert toString orNumber (defaultString)
Symbol orObjectRaise invalid type conversion errorConvert toString; check whether length of result is within expected rangeRaise invalid type conversion errorConvert toString; check whether length of result is within expected rangeErrorErrorError
TypedArrayRaise invalid type conversion errorConvert toString; check whether length of result is within expected rangeRaise invalid type conversion errorConvert toString; check whether length of result is within expected rangeConvert to byte array; check whether result is within expected sizeTreat asFloat32Array; convert to byte array, checking whether it is within the expectedVECTOR field sizeError
null orundefinedNULLNULLNULLNULLNULLNULLNULL

Notes:

  • JavaScriptInfinity and-Infinity are treated as out-of-range values.

  • JavaScriptNaN raises an invalid type conversion error.

  • All rounding is performed usingMath.round().

  • Attempting to cast aBigInt orString having a non-numeric value to MySQLFLOAT raises an invalid type conversion error.

  • The maximum supported length for strings is 1073741799.

  • The maximum supported length forBLOB values is 2147483639.

  • JavaScript.MAX_SAFE_INTEGER is equal to 9007199254740991 (253-1).

Table 27.3 Type Conversion: JavaScript Dates to MySQL

JavaScript TypeMySQLDATEMySQLDATETIME,TIMESTAMPMySQL YEAR
null orundefinedNULLNULLNULL
DateRetain value as is, rounding off any time part to the closest second.Keep value as is.Extract year from theDate
Type convertible to JavaScriptDate (formattedstring)Cast value to JavaScriptDate and handle accordinglyCast value to JavaScriptDate and handle accordinglyIf value contains 4-digit year, use it.
Type not convertible to JavaScriptDateInvalid type conversion errorInvalid type conversion errorIf value contains 4-digit year, use it.

Passing a MySQL zero date (00-00-0000) or zero-in-date value (such as00-01-2023) leads to the creation of anInvalid Date instance ofDate. When passed a MySQL date which is invalid (for example, 31 February), MLE calls a JavaScriptDate constructor with invalid individual date and time component values.

The MySQLTIME type is handled as a string, and is validated inside MySQL. SeeSection 13.2.3, “The TIME Type”, for more information.

Table 27.4 Conversion of MySQL JSON types to JavaScript

MySQL JSON TypeJavaScript Type
NULL,JSON NULLnull
JSON OBJECTObject
JSON ARRAYArray
JSON BOOLEANBoolean
JSON INTEGER,JSON DOUBLE,JSON DECIMALNumber
JSON STRINGString
JSON DATETIME,JSON DATE,JSON TIMEString
JSON BLOB,JSON OPAQUEString

Note

A MySQL JSON string, when converted to a Javascript string, becomes unquoted.

Table 27.5 Conversion of JavaScript types to MySQL JSON

JavaScript TypeMySQL JSON Type
null,undefinedNULL
BooleanError
NumberError
String
  • Can be parsed as JSON: JSON string, JSON object, or JSON array

  • Cannot be parsed as JSON: Error

  • 'null': JSONnull

BigIntError
ObjectJSON object or error (see text following table)
ArrayJSON array
Symbol
  • Inside an object: ignored

  • Inside an array: JSONnull

Scalar value: Error

Notes:

  • A value within a container such as a JSON array or JSON object is converted (loss of precision is possible forNumber values). A scalar value throws an error.

  • JavaScriptBigInt values cannot be converted to MySQL JSON; attempting to perform such a conversion always raises an error, regardless of whether the value is inside a container or not.

  • It may or may not be possible to convert a JavascriptObject to MySQL JSON, depending on howtoJSON() is implemented for the object in question. Some examples are listed here:

    • ThetoJSON() method of the JavaScriptDate class converts aDate to a string having invalid JSON syntax, thus throwing a conversion error.

    • For theSet class,toJSON() returns"{}" which is a valid JSON string.

    • For JSON-like objects,toJSON() returns a valid JSON string.

Conversion to and from MySQL ENUM and SET. ENUM converts to a JavaScriptString;SET converts to a JavaScriptSet object, as shown in the following table:

Table 27.6 Conversion of the MySQL ENUM and SET types to JavaScript

MySQL TypeJavaScript Type
ENUMString
SETSet

The following table shows rules for converting a JavaScript type to a MySQLENUM orSET type:

Table 27.7 Type Conversion: JavaScript types to MySQL ENUM and SET

JavaScript TypeTo MySQLENUMTo MySQLSET
StringPreserve value; check whether string is validENUM valuePreserve value; check whether string is validSET value
null,undefinedNULLNULL
SetErrorConvert to comma-separated string; check whether string is validSET value
Any other typeErrorError

Additional notes

Conversion to and from MySQL DECIMAL and NUMERIC.  MySQL decimal types (DECIMAL andNUMERIC) are converted to either of JavaScriptString orNumber, depending on the value ofsession.options.decimalType (STRING orNUMBER, respectively). The default behavior is to convert such values toString.

To set this variable on the session level so that MySQL decimal types are converted toNumber by default instead, callmle_set_session_state() like this:

mle_set_session_state("decimalType":"NUMBER")

The MLE stored program cache must be empty when this function is invoked; it is not empty, you can clear it usingmle_session_reset(). See the description ofmle_set_session_state() for more information.

To set thedecimalType option within a JavaScript stored routine, useSession.setOptions(), as shown here:

session.setOptions('{"decimalType":"mysql.DecimalType.NUMBER"}')

This sets the default for conversion of MySQL decimal values toNumber for the lifetime of the routine. Usemysql.DecimalType.STRING to makeString the default.

Rules for conversion of JavaScript values to the MySQLDECIMAL type (or its aliasNUMERIC) are shown in the following table:

Table 27.8 Type Conversion: JavaScript types to MySQL DECIMAL

JavaScript TypeReturns
Object,Array, orSymbolError: Conversion not supported
Boolean,Number,String, orBigIntDECIMAL value
null,undefinedSQLNULL

The maximum which a decimal value can hold is determined by the precision and scale ofDECIMAL(M,D), whereM is the precision (maximum number of digits) in the range 1-65, andD is scale (the number of digits to the right of the decimal point, with the range 0-30. In addition,M must be greater than or equal toD. (SeeSection 13.1.3, “Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC”, for more information.)

In the event that a decimal value exceeds the range specified byDECIMAL(M,D) or cannot be stored within the constraints ofDECIMAL(M,D), the behavior depends on the server SQL mode (seeSection 7.1.11, “Server SQL Modes”), as follows:

  • Strict SQL Mode: An error is raised, and the operation fails.

  • Otherwise: The value is automatically capped to the nearest valid minimum or maximum value for the range given, and a warning is issued.

Time zone support.  A JavaScript stored program uses the MySQL session timezone in effect at the time it is first invoked. This time zone remains in effect for this stored program for the duration of the session in the session.

Changing the MySQL session time zone is not automatically reflected in stored programs which have been used and thus are already cached. To make them use the new time zone, callmle_session_reset() to clear the cache; after this, stored programs use the new time zone.

Supported time zone types are listed here:

  • Time zone offsets from UTC, such as+11:00 or-07:15.

  • Timezones defined in theIANA time zone database are supported, with the exception of configurations using leap seconds. For example,Pacific/Nauru,Japan, andMET are supported, whileleap/Pacific/Nauru andright/Pacific/Nauru are not.

Range checks and invalid type conversion checks are performed following stored program execution. Casting is done inside JavaScript using type constructors such asNumber() andString(); rounding toInteger is performed usingMath.round().

An input argument (IN orINOUT parameter) named in a JavaScript stored program definition is accessible from within the routine body using the same argument identifier. Output arguments (INOUT andOUT parameters) are also available in JavaScript stored procedures. The same argument identifier can be used to set the value using the JavaScript assignment (=) operator. As with SQL stored procedureOUT arguments, the initial value is set to JavaScriptnull.

Caution

You shouldnot override program arguments usinglet,var, orconst inside JavaScript stored programs. Doing so turns them into variables which are local to the program, and makes any values passed into the program using the same-named parameters inaccessible.

Example:

mysql> CREATE FUNCTION myfunc(x INT)    ->   RETURNS INT LANGUAGE JAVASCRIPT AS    -> $$    $>   var x    $>       $>   return 2*x    $> $$    -> ;Query OK, 0 rows affected (0.03 sec)mysql> SELECT myfunc(10);ERROR 6000 (HY000): MLE-Type> Cannot convert value 'NaN' to INT from MLE in 'myfunc(10)'

The JavaScriptreturn statement should be used to return scalar values in stored functions. In stored procedures, this statement does not return a value, and merely exits the code block (this may or may not also exit the routine depending on program flow).return cannot be used to set stored procedureOUT orINOUT argument values; these must be set explicitly within the routine.

For information about accessing MySQL stored procedures and stored functions from within JavaScript stored routines, seeSection 27.3.6.10, “Stored Routine API”.