• This repository has been archived on 10/Nov/2021
  • Stars
    star
    1,566
  • Rank 29,900 (Top 0.6 %)
  • Language
    CoffeeScript
  • License
    MIT License
  • Created almost 13 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🏒 SQL query string builder for Javascript

NOTE: Squel is no longer actively maintained. I only have time for occasional bugfixes and small-scale work. If you are interested in helping with squel maintenance the help would be welcome. Alternatively, please use another library - we recommend knex.

squel - SQL query string builder

Build Status CDNJS NPM module NPM downloads Join the chat at https://discord.gg/PBAR2Bz Follow on Twitter

A flexible and powerful SQL query string builder for Javascript.

Full documentation (guide and API) at https://hiddentao.github.io/squel.

Features

  • Works in node.js and in the browser.
  • Supports the standard SQL queries: SELECT, UPDATE, INSERT and DELETE.
  • Supports non-standard commands for popular DB engines such as MySQL.
  • Supports paramterized queries for safe value escaping.
  • Can be customized to build any query or command of your choosing.
  • Uses method chaining for ease of use.
  • Small: ~7 KB minified and gzipped
  • And much more, see the guide..

WARNING: Do not ever pass queries generated on the client side to your web server for execution. Such a configuration would make it trivial for a casual attacker to execute arbitrary queriesβ€”as with an SQL-injection vector, but much easier to exploit and practically impossible to protect against.

Note: Squel is suitable for production use, but you may wish to consider more actively developed alternatives such as Knex

Installation

Install using npm:

$ npm install squel

Available files

  • squel.js - unminified version of Squel with the standard commands and all available non-standard commands added
  • squel.min.js - minified version of squel.js
  • squel-basic.js - unminified version of Squel with only the standard SQL commands
  • squel-basic.min.js - minified version of squel-basic.js

Examples

Before running the examples ensure you have squel installed and enabled at the top of your script:

var squel = require("squel");

SELECT

// SELECT * FROM table
squel.select()
    .from("table")
    .toString()

// SELECT t1.id, t2.name FROM table `t1` LEFT JOIN table2 `t2` ON (t1.id = t2.id) WHERE (t2.name <> 'Mark') AND (t2.name <> 'John') GROUP BY t1.id
squel.select()
    .from("table", "t1")
    .field("t1.id")
    .field("t2.name")
    .left_join("table2", "t2", "t1.id = t2.id")
    .group("t1.id")
    .where("t2.name <> 'Mark'")
    .where("t2.name <> 'John'")
    .toString()

// SELECT `t1`.`id`, `t1`.`name` as "My name", `t1`.`started` as "Date" FROM table `t1` WHERE age IN (RANGE(1, 1.2)) ORDER BY id ASC LIMIT 20
squel.select({ autoQuoteFieldNames: true })
    .from("table", "t1")
    .field("t1.id")
    .field("t1.name", "My name")
    .field("t1.started", "Date")
    .where("age IN ?", squel.str('RANGE(?, ?)', 1, 1.2))
    .order("id")
    .limit(20)
    .toString()

You can build parameterized queries:

/*
{
    text: "SELECT `t1`.`id`, `t1`.`name` as "My name", `t1`.`started` as "Date" FROM table `t1` WHERE age IN (RANGE(?, ?)) ORDER BY id ASC LIMIT 20",
    values: [1, 1.2]
}
*/
squel.select({ autoQuoteFieldNames: true })
    .from("table", "t1")
    .field("t1.id")
    .field("t1.name", "My name")
    .field("t1.started", "Date")
    .where("age IN ?", squel.str('RANGE(?, ?)', 1, 1.2))
    .order("id")
    .limit(20)
    .toParam()

You can use nested queries:

// SELECT s.id FROM (SELECT * FROM students) `s` INNER JOIN (SELECT id FROM marks) `m` ON (m.id = s.id)
squel.select()
    .from( squel.select().from('students'), 's' )
    .field('id')
    .join( squel.select().from('marks').field('id'), 'm', 'm.id = s.id' )
    .toString()

UPDATE

// UPDATE test SET f1 = 1
squel.update()
    .table("test")
    .set("f1", 1)
    .toString()

// UPDATE test, test2, test3 AS `a` SET test.id = 1, test2.val = 1.2, a.name = "Ram", a.email = NULL, a.count = a.count + 1
squel.update()
    .table("test")
    .set("test.id", 1)
    .table("test2")
    .set("test2.val", 1.2)
    .table("test3","a")
    .setFields({
        "a.name": "Ram",
        "a.email": null,
        "a.count = a.count + 1": undefined
    })
    .toString()

