• Stars
    star
    812
  • Rank 56,150 (Top 2 %)
  • Language
    JavaScript
  • Created about 13 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

A simple database layer for localStorage and sessionStorage for creating structured data in the form of databases and tables

localStorageDB 2.3.2

localStorageDB is a simple layer over localStorage (and sessionStorage) that provides a set of functions to store structured data like databases and tables. It provides basic insert/update/delete/query capabilities. localStorageDB has no dependencies, and is not based on WebSQL. Underneath it all, the structured data is stored as serialized JSON in localStorage or sessionStorage.

Installation

NPM

npm install localstoragedb

Yarn

yarn add localstoragedb

Bower

bower install localstoragedb

Run Test Cases

bower install # install mocha and chai for running test cases

open test/local_storage_db_test.html in Browser to check the result

Supported Browsers

Browsers need to support "Local Storage" in order to make localeStorageDB working.

  • IE 8<
  • Firefox 31<
  • Chrome 31<
  • Safari 7<
  • iOS Safari 7.1<
  • Android Browser 4.1<
  • Chrome for Android 42<

Usage / Examples

Creating a database, table, and populating the table

// Initialise. If the database doesn't exist, it is created
var lib = new localStorageDB("library", localStorage);

// Check if the database was just created. Useful for initial database setup
if( lib.isNew() ) {

    // create the "books" table
	lib.createTable("books", ["code", "title", "author", "year", "copies"]);

	// insert some data
	lib.insert("books", {code: "B001", title: "Phantoms in the brain", author: "Ramachandran", year: 1999, copies: 10});
	lib.insert("books", {code: "B002", title: "The tell-tale brain", author: "Ramachandran", year: 2011, copies: 10});
	lib.insert("books", {code: "B003", title: "Freakonomics", author: "Levitt and Dubner", year: 2005, copies: 10});
	lib.insert("books", {code: "B004", title: "Predictably irrational", author: "Ariely", year: 2008, copies: 10});
	lib.insert("books", {code: "B005", title: "Tesla: Man out of time", author: "Cheney", year: 2001, copies: 10});
	lib.insert("books", {code: "B006", title: "Salmon fishing in the Yemen", author: "Torday", year: 2007, copies: 10});
	lib.insert("books", {code: "B007", title: "The user illusion", author: "Norretranders", year: 1999, copies: 10});
	lib.insert("books", {code: "B008", title: "Hubble: Window of the universe", author: "Sparrow", year: 2010, copies: 10});

	// commit the database to localStorage
	// all create/drop/insert/update/delete operations should be committed
	lib.commit();
}

Creating and populating a table in one go

	// rows for pre-population
	var rows = [
		{code: "B001", title: "Phantoms in the brain", author: "Ramachandran", year: 1999, copies: 10},
		{code: "B002", title: "The tell-tale brain", author: "Ramachandran", year: 2011, copies: 10},
		{code: "B003", title: "Freakonomics", author: "Levitt and Dubner", year: 2005, copies: 10},
		{code: "B004", title: "Predictably irrational", author: "Ariely", year: 2008, copies: 10},
		{code: "B005", title: "Tesla: Man out of time", author: "Cheney", year: 2001, copies: 10},
		{code: "B006", title: "Salmon fishing in the Yemen", author: "Torday", year: 2007, copies: 10},
		{code: "B007", title: "The user illusion", author: "Norretranders", year: 1999, copies: 10},
		{code: "B008", title: "Hubble: Window of the universe", author: "Sparrow", year: 2010, copies: 10}
	];

	// create the table and insert records in one go
	lib.createTableWithData("books", rows);

	lib.commit();

Altering

// If database already exists, and want to alter existing tables
if(! (lib.columnExists("books", "publication")) ) {
	lib.alterTable("books", "publication", "McGraw-Hill Education");
	lib.commit(); // commit the deletions to localStorage
}

// Multiple columns can also added at once
if(! (lib.columnExists("books", "publication") && lib.columnExists("books", "ISBN")) ) {
	lib.alterTable("books", ["publication", "ISBN"], {publication: "McGraw-Hill Education", ISBN: "85-359-0277-5"});
	lib.commit(); // commit the deletions to localStorage
}

Querying

query() is deprecated. Use queryAll() instead.

