⚡ A powerful, human-friendly database library for JavaScript using SQLite.

Overview

great.db

A powerful, human-friendly database library for JavaScript using SQLite.

  • Elegant way to set and retrieve data
  • Queries are executed through robust functions
  • Completely asynchronous

Before getting started

This project is at an infancy and currently works only with bun:sqlite (bun.js runtime), but will support better-sqlite3 (node.js runtime) too in future.

Feature checklist

  • Simplify way to insert/update rows
  • Powerful filter function to filter data based on condition
  • Ability to delete tables
  • Ability to execute custom SQL code directly
  • Support better-sqlite3
  • Add more schema presets

Table of Contents

Install

bun install great.db

Creating or Opening a database

new GreatDB.Database(options)

  • options.type

    • GreatDB.Type.Disk

      To create/open the database stored on the disk at a particular location.

    • GreatDB.Type.Memory

      Used to create an in-memory database.

      Note: If this is chosen, then rest of the following properties are not required.

  • options.name

    The name of the database file.

  • options.location (optional)

    The path to the folder where the database file will be/is stored. If not provided, then the base folder of the project will be chosen by default.

  • options.mode

    • GreatDB.Mode.ReadWrite

      Opens the database in read/write mode i.e. read and insert/change values.

    • GreatDB.Mode.ReadOnly

      Opens the database in read only mode i.e. cannot change any values.

Example:

import { GreatDB } from "great.db";
const db = new GreatDB.Database({
    type: GreatDB.Type.Disk,
    name: "test",
    mode: GreatDB.Mode.ReadWrite
});

Defining schema for a table

Schema is a way to define the structure for a table i.e. the columns. They contain column names along with their data types.

Schema.Create({...})

Currently supported data types are String, Number, BigInt and Boolean.

Example:

import { Schema } from "great.db";
const customerSchema = Schema.Create({
    id: Number,
    name: String,
    phone: Number,
    address: String,
    member: Boolean
});
type customerSchemaType = {
    id: number,
    name: string,
    phone: number,
    address: string,
    member: boolean
};

The above schema represents the following columns of a table:

id Number name String phone Number address String member Boolean

Schema.Presets.<Preset Name>

Some commonly used schemas are available as presets.

  • KeyValue

    key String value String
  • More coming soon...

Schema.Types.<Preset Name>

Contains equivalent typescript type information of the respective preset.

Creating or Opening a table

Tables are where the data will be stored. A single database can contain multiple tables.

table<type>(name, schema)

  • type

    The typescript equivalent of the schema created earlier or Schema.Types if using a preset.

  • name

    Name of the table to be created.

  • schema

​ The schema created earlier using Schema.Create or a predefined preset using Schema.Presets.

Example:

const table = db.table<customerSchemaType>("customers", customerSchema);

Getting values from the table

table.get(keyName, keyValue, fetchAll?)

  • keyName

    The name of the column of which we want to sort out the value.

  • keyValue

    The value to be searched in that column.

  • fetchAll (optional)

    • true: Returns an array of all the records whose key matches the given value.
    • false: (Default) Returns only the first record whose key matched with the value.

Example:

const x = await table.get("id", 1);
console.log(x);

Setting values to the table

table.set({...})

From the supplied parameter of objects, the first property is always treated as the key. If the key doesn't exist in the table, then all the supplied values are inserted into the table, but if the key already exists, then the old values belonging to the key will be updated with the new ones supplied.

Example:

// Part-1
await table.set({
    id: 1, /*key*/
    name: "John Doe",
    phone: 1234567890,
    address: "Obere Str. 57",
    member: false
});

// Part-2
await table.set({
    id: 1, /*key*/
    address: "8 Johnstown Road" // Updating only the address value
});

The above example executes to the following:

Table contents after Part-1:

id Number name String phone Number address String member Boolean
1 John Doe 1234567890 Obere Str. 57 false

Table contents after Part-2:

id Number name String phone Number address String member Boolean
1 John Doe 1234567890 8 Johnstown Road false

Checking if a value exists in the table

table.has(keyName, keyValue)