INSERT

// INSERT INTO test (f1) VALUES (1)
squel.insert()
    .into("test")
    .set("f1", 1)
    .toString()

// INSERT INTO test (name, age) VALUES ('Thomas', 29), ('Jane', 31)
squel.insert()
    .into("test")
    .setFieldsRows([
        { name: "Thomas", age: 29 },
        { name: "Jane", age: 31 }
    ])
    .toString()

DELETE

// DELETE FROM test
squel.delete()
    .from("test")
    .toString()

// DELETE FROM table1 WHERE (table1.id = 2) ORDER BY id DESC LIMIT 2
squel.delete()
    .from("table1")
    .where("table1.id = ?", 2)
    .order("id", false)
    .limit(2)

Paramterized queries

Use the useParam() method to obtain a parameterized query with a separate list of formatted parameter values:

// { text: "INSERT INTO test (f1, f2, f3, f4, f5) VALUES (?, ?, ?, ?, ?)", values: [1, 1.2, "TRUE", "blah", "NULL"] }
squel.insert()
    .into("test")
    .set("f1", 1)
    .set("f2", 1.2)
    .set("f3", true)
    .set("f4", "blah")
    .set("f5", null)
    .toParam()

Expression builder

There is also an expression builder which allows you to build complex expressions for WHERE and ON clauses:

// test = 3 OR test = 4
squel.expr()
    .or("test = 3")
    .or("test = 4")
    .toString()

// test = 3 AND (inner = 1 OR inner = 2) OR (inner = 3 AND inner = 4 OR (inner IN ('str1, 'str2', NULL)))
squel.expr()
    .and("test = 3")
    .and(
        squel.expr()
            .or("inner = 1")
            .or("inner = 2")
    )
    .or(
        squel.expr()
            .and("inner = ?", 3)
            .and("inner = ?", 4)
            .or(
                squel.expr()
                    .and("inner IN ?", ['str1', 'str2', null])
            )
    )
    .toString()

// SELECT * FROM test INNER JOIN test2 ON (test.id = test2.id) WHERE (test = 3 OR test = 4)
squel.select()
    .join( "test2", null, squel.expr().and("test.id = test2.id") )
    .where( squel.expr().or("test = 3").or("test = 4") )

Custom value types

By default Squel does not support the use of object instances as field values. Instead it lets you tell it how you want specific object types to be handled:

// handler for objects of type Date
squel.registerValueHandler(Date, function(date) {
  return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
});

squel.update().
  .table('students')
  .set('start_date', new Date(2013, 5, 1))
  .toString()

// UPDATE students SET start_date = '2013/6/1'

Note that custom value handlers can be overridden on a per-instance basis (see the docs)

Custom queries

Squel allows you to override the built-in query builders with your own as well as create your own types of queries:

// ------------------------------------------------------
// Setup the PRAGMA query builder
// ------------------------------------------------------
var util = require('util');   // to use util.inherits() from node.js

var CommandBlock = function() {};
util.inherits(CommandBlock, squel.cls.Block);

// private method - will not get exposed within the query builder
CommandBlock.prototype._command = function(_command) {
  this._command = _command;
}

// public method - will get exposed within the query builder
CommandBlock.prototype.compress = function() {
  this._command('compress');
};

CommandBlock.prototype.buildStr = function() {
  return this._command.toUpperCase();
};


// generic parameter block
var ParamBlock = function() {};
util.inherits(ParamBlock, squel.cls.Block);

ParamBlock.prototype.param = function(p) {
  this._p = p;
};

ParamBlock.prototype.buildStr = function() {
  return this._p;
};


// pragma query builder
var PragmaQuery = function(options) {
  squel.cls.QueryBuilder.call(this, options, [
      new squel.cls.StringBlock(options, 'PRAGMA'),
      new CommandBlock(),
      new ParamBlock()
  ]);
};
util.inherits(PragmaQuery, squel.cls.QueryBuilder);


// convenience method (we can override built-in squel methods this way too)
squel.pragma = function(options) {
  return new PragmaQuery(options)
};


// ------------------------------------------------------
// Build a PRAGMA query
// ------------------------------------------------------

squel.pragma()
  .compress()
  .param('test')
  .toString();

// 'PRAGMA COMPRESS test'

