Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including sqltomango with all npm packages installed. Try it out:

var sqltomango = require("sqltomango")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

sqltomango v1.2.2

Converts SQL statements into CouchDB Mango (Cloudant Query) JSON queries

sqltomango

Build Status npm version

A simple Node.js library that converts Structured Query Language (SQL) into CouchDB Mango / Cloudant Query JSON objects. Mango is the code name for the query language used in Apache CouchDB and IBM Cloudant. It uses JSON to represent queries. This tool converts SQL strings into Mango objects, to allow users to interact with CouchDB/Cloudant database with SQL queries.

Installation

Use sqltomango in your project with:

npm install --save sqltomango

Import the library into your code:

var sqltomango = require('sqltomango');

Usage

The sqltomango library is a single function that accepts one argument - a string containing the SQL you wish to convert to a query object:

var q = sqltomango.parse("SELECT * FROM dogs WHERE owner = 'glynn'")

It returns an object which can be used to to query a CouchDB or Cloudant database:

{
 "selector": {
  "owner": {
   "$eq": "glynn"
  }
 }
}

This works for more complex queries too:

var q = sqltomango.parse("SELECT _id, age, breed FROM dogs WHERE owner = 'glynn' OR (name='towser' AND colour='white') ORDER BY age DESC LIMIT 500,1500")
// produces...
{
 "fields": [
  "_id",
  "age",
  "breed"
 ],
 "selector": {
  "$or": [
   {
    "owner": {
     "$eq": "glynn"
    }
   },
   {
    "$and": [
     {
      "name": {
       "$eq": "towser"
      }
     },
     {
      "colour": {
       "$eq": "white"
      }
     }
    ]
   }
  ]
 },
 "sort": [
  {
   "age": "desc"
  }
 ],
 "limit": 1500,
 "skip": 500
}

Errors

An exception is thrown if the SQL does not parse or contains SQL features not supported by Mango including:

  • GROUP BY
  • SUM/COUNT/AVG/DISTINCT
  • UNION
  • JOIN

Using in a browser

In the GitHub repo, you will find

  • src/sqltomango.js - the original source code
  • dist/sqltomango.js - an auto-generated form of the code that works in a web browser or in Node.js
<script src="browser.js"></script>
sqltomango.parse("SELECT * FROM mytable WHERE x > 2");
</script>
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free