• Stars
    star
    320
  • Rank 131,126 (Top 3 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated almost 4 years ago

Reviews

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

Repository Details

An extensible SQL generation library for JavaScript with a focus on introspectibility

MoSQL - JSON to SQL

Put value and semantic meaning back into your queries by writing your SQL as JSON:

NPM

Gitter chat

var builder = require('mongo-sql');

var usersQuery = {
  type: 'select'
, table: 'users'
, where: { $or: { id: 5, name: 'Bob' } }
};

var result = builder.sql(usersQuery);

result.values     // Array of values
result.toString() // Sql string value

Result:

select "users".* from "users" where "users.id" = $1 or "users"."name" = $2

Want to play around with the syntax? Check out the playground, documentation, and examples.

Installation:

Node.js:

npm install mongo-sql

Require.js:

jam install mongo-sql

Why JSON?

There are plenty of SQL building libraries that use a very imperative style of building SQL queries. The approach is linear and typically requires a bunch of function chaining. It removes your ability to use the query as a value and requires the library consumer to build their queries in large clumps or all at once. It's sometimes impossible with some of these libraries to reflect on the current state of the query programmatically. What columns have I added? Have I already joined against my groups table? MoSQL uses standard data structures to accomplish its query building, so you can figure out the state of the query at all times.

The reason we use standard JavaScript data structures is so everything is easily manipulated. Arrays are arrays and objects are objects. Everyone knows how to interface with them.

JSON is also a prime candidate for becoming a universally understood data representation. By using Javascript objects, we do not rule out the possibility of interoping with and porting to other languages.

It may not be as pretty as other libraries, but prettiness is not a design principle of this library. The design principles are:

Extensibility

If a feature is not supported, you should be able to add your own functionality to make it supported.

Semantic Value

The query should be represented in a manner that makes sense to developer and machine. The use of standard data structures allows the developer to use standard APIs to manipulate the query.

Examples

{
  type: 'create-table'
, table: 'jobs'
, definition: {
    id:         { type: 'serial', primaryKey: true }
  , user_id:    { type: 'int', references: { table: 'users', column: 'id' } }
  , name:       { type: 'text' }
  , createdAt:  { type: 'timestamp', default: 'now()' }
  }
}

Sorry, these are in no particular order.

For even more examples, take a look at the ./tests directory.

How does it work?

Every MoSQL query has a query type specified that maps to a SQL string template. Query types are composed of various strings and query helpers whose output maps to functions.

So type: 'select' uses the query type defined as 'select'. Every other property in the query object maps to a query helper. The 'select' query type starts off like this:

{with} select {columns} {table}...

When you have the following query:

{ type: 'select', table: 'users' }

The table property is mapped to the table query helper.

98% of the functionality in MoSQL is defined through various helper interfaces. If the functionality you need doesn't exist, you can easily register your own behavior and keep on moving along. To see how all of the functionality was implemented, just check out the helpers folder. It uses the same API as library consumers to add its functionality.

Contributing

I will happily accept pull requests. Just write a test for whatever functionality you're providing. Coding style is an evolving thing here. I'll be JSHinting this repo soon and will make the coding style consistent when I do.

Developing

Mongo-sql development is done using Gulp. If you dont have gulp installed globally, install using npm install -g gulp. Then,

  1. Install all development dependencies
npm install
  1. Watch for source/spec files & run jshint/unit-test cases for changed files
gulp watch
  1. Before committing changes, run full jshinting & unit-test cases for browserified version using default gulp target
gulp

Upgrading from 2.4.x to 2.5.x

There are two things you need to look out for:

Do not rely on adding parenthesis to strings (like in columns or returning helpers) in order to prevent MoSQL from attempting to quote the input. Instead use the expression query type:

// select something_custom - another_custom as "custom_result" from "users"
{
  type: 'select'
, table: 'users'
, columns: [
    { expression: 'something_custom - another_custom', alias: 'custom_result' }
  ]
}

If you were relying on expression objects without a type specified to be converted into a function type, this will no longer happen. Queries without types with expression specified in them will get converted to the new expression type.

More Repositories

1

bootstrap-notify

Bootstrap alert system made better, builds off of bootstrap-alert.js
HTML
823
star
2

bootstrap-toggle

Bootstrap toggle switches - Fork it and make it better :D
JavaScript
102
star
3

gplaces

Dependency-free, google maps auto completion input
JavaScript
44
star
4

ti-infini-scroll

Infinite Scroll View for Titanium
JavaScript
37
star
5

trello-to-github

[Deprecated] Chrome extension to create github issues from trello cards.
JavaScript
22
star
6

node-pg-transaction

JavaScript
19
star
7

credit-card-logos

Flexible SVG credit card logo assets and CSS
HTML
16
star
8

jquery-popover

jquery popover plugin
CSS
11
star
9

mocha-perf-reporter

Mocha reporter for performance testing
JavaScript
10
star
10

rk-tools

RockChip tools for RK29xx and RK30xx generations
C
9
star
11

yokohama

Opinionated? dependency resolution library
JavaScript
9
star
12

pg-delta

Interface for running plpgsql delta scripts along with some plpgsql helper functions
JavaScript
7
star
13

backbone.present

View regions, swapping, transitions
JavaScript
6
star
14

jquery.preview

jQuery plugin for previewing hrefs
JavaScript
5
star
15

hiroshima

Opinionated? routing library
JavaScript
5
star
16

loglog

Loglog is an extensible, hierarchical logger with sensible transport methods for node.js and soon the browser
JavaScript
5
star
17

escher

A front-end web application architecture framework built on top of Backbone and RequireJS
JavaScript
4
star
18

pg-range-parser

Parses postgres range types
JavaScript
3
star
19

crazier-alert

CRAAAAZZZIER ALERTS FROM GOODYBAG
JavaScript
3
star
20

allanon

The Goodybag Website
JavaScript
3
star
21

api-presentation

JavaScript
3
star
22

mission

Apply CRUD permissions on your express APIs based on user groups
JavaScript
3
star
23

website

Goodybag website
JavaScript
3
star
24

jquery.row-expand

Expand table rows for additional information related to the target table row
JavaScript
3
star
25

gb-handlebars-helpers

Handlebars Helpers
JavaScript
3
star
26

rapleaf-wrapper

rapleaf api client for node
JavaScript
3
star
27

mongo-pg

A mongo-like interface for node-postgres utilizing mongo-sql
JavaScript
3
star
28

plan

Plan.js allows consumers to create values whose logic is broken up into individual and self-contained strategies. How those strategies interact with the end-value depends on the plan-type.
JavaScript
3
star
29

usd

Stamp/Model for handling USD-related logic
JavaScript
2
star
30

dev-quiz

JavaScript
2
star
31

nagoya

Data validation library
JavaScript
2
star
32

resource

Create HTTP API clients with ease
JavaScript
2
star
33

crazy-alert

Cuh-razy ALeRTiNg!!!!! - Test project for new Goodybag workflow.
JavaScript
2
star
34

github-oauth-proxy

Proxy requests to github for an oauth token to preserve client_secret for client side apps.
JavaScript
2
star
35

pg-type

Dynamically adds new types to the database and adds new values to _existing_ enums
JavaScript
2
star
36

elastic-client

Elasticsearch client for node.js
JavaScript
2
star
37

scheduler-app

Scheduler App
JavaScript
2
star
38

selenium-utils

Utility functions for selenium/webdriver
JavaScript
2
star
39

dirac-ensure-targets

Ensure insert/update documents only contain keys specified in dal schema
JavaScript
2
star
40

jobby

node job scheduling
JavaScript
1
star
41

loglog-server

Loglog logging web server
JavaScript
1
star
42

magic

The Goodybag API
JavaScript
1
star
43

cjsv

custom javascript validation
JavaScript
1
star
44

express-dirac-session

Express session middleware powered by dirac
JavaScript
1
star
45

mongojs-vs-mongode

Mongojs vs Mongode benchmark
JavaScript
1
star
46

rimit

Sensible Rate Limiter with Persistence
JavaScript
1
star
47

json-schema-benchmark

Benchmarks various json schema validators
JavaScript
1
star
48

tank-game

tank game
JavaScript
1
star
49

cater-api-server

hacking this together as fast as possible but with an eye for re-organization
JavaScript
1
star
50

FPImagePicker

Simple ios image picker that uploads to Filepicker
Objective-C
1
star
51

gplaces-demo

Demo site for https://github.com/goodybag/gplaces
CSS
1
star
52

loglog-mongodb

Mongodb Logging transport for loglog
JavaScript
1
star
53

file-transfer-over-soundcard

Source code for jury-rigged software modem
C
1
star
54

amd-bootstrap-modal

Boostrap Modal to be used with requirejs
JavaScript
1
star
55

jam-version-bug-test

Testing Jam's versioning
JavaScript
1
star
56

diet-tags

CSS
1
star
57

tokyo

Opinionated? flux framework
JavaScript
1
star
58

express-locals

Mixin properties into the `res.locals` object for each request
JavaScript
1
star