Examples of custom queries in the wild:

Non-standard SQL

Squel supports the standard SQL commands and reserved words. However a number of database engines provide their own non-standard commands. To make things easy Squel allows for different 'flavours' of SQL to be loaded and used.

At the moment Squel provides mysql, mssql and postgres flavours which augment query builders with additional commands (e.g. INSERT ... RETURNING for use with Postgres).

To use this in node.js:

var squel = require('squel').useFlavour('postgres');

For the browser:

<script type="text/javascript" src="https://rawgithub.com/hiddentao/squel/master/squel.min.js"></script>
<script type="text/javascript">
  squel = squel.useFlavour('postgres');
</script>

(Internally the flavour setup method simply utilizes the custom query mechanism to effect changes).

Read the the API docs to find out available commands. Flavours of SQL which get added to Squel in the future will be usable in the above manner.

Building it

To build the code and run the tests:

$ npm install
$ npm test <-- this will build the code and run the tests

Releasing it

Instructions for creating a new release of squel are in RELEASE.md.

Contributing

Contributions are welcome! Please see CONTRIBUTING.md.

Older verions

Note: The latest Squel version only works on Node 0.12 or above. Please use Squel 4.4.1 for Node <0.12. The old 4.x docs are also still available.

Ports to other languages

License

MIT - see LICENSE.md

More Repositories

1

fast-levenshtein

Efficient Javascript implementation of Levenshtein algorithm with locale-specific collator support.
JavaScript
580
star
2

google-tts

Javascript API for the Google Text-to-Speech engine
JavaScript
312
star
3

robe

MongoDB ODM for Node.js using ES6 generators. Supports schema validation, raw querying, oplog tailing, etc.
JavaScript
178
star
4

linear-algebra

Efficient, high-performance linear algebra for node.js and browsers
JavaScript
162
star
5

melkor

Wiki powered by Node.js and Git
JavaScript
149
star
6

ansijet

Ansible playbook automation server
CSS
110
star
7

react-native-modal-filter-picker

Cross-platform modal picker for React Native which supports keyword filtering, custom rendering, etc
JavaScript
104
star
8

gulp-server-livereload

Gulp plugin to run a local webserver with livereload enabled via socket.io. Also comes with standalone command-line interface.
JavaScript
92
star
9

cordova-plugin-filepath

Resolve native file paths from content URLs for Cordova platforms
Java
66
star
10

geth-private

Quickly setup a local, private Ethereum blockchain.
JavaScript
60
star
11

ethereum-abi-ui

Auto-generate UI form field definitions and associated validators from an Ethereum contract ABI
JavaScript
58
star
12

ethereum-event-logs

Ethereum event logs parser
JavaScript
48
star
13

browsermail

Javascript IMAP email client for browsers
JavaScript
47
star
14

mailmask

Mailmask - easy stop unwanted email. Unlimited, free temporary email addresses, all forwarding to your real email address. Beat spam, protect your privacy.
JavaScript
39
star
15

lzw-async

Asynchronous Javascript implementation of LZW compression algorithm
HTML
38
star
16

wp-flickr-embed

Insert Flickr images into your Wordpress posts using an interactive interface
PHP
19
star
17

gulp-bench

Gulp plugin for running performance benchmarks
JavaScript
17
star
18

react-image-holder

React image component with offline placeholder fallbacks
JavaScript
17
star
19

koa-session-mongo

MongoDB storage layer for Koa session middleware
JavaScript
16
star
20

ethval

Easier calculation and formatting of Ethereum values
JavaScript
16
star
21

weber

Compile scripts, stylesheets and templates on-the-fly for rapid iterations
CoffeeScript
14
star
22

ethereum-contracts

Robust Ethereum contracts wrapper for easier deployment, method invocation and automatic type conversion.
JavaScript
14
star
23

clockmaker

Flexible Javascript timers which can be paused and modified on-the-fly
JavaScript
13
star
24

react-native-advanced-forms

Flexible React Native architecture for building and managing forms
JavaScript
13
star
25

koa-session-store

Session middleware for Koa with a pluggable storage layer
JavaScript
12
star
26

simple-mongo-schema

DEPRECATED. An easy-to-write schema validator for Mongo JSON objects
JavaScript
12
star
27

sjv

🚦 An easy-to-write schema and deep validator for JSON documents
JavaScript
11
star
28

ethereum-blocks

Process blocks from Ethereum client nodes robustly. Catch-up on restart, auto-reconnect to node, etc.
JavaScript
11
star
29

