### Install sqlstring with npm Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Use npm to install the sqlstring package. This is the first step before requiring the module in your Node.js application. ```sh npm install sqlstring ``` -------------------------------- ### Require sqlstring module Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Import the sqlstring module into your JavaScript file to start using its functions for SQL string manipulation. ```js var SqlString = require('sqlstring'); ``` -------------------------------- ### Format Query with Table and Column Placeholders Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Prepare a query with multiple insertion points using `SqlString.format`. Use `??` for identifiers (tables, columns) and `?` for values. ```javascript var userId = 1; var inserts = ['users', 'id', userId]; var sql = SqlString.format('SELECT * FROM ?? WHERE ?? = ?', inserts); console.log(sql); // SELECT * FROM `users` WHERE `id` = 1 ``` -------------------------------- ### Use Raw SQL Functions with SqlString.raw() Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Use `SqlString.raw()` to create an object that will be inserted as-is into a formatted query, bypassing escaping. Be cautious with unvalidated input. ```javascript var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()'); var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 ``` -------------------------------- ### Format Query with MySQL Functions Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Combine `SqlString.format` with `SqlString.raw()` to include dynamic MySQL functions within your queries, such as `NOW()`. ```javascript var userId = 1; var data = { email: 'foobar@example.com', modified: SqlString.raw('NOW()') }; var sql = SqlString.format('UPDATE ?? SET ? WHERE `id` = ?', ['users', data, userId]); console.log(sql); // UPDATE `users` SET `email` = 'foobar@example.com', `modified` = NOW() WHERE `id` = 1 ``` -------------------------------- ### Format SQL Query with Simple Value Placeholder Source: https://context7.com/mysqljs/sqlstring/llms.txt Use `?` for simple value placeholders. Values are escaped using `escape()` and matched in order. ```javascript var SqlString = require('sqlstring'); // Simple value placeholder var userId = 1; var sql = SqlString.format('SELECT * FROM users WHERE id = ?', [userId]); console.log(sql); // Output: SELECT * FROM users WHERE id = 1 ``` -------------------------------- ### Format SQL Query with Multiple Value Placeholders Source: https://context7.com/mysqljs/sqlstring/llms.txt Handles multiple `?` placeholders by substituting values from the provided array in sequence. ```javascript var SqlString = require('sqlstring'); // Multiple value placeholders var sql = SqlString.format( 'UPDATE users SET name = ?, email = ? WHERE id = ?', ['John Doe', 'john@example.com', 42] ); console.log(sql); // Output: UPDATE users SET name = 'John Doe', email = 'john@example.com' WHERE id = 42 ``` -------------------------------- ### Format SQL Query with Object for SET Clause Source: https://context7.com/mysqljs/sqlstring/llms.txt When a single object is provided for a `?` placeholder in a `SET` clause, its properties are converted into key-value pairs. ```javascript var SqlString = require('sqlstring'); // Object as value for SET clause var post = { title: 'Hello World', content: 'My first post', views: 0 }; var sql = SqlString.format('INSERT INTO posts SET ?', post); console.log(sql); // Output: INSERT INTO posts SET `title` = 'Hello World', `content` = 'My first post', `views` = 0 ``` -------------------------------- ### Format SQL Queries with Placeholders Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Use `SqlString.format()` with `?` placeholders to automatically escape values and insert them into SQL queries. Values are mapped to placeholders in the order they are provided. ```javascript var userId = 1; var sql = SqlString.format('SELECT * FROM users WHERE id = ?', [userId]); console.log(sql); // SELECT * FROM users WHERE id = 1 ``` ```javascript var userId = 1; var sql = SqlString.format('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId]); console.log(sql); // UPDATE users SET foo = 'a', bar = 'b', baz = 'c' WHERE id = 1 ``` -------------------------------- ### Format SQL Query with Mixed Identifiers and Values Source: https://context7.com/mysqljs/sqlstring/llms.txt Combines `?` for values and `??` for identifiers in a single SQL query string. ```javascript var SqlString = require('sqlstring'); // Mixed identifiers and values var columns = ['id', 'name', 'email']; var sql = SqlString.format('SELECT ?? FROM ?? WHERE status = ?', [columns, 'users', 'active']); console.log(sql); // Output: SELECT `id`, `name`, `email` FROM `users` WHERE status = 'active' ``` -------------------------------- ### Create Raw SQL String for MySQL Functions Source: https://context7.com/mysqljs/sqlstring/llms.txt Use `SqlString.raw()` to create a string that will not be escaped, suitable for MySQL functions or pre-validated SQL fragments. Exercise caution as this bypasses escaping. ```javascript var SqlString = require('sqlstring'); // Using MySQL functions with raw() var CURRENT_TIMESTAMP = SqlString.raw('CURRENT_TIMESTAMP()'); var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); console.log(sql); // Output: UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 ``` ```javascript var SqlString = require('sqlstring'); // Using NOW() function var sql = SqlString.format( 'INSERT INTO logs SET message = ?, created_at = ?', ['User logged in', SqlString.raw('NOW()')] ); console.log(sql); // Output: INSERT INTO logs SET message = 'User logged in', created_at = NOW() ``` ```javascript var SqlString = require('sqlstring'); // Complex expressions var sql = SqlString.format( 'UPDATE counters SET value = ? WHERE id = ?', [SqlString.raw('value + 1'), 1] ); console.log(sql); // Output: UPDATE counters SET value = value + 1 WHERE id = 1 ``` ```javascript var SqlString = require('sqlstring'); // Combining raw with object values var data = { email: 'user@example.com', updated_at: SqlString.raw('NOW()'), login_count: SqlString.raw('login_count + 1') }; var sql = SqlString.format('UPDATE users SET ? WHERE id = ?', [data, 5]); console.log(sql); // Output: UPDATE users SET `email` = 'user@example.com', `updated_at` = NOW(), `login_count` = login_count + 1 WHERE id = 5 ``` -------------------------------- ### Format Query with Identifier Placeholders Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Use `SqlString.format` with `??` placeholders for identifiers that need to be escaped. This method is experimental and syntax may change. ```javascript var userId = 1; var columns = ['username', 'email']; var sql = SqlString.format('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId]); console.log(sql); // SELECT `username`, `email` FROM `users` WHERE id = 1 ``` -------------------------------- ### Create Raw SQL String with Custom toSqlString Source: https://context7.com/mysqljs/sqlstring/llms.txt An object with a `toSqlString()` method can be used similarly to `SqlString.raw()` to insert custom SQL fragments without escaping. ```javascript var SqlString = require('sqlstring'); // Custom toSqlString object (equivalent to raw()) var customValue = { toSqlString: function() { return 'CONCAT(first_name, " ", last_name)'; } }; var sql = SqlString.format('SELECT ? AS full_name FROM users', [customValue]); console.log(sql); // Output: SELECT CONCAT(first_name, " ", last_name) AS full_name FROM users ``` -------------------------------- ### Format SQL Query with Identifier Placeholders Source: https://context7.com/mysqljs/sqlstring/llms.txt Use `??` for identifier placeholders (table or column names). These are escaped using `escapeId()`. ```javascript var SqlString = require('sqlstring'); // Identifier placeholders with ?? var table = 'users'; var column = 'email'; var sql = SqlString.format('SELECT ?? FROM ?? WHERE id = ?', [column, table, 1]); console.log(sql); // Output: SELECT `email` FROM `users` WHERE id = 1 ``` -------------------------------- ### SqlString.bufferToString Source: https://context7.com/mysqljs/sqlstring/llms.txt Converts a Node.js Buffer object to a MySQL hex string format (`X'...'`), which is suitable for storing binary data in BLOB or BINARY columns. ```APIDOC ## SqlString.bufferToString(buffer) ### Description Converts a Node.js Buffer to a MySQL hex string format (`X'...'`), suitable for storing binary data in BLOB or BINARY columns. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **buffer** (Buffer) - Required - The Node.js Buffer object to convert. ### Request Example ```javascript var SqlString = require('sqlstring'); var buffer = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]); // "Hello" in bytes console.log(SqlString.bufferToString(buffer)); ``` ### Response #### Success Response (200) - **string** - A MySQL hex string representation of the buffer. #### Response Example ``` X'48656c6c6f' ``` ``` -------------------------------- ### Insert Objects with SqlString.format() Source: https://github.com/mysqljs/sqlstring/blob/master/README.md When using `SqlString.format()` with an object as a value, it generates `key = 'value'` pairs for each enumerable property, suitable for `INSERT INTO ... SET` statements. ```javascript var post = {id: 1, title: 'Hello MySQL'}; var sql = SqlString.format('INSERT INTO posts SET ?', post); console.log(sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL' ``` -------------------------------- ### SqlString.format Source: https://context7.com/mysqljs/sqlstring/llms.txt Formats a SQL query by replacing placeholder characters with properly escaped values. Uses '?' for value placeholders and '??' for identifier placeholders. ```APIDOC ## SqlString.format(sql, values, stringifyObjects, timeZone) ### Description Formats a SQL query by replacing placeholder characters with properly escaped values. Values are matched to placeholders in order. ### Parameters - **sql** (string) - Required - The SQL query string containing placeholders. - **values** (array|any) - Optional - The values to replace the placeholders with. - **stringifyObjects** (boolean) - Optional - Whether to stringify objects. - **timeZone** (string) - Optional - The timezone to use for date formatting. ### Request Example SqlString.format('SELECT * FROM users WHERE id = ?', [1]); ### Response - **result** (string) - The formatted SQL query string. ``` -------------------------------- ### SqlString.raw Source: https://context7.com/mysqljs/sqlstring/llms.txt Creates a raw SQL string object that will not be escaped when used as a value in format() or escape(). ```APIDOC ## SqlString.raw(sql) ### Description Creates a raw SQL string object that bypasses escaping. Useful for inserting MySQL functions or pre-validated SQL fragments. ### Parameters - **sql** (string) - Required - The raw SQL fragment. ### Response - **object** (object) - An object with a toSqlString() method. ``` -------------------------------- ### Convert Node.js Buffer to MySQL Hex String Source: https://context7.com/mysqljs/sqlstring/llms.txt SqlString.bufferToString converts a Node.js Buffer into a MySQL hex string format (X'...') suitable for BLOB or BINARY columns. This is useful for storing binary data safely in your database. ```javascript var SqlString = require('sqlstring'); // Convert buffer to hex string var buffer = Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]); // "Hello" in bytes console.log(SqlString.bufferToString(buffer)); // Output: X'48656c6c6f' ``` ```javascript var SqlString = require('sqlstring'); // Binary data var binaryData = Buffer.from([0x00, 0xff, 0x0a, 0x0b]); var sql = 'INSERT INTO files (data) VALUES (' + SqlString.bufferToString(binaryData) + ')'; console.log(sql); // Output: INSERT INTO files (data) VALUES (X'00ff0a0b') ``` ```javascript var SqlString = require('sqlstring'); // Using buffer with escape() var buffer = Buffer.from('binary data'); var sql = SqlString.format('INSERT INTO blobs SET content = ?', [buffer]); console.log(sql); // Output: INSERT INTO blobs SET content = X'62696e6172792064617461' ``` -------------------------------- ### Use Raw SQL Functions with toSqlString Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Define a `toSqlString` method on an object to insert raw SQL fragments, such as function calls, directly into formatted queries. This bypasses standard escaping. ```javascript var CURRENT_TIMESTAMP = { toSqlString: function() { return 'CURRENT_TIMESTAMP()'; } }; var sql = SqlString.format('UPDATE posts SET modified = ? WHERE id = ?', [CURRENT_TIMESTAMP, 42]); console.log(sql); // UPDATE posts SET modified = CURRENT_TIMESTAMP() WHERE id = 42 ``` -------------------------------- ### Format SQL Query with Single Value Source: https://context7.com/mysqljs/sqlstring/llms.txt A single value can be passed directly without wrapping it in an array for a `?` placeholder. ```javascript var SqlString = require('sqlstring'); // Single value without array wrapper var sql = SqlString.format('SELECT * FROM users WHERE id = ?', 42); console.log(sql); // Output: SELECT * FROM users WHERE id = 42 ``` -------------------------------- ### Convert Nested Arrays to SQL List for Bulk Inserts Source: https://context7.com/mysqljs/sqlstring/llms.txt Converts a nested array (array of arrays) into a format suitable for bulk `INSERT` statements, where each inner array represents a row. ```javascript var SqlString = require('sqlstring'); // Nested arrays for bulk inserts var rows = [ ['John', 'john@example.com', 25], ['Jane', 'jane@example.com', 30], ['Bob', 'bob@example.com', 35] ]; var sql = 'INSERT INTO users (name, email, age) VALUES ' + SqlString.arrayToList(rows); console.log(sql); // Output: INSERT INTO users (name, email, age) VALUES ('John', 'john@example.com', 25), ('Jane', 'jane@example.com', 30), ('Bob', 'bob@example.com', 35) ``` -------------------------------- ### SqlString.arrayToList Source: https://context7.com/mysqljs/sqlstring/llms.txt Converts an array to a SQL list format, suitable for comma-separated values or bulk INSERT operations. ```APIDOC ## SqlString.arrayToList(array, timeZone) ### Description Converts an array to a SQL list format. Simple arrays become comma-separated values, while nested arrays become grouped lists. ### Parameters - **array** (array) - Required - The array to convert. - **timeZone** (string) - Optional - The timezone to use for date formatting. ### Response - **result** (string) - The SQL list string. ``` -------------------------------- ### Convert Object to SQL Key-Value Pairs Source: https://context7.com/mysqljs/sqlstring/llms.txt Use SqlString.objectToValues to convert a JavaScript object into a string of `key = value` pairs, suitable for SQL UPDATE SET clauses or INSERT SET syntax. Function properties within the object are ignored, and all keys are automatically escaped as SQL identifiers. ```javascript var SqlString = require('sqlstring'); // Basic object to values var user = { name: 'John', email: 'john@example.com', age: 30 }; console.log(SqlString.objectToValues(user)); // Output: `name` = 'John', `email` = 'john@example.com', `age` = 30 ``` ```javascript var SqlString = require('sqlstring'); // Object with various types var data = { title: 'Hello World', views: 100, published: true, deleted_at: null }; var sql = 'UPDATE posts SET ' + SqlString.objectToValues(data) + ' WHERE id = 1'; console.log(sql); // Output: UPDATE posts SET `title` = 'Hello World', `views` = 100, `published` = true, `deleted_at` = NULL WHERE id = 1 ``` ```javascript var SqlString = require('sqlstring'); // Functions are skipped var objWithFunc = { name: 'Test', getValue: function() { return 42; } }; console.log(SqlString.objectToValues(objWithFunc)); // Output: `name` = 'Test' ``` -------------------------------- ### Convert Array with Mixed Types to SQL List Source: https://context7.com/mysqljs/sqlstring/llms.txt Handles arrays containing mixed data types, converting them to their SQL string representations. ```javascript var SqlString = require('sqlstring'); // Mixed types in array var mixed = [1, 'hello', true, null]; console.log(SqlString.arrayToList(mixed)); // Output: 1, 'hello', true, NULL ``` -------------------------------- ### Convert Simple Array to SQL List Source: https://context7.com/mysqljs/sqlstring/llms.txt Converts a simple JavaScript array into a comma-separated string suitable for SQL `IN` clauses or `VALUES` lists. ```javascript var SqlString = require('sqlstring'); // Simple array to list var values = ['apple', 'banana', 'cherry']; console.log(SqlString.arrayToList(values)); // Output: 'apple', 'banana', 'cherry' ``` -------------------------------- ### Format SQL Query with Timezone for Dates Source: https://context7.com/mysqljs/sqlstring/llms.txt The `timeZone` parameter can be used to format date values according to a specific timezone offset. ```javascript var SqlString = require('sqlstring'); // Using timezone parameter for dates var date = new Date('2024-03-15T10:30:00Z'); var sql = SqlString.format('SELECT * FROM events WHERE created_at > ?', [date], false, '+05:30'); console.log(sql); // Output: SELECT * FROM events WHERE created_at > '2024-03-15 16:00:00.000' ``` -------------------------------- ### Escape User Input with SqlString.escape() Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Use `SqlString.escape()` to safely escape user-provided string values before including them in SQL queries to prevent SQL injection. ```javascript var userId = 'some user provided value'; var sql = 'SELECT * FROM users WHERE id = ' + SqlString.escape(userId); console.log(sql); // SELECT * FROM users WHERE id = 'some user provided value' ``` ```javascript var sql = 'SELECT * FROM posts WHERE title=' + SqlString.escape('Hello MySQL'); console.log(sql); // SELECT * FROM posts WHERE title='Hello MySQL' ``` -------------------------------- ### SqlString.objectToValues Source: https://context7.com/mysqljs/sqlstring/llms.txt Converts a JavaScript object into a string of SQL `key = value` pairs, suitable for UPDATE SET clauses or INSERT SET syntax. Function properties within the object are skipped, and all keys are escaped as identifiers. ```APIDOC ## SqlString.objectToValues(object, timeZone) ### Description Converts an object to SQL `key = value` pairs format, suitable for UPDATE SET clauses or INSERT SET syntax. Function properties are skipped, and all keys are escaped as identifiers. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **object** (object) - Required - The JavaScript object to convert. - **timeZone** (string) - Optional - The timezone to use for date conversions (if applicable within the object values). ### Request Example ```javascript var SqlString = require('sqlstring'); var user = { name: 'John', email: 'john@example.com', age: 30 }; console.log(SqlString.objectToValues(user)); ``` ### Response #### Success Response (200) - **string** - A string of SQL `key = value` pairs. #### Response Example ``` `name` = 'John', `email` = 'john@example.com', `age` = 30 ``` ``` -------------------------------- ### SqlString.dateToString Source: https://context7.com/mysqljs/sqlstring/llms.txt Converts a JavaScript Date object to a MySQL datetime string format (`YYYY-MM-DD HH:mm:ss.mmm`). It supports timezone conversion using 'local' for local time or timezone offset strings like '+05:30' or 'Z' for UTC. ```APIDOC ## SqlString.dateToString(date, timeZone) ### Description Converts a JavaScript Date object to a MySQL datetime string format (`YYYY-MM-DD HH:mm:ss.mmm`). Supports timezone conversion using 'local' for local time or timezone offset strings like '+05:30' or 'Z' for UTC. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **date** (Date) - Required - The JavaScript Date object to convert. - **timeZone** (string) - Optional - The timezone to use for conversion. Can be 'local', 'Z' (for UTC), or a timezone offset string (e.g., '+05:30'). Defaults to 'local'. ### Request Example ```javascript var SqlString = require('sqlstring'); var date = new Date('2024-03-15T10:30:45.123'); console.log(SqlString.dateToString(date, 'local')); ``` ### Response #### Success Response (200) - **string** - A MySQL formatted datetime string or 'NULL' if the date is invalid. #### Response Example ``` '2024-03-15 10:30:45.123' ``` ``` -------------------------------- ### Escape Literal SQL Identifiers Source: https://github.com/mysqljs/sqlstring/blob/master/README.md To prevent `.` from being treated as a qualifier, set the second argument of `SqlString.escapeId` to `true` to treat the entire string as a literal identifier. ```javascript var sorter = 'date.2'; var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter, true); console.log(sql); // SELECT * FROM posts ORDER BY `date.2` ``` -------------------------------- ### Escape values with SqlString.escape Source: https://context7.com/mysqljs/sqlstring/llms.txt Use this method to safely escape user-provided values for SQL queries. It handles strings, numbers, booleans, dates, arrays, objects, and buffers. ```javascript var SqlString = require('sqlstring'); // Escaping strings - prevents SQL injection var userInput = "Robert'; DROP TABLE users;--"; var sql = 'SELECT * FROM users WHERE name = ' + SqlString.escape(userInput); console.log(sql); // Output: SELECT * FROM users WHERE name = 'Robert\'; DROP TABLE users;--' // Escaping numbers - left untouched console.log(SqlString.escape(123)); // Output: 123 // Escaping booleans console.log(SqlString.escape(true)); // Output: true console.log(SqlString.escape(false)); // Output: false // Escaping null/undefined console.log(SqlString.escape(null)); // Output: NULL console.log(SqlString.escape(undefined)); // Output: NULL // Escaping Date objects var date = new Date('2024-03-15T10:30:00'); console.log(SqlString.escape(date)); // Output: '2024-03-15 10:30:00.000' // Escaping arrays - becomes comma-separated list var ids = [1, 2, 3]; var sql = 'SELECT * FROM users WHERE id IN (' + SqlString.escape(ids) + ')'; console.log(sql); // Output: SELECT * FROM users WHERE id IN (1, 2, 3) // Escaping nested arrays for bulk inserts var rows = [['a', 'b'], ['c', 'd']]; console.log(SqlString.escape(rows)); // Output: ('a', 'b'), ('c', 'd') // Escaping Buffer objects var buffer = Buffer.from([0x0f, 0xa5]); console.log(SqlString.escape(buffer)); // Output: X'0fa5' // Escaping objects - becomes key = value pairs var data = { name: 'John', age: 30 }; console.log(SqlString.escape(data)); // Output: `name` = 'John', `age` = 30 ``` -------------------------------- ### Escape SQL Identifiers Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Use `SqlString.escapeId` to safely escape database, table, or column names when they are provided by a user. This prevents SQL injection. ```javascript var sorter = 'date'; var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter); console.log(sql); // SELECT * FROM posts ORDER BY `date` ``` -------------------------------- ### SqlString.escape Source: https://context7.com/mysqljs/sqlstring/llms.txt Escapes a value for safe use in a SQL query, handling strings, numbers, booleans, dates, arrays, objects, and buffers. ```APIDOC ## SqlString.escape(val, stringifyObjects, timeZone) ### Description Escapes a value for safe use in a SQL query. Handles multiple data types: strings are safely escaped, numbers and booleans are converted to their SQL equivalents, Date objects become formatted datetime strings, arrays become comma-separated lists, objects become `key = value` pairs, and `null`/`undefined` become `NULL`. ### Parameters - **val** (any) - Required - The value to escape. - **stringifyObjects** (boolean) - Optional - Whether to stringify objects. - **timeZone** (string) - Optional - The timezone for date formatting. ### Response - **string** - The escaped SQL-safe string representation of the input value. ``` -------------------------------- ### Escape identifiers with SqlString.escapeId Source: https://context7.com/mysqljs/sqlstring/llms.txt Use this method to escape database, table, or column names. It wraps identifiers in backticks and handles qualified identifiers by default. ```javascript var SqlString = require('sqlstring'); // Basic identifier escaping var column = 'user_name'; var sql = 'SELECT ' + SqlString.escapeId(column) + ' FROM users'; console.log(sql); // Output: SELECT `user_name` FROM users // Escaping user-provided column names safely var sortColumn = 'created_at'; var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sortColumn); console.log(sql); // Output: SELECT * FROM posts ORDER BY `created_at` // Qualified identifiers (table.column) - dot separates parts var qualified = 'users.email'; console.log(SqlString.escapeId(qualified)); // Output: `users`.`email` // Literal identifier with dot in name (forbidQualified = true) var columnWithDot = 'price.usd'; console.log(SqlString.escapeId(columnWithDot, true)); // Output: `price.usd` // Escaping array of identifiers var columns = ['id', 'name', 'email']; var sql = 'SELECT ' + SqlString.escapeId(columns) + ' FROM users'; console.log(sql); // Output: SELECT `id`, `name`, `email` FROM users // Handling backticks in identifiers (doubled for escaping) var dangerous = 'column`name'; console.log(SqlString.escapeId(dangerous)); // Output: `column``name` ``` -------------------------------- ### SqlString.escapeId Source: https://context7.com/mysqljs/sqlstring/llms.txt Escapes a SQL identifier (database, table, or column name) by wrapping it in backticks. ```APIDOC ## SqlString.escapeId(val, forbidQualified) ### Description Escapes a SQL identifier (database, table, or column name) by wrapping it in backticks. By default, dots are treated as qualified identifier separators and each part is escaped separately. Set `forbidQualified` to `true` to escape the entire string as a literal identifier. ### Parameters - **val** (string|Array) - Required - The identifier or array of identifiers to escape. - **forbidQualified** (boolean) - Optional - If true, treats the input as a single literal identifier even if it contains dots. ### Response - **string** - The escaped SQL identifier string. ``` -------------------------------- ### Escape Qualified SQL Identifiers Source: https://github.com/mysqljs/sqlstring/blob/master/README.md Escape both parts of a qualified identifier (e.g., 'table.column') using `SqlString.escapeId` by passing the combined string. ```javascript var sorter = 'date'; var sql = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId('posts.' + sorter); console.log(sql); // SELECT * FROM posts ORDER BY `posts`.`date` ``` -------------------------------- ### Format JavaScript Date to MySQL Datetime String Source: https://context7.com/mysqljs/sqlstring/llms.txt SqlString.dateToString converts a JavaScript Date object into a MySQL datetime string format ('YYYY-MM-DD HH:mm:ss.mmm'). It supports timezone conversion using 'local' for the client's local time, 'Z' for UTC, or custom timezone offset strings like '+05:30'. Invalid dates are converted to NULL. ```javascript var SqlString = require('sqlstring'); // Local timezone (default) var date = new Date('2024-03-15T10:30:45.123'); console.log(SqlString.dateToString(date, 'local')); // Output: '2024-03-15 10:30:45.123' ``` ```javascript var SqlString = require('sqlstring'); // UTC timezone var date = new Date('2024-03-15T10:30:45.123Z'); console.log(SqlString.dateToString(date, 'Z')); // Output: '2024-03-15 10:30:45.123' ``` ```javascript var SqlString = require('sqlstring'); // Custom timezone offset var date = new Date('2024-03-15T10:30:45.123Z'); console.log(SqlString.dateToString(date, '+05:30')); // Output: '2024-03-15 16:00:45.123' ``` ```javascript var SqlString = require('sqlstring'); // Invalid date returns NULL var invalidDate = new Date('invalid'); console.log(SqlString.dateToString(invalidDate, 'local')); // Output: NULL ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.