// simple select queries
lib.queryAll("books", {
	query: {year: 2011}
});
lib.queryAll("books", {
	query: {year: 1999, author: "Norretranders"}
});

// select all books
lib.queryAll("books");

// select all books published after 2003
lib.queryAll("books", {
	query: function(row) {    // the callback function is applied to every row in the table
		if(row.year > 2003) {		// if it returns true, the row is selected
			return true;
		} else {
			return false;
		}
	}
});

// select all books by Torday and Sparrow
lib.queryAll("books", {
    query: function(row) {
            if(row.author == "Torday" || row.author == "Sparrow") {
		        return true;
	        } else {
		        return false;
	    }
    },
    limit: 5
});

Sorting

// select 5 rows sorted in ascending order by author
lib.queryAll("books", { limit: 5,
                        sort: [["author", "ASC"]]
                      });

// select all rows first sorted in ascending order by author, and then, in descending, by year
lib.queryAll("books", { sort: [["author", "ASC"], ["year", "DESC"]] });

lib.queryAll("books", { query: {"year": 2011},
                        limit: 5,
                        sort: [["author", "ASC"]]
                      });

// or using query()'s positional arguments, which is a little messy (DEPRECATED)
lib.query("books", null, null, null, [["author", "ASC"]]);

Distinct records

lib.queryAll("books", { distinct: ["year", "author"]
                      });

Example results from a query

// query results are returned as arrays of object literals
// an ID field with the internal auto-incremented id of the row is also included
// thus, ID is a reserved field name

lib.queryAll("books", {query: {author: "ramachandran"}});

/* results
[
 {
   ID: 1,
   code: "B001",
   title: "Phantoms in the brain",
   author: "Ramachandran",
   year: 1999,
   copies: 10
 },
 {
   ID: 2,
   code: "B002",
   title: "The tell-tale brain",
   author: "Ramachandran",
   year: 2011,
   copies: 10
 }
]
*/

Updating

// change the title of books published in 1999 to "Unknown"
lib.update("books", {year: 1999}, function(row) {
	row.title = "Unknown";

	// the update callback function returns to the modified record
	return row;
});

// add +5 copies to all books published after 2003
lib.update("books",
	function(row) {	// select condition callback
		if(row.year > 2003) {
			return true;
		} else {
			return false;
		}
	},
	function(row) { // update function
		row.copies+=5;
		return row;
	}
);

Insert or Update conditionally

// if there's a book with code B003, update it, or insert it as a new row
lib.insertOrUpdate("books", {code: 'B003'}, {	code: "B003",
						title: "Freakonomics",
						author: "Levitt and Dubner",
						year: 2005,
						copies: 15});

lib.commit();

Deleting

// delete all books published in 1999
lib.deleteRows("books", {year: 1999});

// delete all books published before 2005
lib.deleteRows("books", function(row) {
	if(row.year < 2005) {
		return true;
	} else {
		return false;
	}
});

lib.commit(); // commit the deletions to localStorage

Methods

Method Arguments Description
localStorageDB() database_name, storage_engine Constructor
- storage_engine can either be localStorage (default) or sessionStorage
isNew() Returns true if a database was created at the time of initialisation with the constructor
drop() Deletes a database, and purges it from localStorage
tableCount() Returns the number of tables in a database
commit() Commits the database to localStorage. Returns true if successful, and false otherwise (highly unlikely)
serialize() Returns the entire database as serialized JSON
tableExists() table_name Checks whether a table exists in the database
tableFields() table_name Returns the list of fields of a table
createTable() table_name, fields Creates a table
- fields is an array of string fieldnames. 'ID' is a reserved fieldname.
createTableWithData() table_name, rows Creates a table and populates it
- rows is an array of object literals where each object represents a record
[{field1: val, field2: val}, {field1: val, field2: val}]
alterTable() table_name, new_fields, default_values Alter a table
- new_fields can be a array of columns OR a string of single column.
- default_values (optional) can be a object of column's default values OR a default value string for single column for existing rows.
dropTable() table_name Deletes a table from the database
truncate() table_name Empties all records in a table and resets the internal auto increment ID to 0
columnExists() table_name, field_name Checks whether a column exists in database table.
rowCount() table_name Returns the number of rows in a table
insert() table_name, data Inserts a row into a table and returns its numerical ID
- data is an object literal with field-values
Every row is assigned an auto-incremented numerical ID automatically
query() DEPRECATED table_name, query, limit, start, sort
queryAll() table_name, params{} Returns an array of rows (object literals) from a table matching the query.
- query is either an object literal or null. If query is not supplied, all rows are returned
- limit is the maximum number of rows to be returned
- start is the number of rows to be skipped from the beginning (offset)
- sort is an array of sort conditions, each one of which is an array in itself with two values
- distinct is an array of fields whose values have to be unique in the returned rows
Every returned row will have it's internal auto-incremented id assigned to the variable ID
update() table_name, query, update_function Updates existing records in a table matching query, and returns the number of rows affected
- query is an object literal or a function. If query is not supplied, all rows are updated
- update_function is a function that returns an object literal with the updated values
insertOrUpdate() table_name, query, data Inserts a row into a table if the given query matches no results, or updates the rows matching the query.
- query is either an object literal, function, or null.
- data is an object literal with field-values