git-pull-cron

Git clone a repo into a folder and then schedule a cronjob to git pull updates
JavaScript
10
star
30

machine-learning

High-performance machine learning library for node.js and browsers
JavaScript
8
star
31

jquery.ajaxprogress

jQuery AJAX Progress plugin
JavaScript
8
star
32

drush_simpletest_command

An improved Drush SimpleTest command which allows you to run a single Drupal test from the command-line
7
star
33

elrond-voting-contract

Commit-reveal voting contract written in Rust for Elrond VM
Rust
6
star
34

page-tagger

A Wordpress plugin which lets you tag your pages just like you do with your posts
PHP
6
star
35

immutable-state-machine

Immutable state machine for Javascript with ability to associate extra data with each state. Useful for React.
JavaScript
6
star
36

askthensa

http://askthensa.com
5
star
37

ethereum-token-sales

Various Ethereum token sale contracts
5
star
38

mongo-replica-set

Command-line tool and API for setting up MongoDB replica sets on localhost
JavaScript
5
star
39

cron-async

Execute something on a schedule, using cron syntax, with async/await support.
TypeScript
4
star
40

patterns2

An improved version of the Drupal Patterns module.
PHP
4
star
41

es6-slides

Slides on the new features in Javascript ES6
JavaScript
4
star
42

react-native-extended-stylesheet-breakpoints

Smart responsive @media query generation for react-native-extended-stylesheets using configurable breakpoints
JavaScript
4
star
43

opengraph_meta

Drupal module which adds Open Graph meta tags to node pages for better social network sharing (e.g. http://developers.facebook.com/docs/share)
PHP
3
star
44

mocha-ci-slack-reporter

Slack reporter for Mocha when running in CI environments
JavaScript
2
star
45

ois-incidents-map

Officer-involved Shootings map of the USA
JavaScript
2
star
46

react-hooks

A collection of useful React hooks for async programming, web3, etc
TypeScript
2
star
47

node-generator-perf-tests

Some performance tests for when using generators in node.js
JavaScript
2
star
48

zhongwen

The source code to the zhongwen.co.uk website
JavaScript
2
star
49

ethanol

Desktop Solidity IDE **Work in progress**
JavaScript
2
star
50

react-native-xcode-packager

Custom XCode packager script for react-native which ensure bundle always gets built
Shell
2
star
51

logarama

Logging for the browser, logging levels, hierarchical child loggers, smart formatting, etc
JavaScript
2
star
52

documentation-lite

Extract JSDoc documentation from ES5/ES6 files into a JSON output structure.
JavaScript
2
star
53

us_latlng_json

JSON dataset of latitude and longitude co-ordinates for USA state counties and cities
2
star
54

abide

Base class with pub-sub and observers for JS object properties using ECMA5 getters/setters
JavaScript
2
star
55

genomatic

Utility methods for working with Generator functions, such as bind(), is(), etc
JavaScript
1
star
56

ethgoal

Goal achievement powered by Ethereum
JavaScript
1
star
57

phonegap-demo-app

CSS
1
star
58

indium

Reactive web framework for Node.js utilising RethinkDB and ReactJS
1
star
59

updates_notifier

Redmine plugin which update notifications to a callback URL when changes are made within Redmine
Ruby
1
star
60

saffronvideo

A Drupal module to make it easy to use Saffron media server assets.
PHP
1
star
61

smart-solidity-docs

Getting to grips with the Solidity programming language for the Ethereum blockchain
1
star
62

docjam

Javascript ES6 documentation extractor using markdown and jsdoc
JavaScript
1
star
63

method-mocks

Works with existing mocking and testing frameworks (e.g. Jest) to make method mocking easier.
JavaScript
1
star
64

hiddentao.com

HiddenTao website
JavaScript
1
star
65

nodejs-intro

Introduction to Node.js - building a chatroom using ExpressJS and Socket.IO
JavaScript
1
star
66

i21n

Tiny internationalization library for Node and the Browser
JavaScript
1
star
67

bulksms

BulkSMS API for TextAnywhere service
PHP
1
star
68

calc

Simple HTML5 calculator
HTML
1
star
69

uc_bulk_stock_updater

This is a Ubercart (Drupal) extension module which enables you to easily product stock levels on one page.
JavaScript
1
star
70

latlong-route-cleaner

Simple PHP script for cleaning out bad lat-long points form a driving route
PHP
1
star