TaffyDB Documentation

repository·master·Indexed 25 days ago

https://github.com/typicaljoe/taffydb

TaffyDB is an open-source JavaScript library that provides in-memory database capabilities for browser and Node.js applications using a SQL-like interface. It features record filtering with various match types, sorting via .order(), pagination with .limit() and .start(), and data aggregation using .sum(), .min(), and .max(). The library supports inner joins between tables, localStorage persistence via .store(), and a set of utility functions for type checking and object comparison.

Tokens
2.7K
Snippets
4
Records
20
Agent score
31%

What's inside TaffyDB

  1. Create a TaffyDB instance

    master

    You can initialize a database by passing a JSON array of objects to the TAFFY() function. Each object in the array represents a record in the database.

    var product_db = TAFFY([ 
      { "item"  : 1,
        "name"  : "Blue Ray Player",
        "price" : 99.99
      },
      { "item"  : 2,
        "name"  : "3D TV",
        "price" : 1799.99
      }
    ]);
  2. Install TaffyDB in Node.js

    master

    To use TaffyDB in a Node.js environment, install the taffy package via npm and then assign the taffy function to a variable (commonly TAFFY) by requiring the package.

    $ npm install --production taffy
    TAFFY = require( 'taffy' ).taffy;
  3. Initialize a TaffyDB instance

    master

    Use the TAFFY() constructor to create a new in-memory database. You can pass an array of objects or a JSON string to populate the database immediately upon creation.

    // Create an empty database
    var db = TAFFY();
    
    // Create a database with initial data
    var db = TAFFY([
      { name: 'Joe', age: 30 },
      { name: 'Jane', age: 25 }
    ]);
  4. Query records in TaffyDB

    master

    TaffyDB uses a SQL-inspired interface for selecting data. You can pass an object to the database instance to filter records based on key-value matches or specific operators like lt (less than) and like (pattern matching).

    // where item is equal to 1
    var item1 = products({item:1});
    
    // where price is less than 100
    var lowPricedItems = products({price:{lt:100}});
    
    // where name is like "Blue Ray"
    var blueRayPlayers = products({name:{like:"Blue Ray"}});
    
    // get first record
    products().first();
    
    // get last record
    products().last();
  5. Manipulate and transform records

    master

    TaffyDB provides several methods for updating, iterating, sorting, and projecting data:

    • .update(object): Updates records matching the current selection with the provided object.
    • .each(callback): Iterates over the selected records.
    • .sort(string): Sorts records using a string (e.g., "price desc").
    • .select(key): Returns an array containing only the values of the specified key.
    • .supplant(template): Injects record values into a string template using {key} syntax.
    // update the price of the Blue Ray Player to 89.99
    products({item:1}).update({price:89.99});
    
    // loop over the records and call a function
    products().each(function (r) {alert(r.name)});
    
    // sort the records by price descending
    products.sort("price desc");
    
    // select only the item names into an array
    products().select("name"); // returns ["3D TV","Blue Ray Player"]
    
    // Inject values from a record into a string template.
    var row = products({item:2})
      .supplant("<tr><td>{name}</td><td>{price}</td></tr>");
  6. Configure TaffyDB settings and events

    master

    You can configure database behavior and lifecycle events using the .settings() method on the database instance.

    Supported settings include:

    • template: An object used to merge with all new records inserted into the DB.
    • onInsert: Callback function triggered after a record is inserted (receives the new record).
    • onUpdate: Callback function triggered after a record is updated (receives the original record, the changes, and the new record).
    • onRemove: Callback function triggered after a record is removed (receives the removed record).
    • onDBChange: Callback function triggered when the database is modified.
    • storageName: A string used to identify the database in localStorage.
    • forcePropertyCase: Can be 'lower', 'upper', or null to force the casing of property names on insert.
    • cacheSize: Number of query results to cache.
    db.settings({
      onInsert: function(r) { console.log('Inserted:', r); },
      forcePropertyCase: 'lower',
      storageName: 'my_app_db'
    });
  7. Persist data to localStorage with .store()

    master

    The .store(name) method allows you to link the database to the browser's localStorage. When called with a name, TaffyDB will attempt to load existing data from localStorage using the key taffy_<name>. It also sets up automatic persistence whenever the database is modified.

    // Load from and save to localStorage under the key 'taffy_my_app'
    db.store('my_app');
  8. Limit and paginate results with `limit()` and `start()`

    master

    Use limit(n) to restrict the number of records returned. Use start(n) to skip the first n records (offsetting).

    Note: limit() and start() are typically used in conjunction with order() to implement pagination.

  9. Filter records with `filter()`

    master

    The filter() method allows you to narrow down results using various match types. You can pass objects or functions to define criteria.

    Match Types:

    • is or ===: Exact equality.
    • != or !==: Inequality.
    • lt, lte, gt, gte: Comparison operators (<, <=, >, >=).
    • left, leftnocase: Starts with (case-sensitive/insensitive).
    • right, rightnocase: Ends with (case-sensitive/insensitive).
    • like, likenocase: Contains substring (case-sensitive/insensitive).
    • regex: Regular expression match.
    • has, hasall: Checks for presence in collections.
    • contains: Checks if an array contains a value.
    • !is: Prefixing a match type with ! (e.g., !is) reverses the logic.

    Logical Operators:

    • Passing an array of filters acts as a logical OR (e.g., db.filter([{ age: { is: 30 } }, { age: { is: 25 } }])).
    • Passing multiple arguments or multiple keys in an object acts as a logical AND.
  10. Perform an `innerJoin` between two tables

    master

    The join() method allows you to merge two TaffyDB tables based on shared conditions.

    Condition Formats:

    1. Array: [ 'left_col', 'operator', 'right_col' ]. If the operator is omitted, === is used. Example: [ 'user_id', '==', 'id' ] or [ 'user_id', 'id' ].
    2. Function: A callback function(left_row, right_row) that returns true if the rows should be joined.

    When columns collide, the columns from the right table are prefixed with right_ to avoid overwriting the left table's data.

  11. Remove records from TaffyDB

    master

    Removing a record is a two-step process in TaffyDB. Calling .remove() marks a record for deletion (setting an internal ___s flag to false). To actually purge the records from memory and trigger the onRemove event, you must call .removeCommit().

    // Mark a record for removal
    db.find({ name: 'Bob' }).remove();
    
    // Permanently remove all marked records
    db.removeCommit();
  12. Update matched records with `update()`

    master
    The update() method modifies records that match the current query. You can pass an object of changes, a string key-value pair, or a function to compute new values based on the existing record.