Documentation Home
MySQL 9.4 Reference Manual
Related Documentation Download this Manual
PDF (US Ltr) - 41.2Mb
PDF (A4) - 41.3Mb
Man Pages (TGZ) - 262.8Kb
Man Pages (Zip) - 368.8Kb
Info (Gzip) - 4.1Mb
Info (Zip) - 4.1Mb


27.3.6.1 Session Object

TheSession object is always available as thesession property of the global object.Session has the methods listed here:

  • createSchema(Stringname): Creates a database having the specifiedname, and returns the correspondingSchema object.

  • dropSchema(Stringname): Drops the database having the specifiedname. The return value is undefined.

  • getDefaultSchema(): Returns aSchema corresponding to the default (current) database.

  • getOption(Stringname): Gets the value of statement optionname. Returns a string or a true-false value depending on the option type.

  • getSchema(Stringname): Gets theSchema object having the suppliedname if the corresponding schema exists, otherwise throwing an error.

  • getSchemas(): Returns a list of all availableSchema objects.

  • prepare(Stringsql, {passResultToClient: Bool,charsetName: String}): Enables the execution of a prepared statements; takes an SQL statement and returns aPreparedStatement object.

    Calling this method is equivalent to executing aPREPARE statement in themysql client.

  • quoteName(Stringname): Returnsname, after escaping it.

  • runSql(Stringquery[[, ArraystatementParameters], Optionsoptions]): Executes a query, with any options specified, and using an optional list of statement parameters; it returns anSqlResult.

  • setOptions(Objectoptions): Sets statement option defaults. Options not specified assume their default values. See the description ofSession.sql() for option names and possible values.

  • sql(Stringsql, {passResultToClient: Bool,charsetName: String,integerType: IntegerType,decimalType: DecimalType}): Executes a simple SQL statement. Can also be used to provide attributes overriding thepassResultToClient andcharsetName values set in the session. Returns anSqlExecute object.

    IntegerType consists of a JSON key-value pair whose key isIntegerType, and whose possible values and their effects are listed here:

    • mysql.IntegerType.BIGINT: Convert all MySQL integer values to JavaScriptBigInt.

    • mysql.IntegerType.STRING: Convert all MySQL integer values to JavaScriptString

    • mysql.IntegerType.UNSAFE_BIGINT: If the MySQL value is safe, convert it to JavaScriptNumber; otherwise convert it to JavaScriptBigInt. If the value is safe, convert to JavaScriptNumber; otherwise convert to JavaScriptString. This is the default behavior if no rule is specified.

    • mysql.IntegerType.UNSAFE_STRING: If the MySQL value is safe, convert it to JavaScriptNumber; otherwise convert it to JavaScriptString. This is the default behavior if no rule is specified.

    The rule set by this value determines how MySQL integer values are converted to JavaScript by this SQL statement. Their names (less object references) correspond to those for the used with theinteger_type key used withmle_set_session_state(). The default behavior is equivalent to having setmysql.IntegerType.UNSAFE_STRING, or having calledmle_set_session_state('{"integer_type":"STRING"}').

    DecimalType consists of a JSON key-value pair whose key isDecimalType, and whose possible values and their effects are listed here:

    • mysql.DecimalType.STRING: Convert MySQL decimal values (DECIMAL and its aliasNUMERIC) to JavaScriptString values. (This is the default behavior.)

    • mysql.DecimalType.NUMBER: Convert MySQL decimal values to JavaScriptNumber.

    These options can also be set for a given statement usingrunSQL() orprepare(). To set them on the session or routine level, you can also usesetOptions().

JavaScript transactional functions are also methods ofSession. SeeSection 27.3.6.11, “JavaScript Transaction API” for descriptions and examples.

Accessing Session Variables from JavaScript

You can access MySQL session variables as properties of theSession object, as shown in this example:

mysql> SET @myvar = 27;Query OK, 0 rows affected (0.00 sec)mysql> CREATE PROCEDURE get_session_var() LANGUAGE JAVASCRIPT    -> AS $$    $>     console.clear()    $>     let the_var = session.myvar    $>         $>     console.log("the_var: " + the_var)    $>     console.log("typeof the_var: " + typeof the_var)    $> $$;Query OK, 0 rows affected (0.01 sec)mysql> CALL get_session_var();Query OK, 0 rows affected (0.01 sec)mysql> SELECT mle_session_state("stdout")\G*************************** 1. row ***************************mle_session_state("stdout"): the_var: 27typeof the_var: numbermysql> SET @myvar = "Something that is not 27";Query OK, 0 rows affected (0.00 sec)mysql> CALL get_session_var();Query OK, 0 rows affected (0.00 sec)mysql> SELECT mle_session_state("stdout")\G*************************** 1. row ***************************mle_session_state("stdout"): the_var: Something that is not 27typeof the_var: string1 row in set (0.00 sec)

You can also set session variables by accessing them in the same way, as shown here:

mysql> CREATE PROCEDURE set_session_var(IN x INT) LANGUAGE JAVASCRIPT    -> AS $$    $>   session.myvar = x    $> $$;Query OK, 0 rows affected (0.01 sec)mysql> CALL set_session_var(72);Query OK, 0 rows affected (0.00 sec)mysql> SELECT @myvar;+--------+| @myvar |+--------+|     72 |+--------+1 row in set (0.00 sec)

Session variables accessed asSession properties in JavaScript are created automatically if they do not already exist, as shown in this example:

