npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sfdatabase-js

v2.0.0-alpha-1

Published

SFDatabase-js is a database library that can help you build a SQL Query and execute it to the server from Nodejs or local browser with WebSQL. It will fallback to IndexedDB or LocalStorage for saving the database if running on browser.

Downloads

9

Readme

Software License

SFDatabase-js

SFDatabase-js is a database library that can help you build a SQL Query and execute it to the server from Nodejs or local browser with WebSQL. It will fallback to IndexedDB or LocalStorage for saving the database if running on browser. Check the example here.

Getting started for Node.js

First, you should install mysqljs and sfdatabase-js

$ npm i sfdatabase-js

# Optional if you want to use MySQL or SQLite for your database
$ npm i mysqljs/mysql
$ npm i sqlite3

Sample Usage

var MyDB = new SFDatabase('MyDB', {

    // For MySQL on Node.js
    mysql: true,
    host:'localhost',
    user:'root',
    password:'',

    // For SQLite on Node.js
    sqlite3: new (require('sqlite3').Database)('./test.db'),
    // Your database table's structure [optional]
    structure:{/*
        TableName:{
            id: ['integer', 'primary', 'autoincrement'],
            ColumnName: 'integer',
        },
    */},

    hideInitialization:true, // Keep silent after connected to DB

    // Debug SQL query if needed
    debug(query, data){
        console.log("Query: "+query, data);
    },

    onError: console.error,

    // You can also preprocess your data before or after the SQL Query is executed
    // This is optional
    preprocessTable: {
        test:{ // Table name
            data:{ // Column name
                set:JSON.stringify, // On insert or update
                get:JSON.parse // On select
            }
        }
    },

    onInit(){
        console.log("Database was connected!");
    }
});

Getting started for Browser

Add this into your HTML's header.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/SFDatabase.min.js"></script>

Before you use the database, you need to create the table first.

// Let's begin the initialization
var MyDB = new SFDatabase('MyDBName', {
    // Set this to true if you want to use WebSQL
    // Only some browser may support WebSQL
    // Set to false if you want to use IndexedDB
    websql: false,

    // When you have changed the DBStructure you need to update this version
    idbVersion:1,

    // Your database table's structure
    structure:{
        // TableName:{ TableStructure },
        UsersInfo:{
            $user_id: ['number', 'unique'], // indexed user_id
            $username: 'text', // indexed username
            name: 'text',

            // When using IndexedDB you can store almost any data types
            // To improve performance and memory you shouldn't store a big Object
            // instead you should spread it as table's structure
            data: 'Object', // you can store like {my: 'object'}

            // When using IndexedDB you can also store data without
            // declaring the structure, but declaring the table name is a must
        },
        Settings:{
            $name: ['text', 'unique'], // indexed name
            value:'text',
        },
    },

    // Debug WebSQL query if needed
    debug(query, data){
        console.log("Query: "+query, data);
    },

    onInit(){
        // MyDB_was_initialize(MyDB);

        // Maybe add some feature to make something easier
        Object.assign(MyDB, myFeature);
        MyDB.setSettings("It's", "ready", function(){
            MyDB.getSettings("It's", console.log)
        });
    }
});

var myFeature = {
    getSettings(name, callback){
        //       TableName  Get Column   Where    Success Callback
        this.get('Settings', 'value', {name:name}, function(data){
            callback(data);
        });
    },
    setSettings(name, value){
        let that = this;
        //       TableName      Where     Success Callback
        this.has('Settings', {name:name}, function(exist){
            if(exist === false)
                that.insert('Settings', {name:name, value:value});
                   //       TableName           Data
            else
                that.update('Settings', {value:value}, {name:name});
                   //       TableName       Data           Where
        });
    }
};

Available Function

// If you use IndexedDB you don't need .createTable
// onSuccess and onError callback are optional

// CREATE TABLE IF NOT EXISTS test (id NUMBER, name TEXT, data TEXT, words TEXT)
// createTable(tableName, structure, onSuccess, onError);
await MyDB.createTable('test', {
    id:['number', 'unique'],
    name:'text',
    data:'text',
    words:'text'
});

// INSERT INTO test (id, name, words) VALUES (?, ?, ?)
// insert(tableName, fields, onSuccess, onError);
await MyDB.insert("test", {
    id:1,
    name:"abc",
    words:'hey'
});

// UPDATE test
//      SET name = ?, data = ?
//      WHERE (id = ? AND (name = ? OR name = ?))
// update(tableName, fields, where, onSuccess, onError);
await MyDB.update("test", {
    // Fields
    name:'zxc',
    data:{
        any:[1,2,3]
    }
}, {
    // Where
    AND:{
        id:1,
        OR:{
            name:'abc',
            'name#1':'zxc'
        }
    }
});

// SELECT name, data FROM test
//      WHERE (id = ? OR (words LIKE ?))
//      LIMIT 1
// select(tableName, GetFieldsData, where, onSuccess, onError);
let result = await MyDB.select("test", ['name', 'data'], {
    OR:{
        id:321,
        'words[~]':'hey'
    },
    LIMIT:1
});

// SELECT name FROM test
//      WHERE (rowid = ? AND (name = ? OR name = ?) AND (id IN (?, ?, ?) OR data IS NOT NULL))
let results = await MyDB.select("test", 'name', {
    AND:{
        rowid:1,
        OR:{name:'abc', 'name#1':'zxc'},
        'OR#1':{id:[1,2,null], 'data[!]':null}
    }
});

// DELETE FROM test WHERE (name LIKE ?)
// delete(tableName, where, onSuccess, onError);
await MyDB.delete("test", {'name[~]':"%xc"}, console.warn);

// TRUNCATE TABLE test
await MyDB.delete("test", 0, console.warn);

// Drop table
await MyDB.drop("test", console.warn);

Contribution

If you want to help in SFDatabase-js library, please fork this project and edit on your repository, then make a pull request to here. This library can be improved by making some code more efficient.

License

MIT license.