Super flexible database/datastore for the client, server & mobile devices.
NanoSQL is the smallest and quickest way to get SQL power into your app. You get tons of RDBMS perks like joins, groupby, functions and orderby with strong runtime type casting, events, IndexedDB support, transactions and an ORM.
Persistence supports Local Storage
, Indexed DB
, and WebSQL
in the browser, and Level DB
in NodeJS with the same API. The storage engine is automatically selected based on the browser/environment, or can be manually selected.
Documentation
Highlighted Features
- Easy
LevelDB
, IndexedDB
, WebSQL
support. - Runs in Node, IE9+ & modern browsers.
- Supports all common RDBMS queries.
- Import and Export CSV/JSON.
- Simple & elegant undo/redo.
- Full Typescript support.
- Runtime type casting.
- Complete ORM support.
- Fast secondary indexes.
- Full events system.
NEW: Observable Queries
Use observables to subscribe to table changes and automatically update your views.
nSQL().observable(() => {
return nSQL("users").query("select").emit();
})
.debounce(1000)
.distinct()
.filter(rows => rows.length)
.map(rows => rows)
.first()
.skip(10)
.take(10)
.subscribe((rows) => {
})
NEW: Fuzzy Search
nSQL("posts")
.model([
{key: "id", type: "uuid", props: ["pk"]},
{key: "title", type: "string", props: ["search(english, 5)"]},
{key: "body", type: "string", props: ["search(english, 1)"]}
]).connect().then(() => {
return nSQL("posts").query("select").where(["search(title, body)", ">0.4", "some search term"]).exec();
})....
Browser Support
| | | | | |
---|
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 9+ ✔ |
Comparison With Other Projects
| nanoSQL | TaffyDB | LokiJS | NeDB | LoveField | PouchDB | alaSQL | RxDB | SQL.js |
---|
Events | ✓ | ✓ | ✓ | ✕ | ✓ | ✓ | ✕ | ✓ | ✕ |
Typescript | ✓ | ✕ | ✓ | ✓ | ✓ | ✓ | ✕ | ✓ | ✓ |
Undo/Redo | ✓ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✓ | ✕ |
ORM | ✓ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✓ | ✕ |
IndexedDB | ✓ | ✕ | ✓ | ✕ | ✓ | ✓ | ✓ | ✓ | ✕ |
Node | ✓ | ✓ | ✓ | ✓ | ✕ | ✓ | ✓ | ✓ | ✓ |
Observables | ✓ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✓ | ✕ |
Fuzzy Search | ✓ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ |
Query Functions | ✓ | ✕ | ✕ | ✕ | ✕ | ✕ | ✓ | ✕ | ✓ |
Size (kb) | 32 | 5 | 19 | 27 | 40 | 46 | 88 | 183 | 500 |
Database Support
NanoSQL can save data to several different places, depending on the browser or environment it's being ran in.
-
Included In The Box
- Memory
- Level DB
- Indexed DB
- WebSQL
- Local Storage
-
SQLite (NodeJS)
-
SQLite (Cordova)
-
MySQL
-
React Native
-
Redis
-
Google Cloud Datastore
-
Trivial DB (JSON File Store)
Installation
npm i nano-sql --save
Using in Typescript/Babel project:
import { nSQL } from "nano-sql";
Using in Node:
const nSQL = require("nano-sql").nSQL;
To use directly in the browser, drop the tag below into your <head>
.
<script src="https://cdn.jsdelivr.net/npm/nano-sql@1.8.3/dist/nano-sql.min.js"></script>
Simple Usage
1 minute minimal quick start:
nSQL([
{name: "bill", age: 20},
{name: "bob", age: 25},
{name: "jeb", age: 27}
]).query("select", ["name", "MAX(age) AS age"]).exec().then((rows) => {
console.log(rows);
})
nSQL('users')
.model([
{key:'id',type:'int',props:['pk','ai']},
{key:'name',type:'string'},
{key:'age', type:'int'}
])
.connect()
.then(function(result) {
return nSQL().query('upsert',{
name:"bill", age: 20
}).exec();
})
.then(function(result) {
return nSQL().query('select').exec();
})
.then(function(result) {
console.log(result)
})
Documentation
Detailed Usage
First you declare your models, connect the db, then you execute queries.
1. Declare Model & Setup
nSQL('users')
.model([
{key:'id',type:'uuid',props:['pk']},
{key:'name',type:'string', default:"None"},
{key:'age',type:'int', props: ["idx"]},
{key: "eyeColor", type: "string", props:["trie"]},
{key:'balance',type:'float', default: 0},
{key:'postIDs',type:'array'},
{key:'meta',type:'map'}
])
.config({
mode: "PERM",
history: true
})
.actions([
{
name:'add_new_user',
args:['user:map'],
call:function(args, db) {
return db.query('upsert',args.user).exec();
}
}
])
.views([
{
name: 'get_user_by_name',
args: ['name:string'],
call: function(args, db) {
return db.query('select').where(['name','=',args.name]).exec();
}
},
{
name: 'list_all_users',
args: ['page:int'],
call: function(args, db) {
return db.query('select',['id','name']).exec();
}
}
])
2. Connect the DB and execute queries
nSQL().connect().then(function(result) {
nSQL().doAction('add_new_user',{user:{
id:null,
name:'jim',
age:30,
balance:25.02,
postIDs:[0,20,5],
meta:{
favorteColor:'blue'
}
}}).then(function(result) {
console.log(result)
return nSQL().getView('list_all_users');
}).then(function(result) {
console.log(result)
});
});
Documentation
Some examples of queries you can do.
nSQL("users").on("change", function(dbEvent) { ... });
nSQL("*").on("change", function(dbEvent) { ... });
nSQL("users").query("select",["name"]).exec().then(function(rows) {...});
nSQL("users").query("select").trieSearch("name","fr").exec()...
nSQL("users").query("select").where(["name","=","John"]).exec().then(function(rows) {...});
nSQL("users").query("select").where(row => row.age > 20).exec().exec().then(function(rows) {...});
nSQL("users").query("select").where(["meta[eyeColor]", "=", "blue"]).exec().then(function(rows) {...});
nSQL("users").query("select").where(["posts.length", ">", 4]).exec().then(function(rows) {...});
nSQL("users").query("select").where([["name","=","John"],"AND",["age",">",25]]).exec().then(function(rows) {...});
nSQL("users").query("select").orderBy({name:"asc",age:"desc"}).exec().then(function(rows) {...});
nSQL("users").query("select").limit(10).offset(100).exec().then(function(rows) {...});
nSQL("users").query("select",["COUNT(*) AS totalUsers"]).exec().then(function(rows) {...});
nSQL("users")
.query("select",["id", "name AS username", "age"])
.where([["name","=","John"],"AND",["age",">",25]])
.orderBy({username:"desc",age:"asc"})
.exec().then(function(rows) {})
And here are some more advanced query examples.
nSQL("users")
.query("select",["orders.id", "users.name","orders.total"])
.where(["users.balance",">",500])
.join({
type:"left",
table: "orders",
where: ["orders.userID", "=", "users.id"]
}).exec().then(function(rows) {...})
nSQL("users")
.query("select",["favoriteColor", "eyeColor", "COUNT(*) AS users"])
.groupBy({favoriteColor:"asc", eyeColor:"desc"})
.having(["users" ,">", 2])
.orderBy({users:"desc"})
.exec().then(function(rows) {...})
nSQL("users")
.query("select",["orders.userID AS ID", "users.name AS Customer", "COUNT(*) AS Orders", "SUM(orders.total) AS Total"])
.join({
type:"left",
table: "orders",
where: ["orders.userID","=","users.id"]
})
.where([["users.balance", ">", 100], "OR",["users.age", ">", 45]])
.groupBy({"orders.userID":"asc"})
.having(["Total", ">", 100])
.orderBy({Total:"desc"})
.limit(20)
.exec().then(function(rows) {...})
History
The Undo/Redo system is super easy to use. First, enable it in the config object.
nSQL("table")
.model([...])
.config({
history: true
})
.connect().then....
Then use it! Every query that changes row data will be tracked as a history point.
nSQL().extend("hist", "<");
nSQL().extend("hist", ">");
nSQL().extend("hist", "clear")
nSQL().extend("hist", "?").then(function(status) {
console.log(status)
});
Writes are quite a bit slower when the history system is used, and your database takes up more space. You can disable the history system from being activated by not calling history
in the config object.
Help
Contributing
nanoSQL is an OPEN Open Source Project. This means that:
Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
Read more details here.
MIT License
Copyright (c) 2017 Scott Lott
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.