mysql> CREATE PROCEDURE set_any_var(IN name VARCHAR, IN val INT)    ->   LANGUAGE JAVASCRIPT    -> AS $$    $>   session[name] = val    $> $$;Query OK, 0 rows affected (0.00 sec)mysql> SELECT @yourvar;+--------------------+| @yourvar           |+--------------------+| NULL               |+--------------------+1 row in set (0.00 sec)mysql> CALL set_any_var("myvar", 25);Query OK, 0 rows affected (0.01 sec)mysql> CALL set_any_var("yourvar", 100);Query OK, 0 rows affected (0.00 sec)mysql> SELECT @myvar, @yourvar;+--------+----------+| @myvar | @yourvar |+--------+----------+|     25 |      100 |+--------+----------+1 row in set (0.00 sec)

Rules for type conversion from MySQL session variables to JavaScript variables are shown in the following table:

MySQL typeJavaScript typeComments
NULLnull-
BIGINTNumber,String, orBigIntDepends onsession.sql() methodintegerType option value
DECIMAL orNUMERICString orNumberDepends onsession.sql() methoddecimalType option value
DOUBLENumber-
Binary stringUint8Array-
StringString-

Rules for type conversion from JavaScript variables to MySQL session variables are shown in the following table:

JavaScript typeMySQL typeComment
null orundefinedNULL-
BooleanBIGINT-
NumberBIGINT,DECIMAL, orDOUBLE-
Infinity,NaN, orSymbol-Error: Type cannot be used for session variables
Stringstring-
BigIntBIGINT-
TypedArray orFloat32ArrayBINARY-
Objectstring-
Arraystring-
JavaScript Localization and Internationalization

JavaScript stored programs in MySQL support MySQL locales. Localization and internationalization are handled using theIntl global object.

MySQL locale names map to JavaScript locale names by replacing the underscore character with a dash. This can be seen in the following example, which shows how to retrieve the current locale:

mysql> SET @@lc_time_names = "sv_SE";mysql> CREATE PROCEDURE lc1() LANGUAGE JAVASCRIPT mysql>   AS mysql>   $$mysql>     const defaultLocale = Intl.DateTimeFormat().resolvedOptions().localemysql>     console.log("Default Locale: ", defaultLocale)mysql>   $$;mysql> CALL lc1();Query OK, 0 rows affected (0.01 sec)mysql> SELECT mle_session_state("stdout");+-----------------------------+| mle_session_state("stdout") |+-----------------------------+|       Default Locale: sv-SE |+-----------------------------+1 row in set (0.04 sec)

It is also possible to override the session locale within a JavaScript stored program; here, we show the same number displayed twice in succession using a different locale each time:

mysql> SET @@lc_time_names = "fr_FR";Query OK, 0 rows affected (0.01 sec)mysql> CREATE PROCEDURE lc2() LANGUAGE JAVASCRIPT mysql>   AS mysql>   $$mysql>     const defaultLocale = Intl.DateTimeFormat().resolvedOptions().localemysql>     const n = 1234567.89;mysql>     console.log("Default Locale (", defaultLocale, "): ", n.toLocaleString());mysql>     console.log("ja_JP Locale: ", n.toLocaleString("ja-JP"));mysql>   $$;Query OK, 0 rows affected (0.01 sec)mysql> CALL lc2();Query OK, 0 rows affected (0.01 sec)mysql> SELECT mle_session_state("stdout");+--------------------------------------+| mle_session_state("stdout")          |+--------------------------------------+| Default Locale (fr-FR): 1 234 567,89  Using ja_JP locale: 1,234,567.89     |+--------------------------------------+1 row in set (0.04 sec)

You can usetoLocaleString() and other such methods to specify the locale for numbers and dates. For currency and other special numeric values, create an instance ofNumberFormat having the appropriate properties.

A JavaScript stored program continues to use by default the session locale setting that was in effect the first time it was invoked is executed during a given session remains in effect, even if the session locale setting is changed, until the session is reset. (This does not affect the result oftoLocaleString() orNumberFormat called with an explicit locale.) Iflc_time_names is updated, callmle_session_reset() to cause any existing stored programs to use the new locale setting by default instead. An example is shown here:

mysql> SELECT @@lc_time_names;+-----------------+| @@lc_time_names |+-----------------+| fr_FR           |+-----------------+1 row in set (0.00 sec)mysql> CALL lc1();Query OK, 0 rows affected (0.01 sec)mysql> SELECT mle_session_state("stdout");+-----------------------------+| mle_session_state("stdout") |+-----------------------------+|       Default Locale: fr-FR |+-----------------------------+1 row in set (0.04 sec)mysql> SET @@lc_time_names = "ja_JP";+-----------------+| @@lc_time_names |+-----------------+| ja_JP           |+-----------------+1 row in set (0.00 sec)mysql> CALL lc1();Query OK, 0 rows affected (0.01 sec)mysql> SELECT mle_session_state("stdout");+-----------------------------+| mle_session_state("stdout") |+-----------------------------+|       Default Locale: fr-FR |+-----------------------------+1 row in set (0.04 sec)mysql> SELECT mle_session_reset();+------------------------------------------+| mle_session_reset()                      |+------------------------------------------+| The session state is successfully reset. |+------------------------------------------+1 row in set (0.01 sec)mysql> CALL lc1();Query OK, 0 rows affected (0.01 sec)mysql> SELECT mle_session_state("stdout");+-----------------------------+| mle_session_state("stdout") |+-----------------------------+|       Default Locale: ja-JP |+-----------------------------+1 row in set (0.04 sec)