Returns the numerical ID if a new row was inserted, or an array of IDs if rows were updated
deleteRows() table_name, query Deletes rows from a table matching query, and returns the number of rows deleted
- query is either an object literal or a function. If query is not supplied, all rows are deleted

Storing complex objects

While the library is meant for storing fundamental types (strings, numbers, bools), it is possible to store object literals and arrays as column values, with certain caveats. Some comparison queries, distinct etc. may not work. In addition, if you retrieve a stored array in a query result and modify its values in place, these changes will persist throughout further queries until the page is refreshed. This is because localStorageDB loads and unserializes data and keeps it in memory in a global pool until the page is refreshed, and arrays and objects returned in results are passed by reference.

If you really need to store arrays and objects, you should implement a deep-copy function through which you pass the results before manipulation.

More Repositories

1

listmonk

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
Go
14,893
star
2

dns.toys

A DNS server that offers useful utilities and services over the DNS protocol. Weather, world time, unit conversion etc.
Go
2,446
star
3

koanf

Simple, extremely lightweight, extensible, configuration management library for Go. Support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.
Go
2,445
star
4

niltalk

Instant, disposable, single-binary web based live chat server. Go + VueJS.
Go
939
star
5

dragmove.js

A super tiny Javascript library to make DOM elements draggable and movable. ~500 bytes (minified+gzipped) and no dependencies.
JavaScript
819
star
6

tg-archive

A tool for exporting Telegram group chats into static websites like mailing list archives.
Python
772
star
7

otpgateway

Standalone server for user address and OTP verification flows with pluggable providers (e-mail, SMS, bank penny drops etc.)
Go
429
star
8

hugo-ink

Crisp, minimal personal website and blog theme for Hugo
HTML
395
star
9

dictpress

A stand-alone web server application for building and publishing full fledged dictionary websites and APIs for any language.
Go
360
star
10

autocomp.js

A super tiny Javascript autocomplete / autosuggestions library. Zero dependencies, ~800 bytes min+gzip.
JavaScript
299
star
11

xmlutils.py

Python scripts for processing XML documents and converting to SQL, CSV, and JSON [UNMAINTAINED]
Python
241
star
12

dont.build

A simple, opinionated decision system to help decide whether to build a software feature or not.
HTML
206
star
13

stuffbin

Compress and embed static files and assets into Go binaries and access them with a virtual file system in production
Go
166
star
14

go-get-youtube

A tiny Go library + client for downloading Youtube videos. The library is capable of fetching Youtube video metadata, in addition to downloading videos.
Go
158
star
15

smtppool

High throughput Go SMTP pool library with graceful handling of idle timeouts, errors, and retries.
Go
124
star
16

ml2en

An algorithm that transliterates Malayalam script to Roman / Latin characters (commonly 'Manglish') with reasonable phonetic fairness. Available in Python, PHP, Javascript
Python
87
star
17

git-bars

A utility for visualising git commit activity as bars on the terminal
Python
85
star
18

indexed-cache

A tiny Javsacript library for sideloading static assets on pages and caching them in the browser's IndexedDB for longer-term storage.
JavaScript
78
star
19

simplemysql

An ultra simple wrapper for Python MySQLdb with very basic functionality
Python
77
star
20

floatype.js

A tiny, zero-dependency, floating autocomplete / autosuggestion widget for textareas.
JavaScript
76
star
21

pfxsigner