Checks if the given key is present in the table and returns true or false accordingly.

  • keyName: The column name where the value is to be searched.
  • keyValue: The value to be searched in that column.

Example:

const x = await table.has("name", "John Doe");
console.log(x);	// true

Deleting row(s) based on a value

table.delete(keyName, keyValue)

Deletes entire row(s) of where the value is present in that column.

  • keyName: The column name where the value is to be searched.
  • keyValue: The value to be searched in that column.

Example:

await table.delete("name", "John Doe");
const x = await table.has("name", "John Doe");
console.log(x);	// false

Converting an entire table to an array

table.toArray()

Returns all the rows of the table in the form of an array.

CAUTION: Avoid using this with tables having large amounts of data.

Closing the database

After all the tasks are completed, the database should be closed. After closing, executing any operation on the database will result in error.

db.close();

Examples

Browse all the examples here.

You might also like...

Send encrypted and decrypted messages with verifiable keys and human readable names.

Send encrypted and decrypted messages with verifiable keys and human readable names.

zooko-msg Encrypt and decrypt messages using AES with a preshared ECDH key generated using keys associated with Handshake names. I noticed that there

Jul 27, 2022

Convert JSON to human readable HTML

json.human.js: Json Formatting for Human Beings A small library to convert a JSON object into a human readable HTML representation that is easy to sty

Dec 3, 2022

⏱ Simple Alpine.js plugin to display the human-readable distance between a date and now.

⏱ Alpine TimeAgo ⏱ An Alpine.js plugin to return the distance between a given date and now in words (like "3 months ago", "about 2 hours ago" or "in a

Dec 22, 2022

💡 Providing equitable access to human useable Web3 data.

💡 Providing equitable access to human useable Web3 data.

💡 Providing equitable access to human useable Web3 data. Unidata The beauty of Web3 is that everyone owns their data, but accessing and displaying ow

Jan 2, 2023

A personal school project to model the behaviour of the human immune system as a network graph with interactive visualisation.

A personal school project to model the behaviour of the human immune system as a network graph with interactive visualisation.

An educational tool designed to help users understand the immune system. Made using Processing 5 for Java Script

Jun 18, 2022

Enhanced interval features for Node.js, such as promisified interval and human readable time parsing.

Interval-next Interval-next is a package that extends Javascript's built-in setInterval() capabilities. You have a plain and promisified interval meth

Jul 28, 2022

Svelte component to display time distances in a human readable format.

Time Distance Display time distances in a human readable format. Based on date-fns Updates every 60 seconds View demo Usage Install package: pnpm i -D

Nov 2, 2022

Visualize, modify, and build your database with dbSpy! An open-source data modeling tool to facilitate relational database development.

Visualize, modify, and build your database with dbSpy! An open-source data modeling tool to facilitate relational database development.

Visualize, modify, and build your database with dbSpy! dbSpy is an open-source data modeling tool to facilitate relational database development. Key F

Dec 22, 2022

PouchDB for Deno, leveraging polyfill for IndexedDB based on SQLite.

PouchDB for Deno PouchDB for Deno, leveraging polyfill for IndexedDB based on SQLite. Usage import PouchDB from 'https://deno.land/x/[email protected]

Aug 2, 2022
Comments
  • How would we retrive multiple entries?

    How would we retrive multiple entries?

    How would we retrieve multiple entries from db? Modified example down bellow.

    import { DataType, GreatDB, Schema } from "great.db";
    
    // Creating the database
    const db = new GreatDB.Database({
        type: GreatDB.Type.Disk,
        name: "test"
    });
    
    // Creating the schema and the table (Typescript types are automagically inferred)
    const customerSchema = Schema.Create({
        id: DataType.AutoIncrement,
        name: DataType.String,
        phone: DataType.Number,
        address: DataType.String,
        member: DataType.Boolean
    });
    const table = db.table("customers", customerSchema);
    
    // Populating the table
    await table.set([
        {
            name: "John Doe",
            phone: 1234567890,
            address: "Obere Str. 57",
            member: false
        },
        {
            name: "Adam Evans",
            phone: 6789067890,
            address: "120 Hanover Sq.",
            member: true
        },
        {
            name: "Frank Smith",
            phone: 1234512345,
            address: "City Center Plaza 516 Main St.",
            member: true
        }
    ]);
    
    // Retrieving multiple values
    const x = await table.get("member", true);
    console.log(x?.name);   // Adam Evans, <-- but where is Frank Smith?
    
    // Closing the database after all tasks are done
    db.close();
    
    opened by ohbob 4
Releases(2.3.0)
  • 2.3.0(Oct 31, 2022)

    1. New serialize, backup and clone functions for GreatDB.Database. Check out the docs to learn more about it.
    2. Added new Type.Serialized to support opening of serialized database.
    3. Improved and simplified internal runtime detection.
    4. Updated docs for new api.
    5. Added tests for few functions. Can be run using bun run test.
    6. Bumped bun-types to v0.2.2.
    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Oct 11, 2022)

    1. Added executeQuery function to run SQL code directly. Learn more.
    2. Added new pattern field to filter function to support SQL LIKE.
    3. Database#close function is now asynchronous.
    4. Added a new live shell to execute SQL code in a shell based environment on an in-memory database (run bun run shell to try it).
    5. Internal refactor of type inference.
    6. Updated docs for the above changes.
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Sep 22, 2022)

  • 2.0.0(Sep 18, 2022)

    v2 brings some big changes to great.db

    • great.db now works both with node.js and bun using better-sqlite3 and bun:sqlite respectively
    • Schemas now can only be created through DataType imported from great.db
    • 3 new datatypes are added - AutoIncrement, Buffer, Uint8Array
    • Typescript types are now automagically inferred from the schema created using DataType
    • Some internal code refactors to maintain cross-compatibility between both libraries
    • table#set() now also supports array of inputs
    • Improved examples to support the new API
    • Improved README.md, DOCUMENTATION.md
    • Removed db readonly feature temporarily
    • Bump bun-types to 0.1.11
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Sep 13, 2022)

