All Projects → mysqljs → Sqlstring

mysqljs / Sqlstring

Licence: mit
Simple SQL escape and format for MySQL

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Sqlstring

Orangehrm
OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures all the essential functionalities required for any enterprise.
Stars: ✭ 274 (-4.2%)
Mutual labels:  mysql
Yclas
Yclas Self Hosted is a powerful script that can transform any domain into a fully customizable classifieds site within a few seconds.
Stars: ✭ 276 (-3.5%)
Mutual labels:  mysql
Cool Admin Midway
cool-admin(midway版)一个很酷的后台权限管理框架,模块化、插件化、CRUD极速开发,永久开源免费,基于midway.js 2.0、typeorm、mysql、jwt、element-ui等构建
Stars: ✭ 204 (-28.67%)
Mutual labels:  mysql
Ruoyi Vue Pro
基于SpringBoot,Spring Security,JWT,Vue & Element 的前后端分离权限管理系统
Stars: ✭ 260 (-9.09%)
Mutual labels:  mysql
Docker Lamp
Docker with Apache, MySql, PhpMyAdmin and Php
Stars: ✭ 276 (-3.5%)
Mutual labels:  mysql
Phpminiadmin
extremely lightweight alternative to heavy phpMyAdmin for quick and easy access MySQL databases
Stars: ✭ 278 (-2.8%)
Mutual labels:  mysql
Mini Inventory And Sales Management System
An Inventory and Sales Management System written in PHP (codeIgniter) with support for MySQL and Sqlite3 databases
Stars: ✭ 273 (-4.55%)
Mutual labels:  mysql
Doctor
基于知识图谱的医学诊断系统。Medical Diagnosis System Based on Knowledge Map.
Stars: ✭ 286 (+0%)
Mutual labels:  mysql
Jsqlparser
JSqlParser parses an SQL statement and translate it into a hierarchy of Java classes. The generated hierarchy can be navigated using the Visitor Pattern
Stars: ✭ 3,405 (+1090.56%)
Mutual labels:  mysql
Arcemu
World Of Warcraft 3.3.5a server package
Stars: ✭ 281 (-1.75%)
Mutual labels:  mysql
Dbq
Zero boilerplate database operations for Go
Stars: ✭ 273 (-4.55%)
Mutual labels:  mysql
Laravel Vue
运用laravel5.4 + vue2.0 + elementui
Stars: ✭ 276 (-3.5%)
Mutual labels:  mysql
Sqlc
Generate type-safe code from SQL
Stars: ✭ 4,564 (+1495.8%)
Mutual labels:  mysql
Pg chameleon
MySQL to PostgreSQL replica system
Stars: ✭ 274 (-4.2%)
Mutual labels:  mysql
Typescript Node
📋 TypeScript and NodeJS project template.
Stars: ✭ 282 (-1.4%)
Mutual labels:  mysql
Shineframe
高性能超轻量级C++开发库及服务器编程框架
Stars: ✭ 274 (-4.2%)
Mutual labels:  mysql
Egg Mysql
MySQL plugin for egg
Stars: ✭ 276 (-3.5%)
Mutual labels:  mysql
Mysql
A pure node.js JavaScript Client implementing the MySQL protocol.
Stars: ✭ 16,878 (+5801.4%)
Mutual labels:  mysql
Sql Parser
A validating SQL lexer and parser with a focus on MySQL dialect.
Stars: ✭ 284 (-0.7%)
Mutual labels:  mysql
Spring Boot Mysql Rest Api Tutorial
Building a Restful CRUD API using Spring Boot, Mysql, JPA and Hibernate
Stars: ✭ 279 (-2.45%)
Mutual labels:  mysql

sqlstring

NPM Version NPM Downloads Node.js Version Build Status Coverage Status

Simple SQL escape and format for MySQL

Install

$ npm install sqlstring

Usage

var SqlString = require('sqlstring');

Escaping query values

Caution These methods of escaping values only works when the NO_BACKSLASH_ESCAPES SQL mode is disabled (which is the default state for MySQL servers).

In order to avoid SQL Injection attacks, you should always escape any user provided data before using it inside a SQL query. You can do so using the SqlString.escape() method:

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'

Alternatively, you can use ? characters as placeholders for values you would like to have escaped like this:

var userId = 1;
var sql    = SqlString.format('SELECT * FROM users WHERE id = ?', [userId]);
console.log(sql); // SELECT * FROM users WHERE id = 1

Multiple placeholders are mapped to values in the same order as passed. For example, in the following query foo equals a, bar equals b, baz equals c, and id will be userId:

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

This looks similar to prepared statements in MySQL, however it really just uses the same SqlString.escape() method internally.

Caution This also differs from prepared statements in that all ? are replaced, even those contained in comments and strings.

Different value types are escaped differently, here is how:

  • Numbers are left untouched
  • Booleans are converted to true / false
  • Date objects are converted to 'YYYY-mm-dd HH:ii:ss' strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects that have a toSqlString method will have .toSqlString() called and the returned value is used as the raw SQL.
  • Objects are turned into key = 'val' pairs for each enumerable property on the object. If the property's value is a function, it is skipped; if the property's value is an object, toString() is called on it and the returned value is used.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

You may have noticed that this escaping allows you to do neat things like this:

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'

And the toSqlString method allows you to form complex queries with functions:

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

To generate objects with a toSqlString method, the SqlString.raw() method can be used. This creates an object that will be left un-touched when using in a ? placeholder, useful for using functions as dynamic values:

Caution The string provided to SqlString.raw() will skip all escaping functions when used, so be careful when passing in unvalidated input.

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

If you feel the need to escape queries by yourself, you can also use the escaping function directly:

var sql = 'SELECT * FROM posts WHERE title=' + SqlString.escape('Hello MySQL');
console.log(sql); // SELECT * FROM posts WHERE title='Hello MySQL'

Escaping query identifiers

If you can't trust an SQL identifier (database / table / column name) because it is provided by a user, you should escape it with SqlString.escapeId(identifier) like this:

var sorter = 'date';
var sql    = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId(sorter);
console.log(sql); // SELECT * FROM posts ORDER BY `date`

It also supports adding qualified identifiers. It will escape both parts.

var sorter = 'date';
var sql    = 'SELECT * FROM posts ORDER BY ' + SqlString.escapeId('posts.' + sorter);
console.log(sql); // SELECT * FROM posts ORDER BY `posts`.`date`

If you do not want to treat . as qualified identifiers, you can set the second argument to true in order to keep the string as a literal identifier:

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`

Alternatively, you can use ?? characters as placeholders for identifiers you would like to have escaped like this:

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

Please note that this last character sequence is experimental and syntax might change

When you pass an Object to .escape() or .format(), .escapeId() is used to avoid SQL injection in object keys.

Formatting queries

You can use SqlString.format to prepare a query with multiple insertion points, utilizing the proper escaping for ids and values. A simple example of this follows:

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

Following this you then have a valid, escaped query that you can then send to the database safely. This is useful if you are looking to prepare the query before actually sending it to the database. You also have the option (but are not required) to pass in stringifyObject and timeZone, allowing you provide a custom means of turning objects into strings, as well as a location-specific/timezone-aware Date.

This can be further combined with the SqlString.raw() helper to generate SQL that includes MySQL functions as dynamic vales:

var userId = 1;
var data   = { email: '[email protected]', modified: SqlString.raw('NOW()') };
var sql    = SqlString.format('UPDATE ?? SET ? WHERE `id` = ?', ['users', data, userId]);
console.log(sql); // UPDATE `users` SET `email` = '[email protected]', `modified` = NOW() WHERE `id` = 1

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].