A CLI utility and web server for digitally signing PDFs with docsign loaded from PFX (PKCS#12) files
Go
73
star
22

go-pop3

A simple Go POP3 client library for connecting and reading mails from POP3 servers.
Go
72
star
23

indic.page

A directory of Indic (Indian) language computing resources.
HTML
55
star
24

goyesql

Parse SQL files with multiple named queries and automatically prepare and scan them into structs.
Go
48
star
25

dirmaker

dirmaker is a simple, opinionated static site generator for quickly publishing directory websites.
Python
48
star
26

knphone

KNphone is a phonetic algorithm for indexing Kannada words by their pronunciation, like Metaphone for English.
Go
45
star
27

tinytabs

A tiny (1.3 KB minified) Javascript tabbing library for rendering tabbed UIs. Zero dependencies.
HTML
44
star
28

wordpluck

A browser based typing game in Javascript. Revived from a 2012 project.
JavaScript
43
star
29

datuk

"Datuk", the Unicode Malayalam - Malayalam dictionary dataset
40
star
30

csv2json

csv2json is a fast utility that converts CSV files into JSON line files. An experiment in Zig lang.
Zig
37
star
31

profiler

A simple wrapper over Go runtime/pprof for running multiple concurrent profiles and dumping results to files.
Go
30
star
32

mlphone

MLphone (Python, PHP) is a phonetic algorithm for indexing Malayalam words by their pronounciation, like Metaphone for English. The algorithm generates three Romanized phonetic keys (hashes) of varying phonetic proximities for a given Malayalam word.
PHP
29
star
33

paginator

Tiny Go package for pagination queries and generating page numbers
Go
20
star
34

gtbump

git tag bump: A simple utility to bump and manage git semantic version tags and generate Markdown changelogs.
Python
20
star
35

listmonk-heroku-deploy

Official listmonk install button for Heroku.
Shell
16
star
36

bigreddy

BigReddy is a small utility that generates pseudo-philosophical and pseudo-poetic ramblings.
Python
15
star
37

tinyprogressbar

tinyProgressbar is an extremely tiny (640 bytes minified+gzipped) Javascript progressbar library
JavaScript
15
star
38

listmonk-site

Static website + docs for listmonk
HTML
15
star
39

otpgateway-solsms

SMS provider for otpgateway (SolutionsInfini, India)
Go
15
star
40

go-i18n

Tiny i18n library for loading and using simple JSON language translation files in Go programs.
Go
14
star
41

tinyauth

Tiny, opinionated authentication library for Go. Work in progress and not usable right now.
Go
14
star
42

simpleplanner

Simple planner
JavaScript
13
star
43

querytostruct

An extremely tiny utility for unmarshalling and scanning querystrings into structs
Go
13
star
44

jsonconfig

Super tiny JSON configuration file parser with comments support for Go programs
Go
12
star
45

tinytooltip

An extremely tiny tooltip plugin for jQuery
JavaScript
10
star
46

zig-releaser

A simple hack to use GoReleaser to build, release, and publish Zig projects.
Shell
10
star
47

scylladb-metrics

A script for generating docs for Promethus metrics exported by ScyllaDB
HTML
9
star
48

stringvalidator.py

Aa simple string validator class in Python for basic data validation such as checking if a string is alpha, alphanumeric, e-mail etc.
Python
8
star
49

jqdialog

A jQuery plugin with smooth and peristent dialog boxes meant as a replacement for alert(), confirm(), and prompt()
JavaScript
8
star
50

boastmachine

boastMachine (legacy), a full fledged blogging package. One of the earliest on the web, first released in 2002.
PHP
7
star
51

yesqlr

Parse SQL files with multiple named queries into a map for easy organisation and management of SQL queries. Port of goyesql.
Rust
7
star
52

ctunes

A prototype music list manager. C programming exercise I did a very long time ago.
C
6
star
53

CANT24

A neural network framework (primarily, a fLIF neuron simulator)
5
star
54

chunkedreader

chunkedreader is a light weight wrapper for Go's `bufio` that enables reading of byte streams in fixed size chunks
Go
4
star
55

rofi-vscode-projects

A vscode project launcher menu for the rofi app launcher
3
star
56

omeka-total-pages

An Omeka-S plugin for computing the total number of pages across items in an item set or collection.
PHP
2
star
57

csssprite

A simple utility for merging images into a sprite with accompanying CSS
Python
1
star