Owner
null
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
💡 Providing easy access to human-friendly Web3 data.

?? Providing easy access to human friendly Web3 data. Unidata Docs The beauty of Web3 is that everyone owns their data, but accessing and displaying o

Natural Selection Labs 263 Dec 29, 2022
An open source, friendly human-like chatbot to be with you, forever

Chatbot A Friendly human-like chatbot to be with you, forever Made by Rahuletto#0243 This template powers our system at Simply API Instructions This b

Rahul Marban 6 Sep 18, 2022
Workshop: Crafting Human Friendly CLIs with Node.js Core

$ Crafting Human Friendly CLIs with Node.js Core █ A workshop by Simon Plenderleith & Kevin Cunningham. Getting ready for the workshop 1. Required sof

Simon Plenderleith 13 Dec 26, 2022
⚡ It is a simplified database module with multiple functions that you can use simultaneously with sqlite, yaml, firebase and json.

Prisma Database Developed with ?? by Roxza ⚡ An easy, open source database ?? Installation npm i prisma.db --save yarn add prisma.db ?? Importing impo

Roxza 21 Jan 3, 2023
Small js library to animate some writing effect through a list of strings. It also supports settings for typo errors, to make it more human likely.

Write and Delete Small js library to animate some writing effect through a list of strings. It also supports settings for typo errors, to make it more

fabs 2 Nov 15, 2022
parses human-readable strings for JavaScript's Temporal API

?? temporal-parse What is the temporal-parse? Temporal is the next generation of JavaScript's standard Date API. It's currently proposed to TC39 (see:

Eser Ozvataf 22 Jan 2, 2023
A web scraping / data mining script for extracting beginner-friendly github repos from Y Combinator's company database

A web scraping / data mining script for extracting beginner-friendly github repos from Y Combinator's company database

Oscar Mier 27 Nov 24, 2022
Interplanetary Database: A Database built on top of IPFS and made immutable using Ethereum blockchain.

IPDB IPDB (Interplanetary Database) is a key/value store database built on top of IPFS (Interplanetary File System). Project is intended to be an MVP

turinglabs 8 Oct 6, 2022