Dexie.js

A Minimalistic Wrapper for IndexedDB

APACHE-2.0 License

Downloads
2.2M
Stars
10.7K
Committers
98

Bot releases are hidden (Show)

Dexie.js - Dexie v4.0.4 Latest Release

Published by dfahlander 6 months ago

Fixes #1955 for real this time (the fix in 4.0.2 wasn't correct enough for npm)

Dexie.js - Dexie v4.0.2

Published by dfahlander 6 months ago

Patch Release

[email protected]

  • Fixes issue #1946 - liveQueries of compound index involving auto-incremented primary key as part failed to update.
  • Fixes issue #1955 - tsconfig.json in root referering to nonexisting tsconfig in non-bundled src directory. Fixed for real in 4.0.4.

[email protected]

  • Allow logging in with demo account in default login GUI and customized login GUI. User can write an imported @demo.local address in the email dialog and can skip the OTP step.
Dexie.js - Dexie v4.0.1

Published by dfahlander 7 months ago

Dexie 4 Stable

After 3 years is alpha and beta, and a week in RC, Dexie@4 is finally out!

Changed Version Handling (PR #1880)

  • Dexie@4 accepts upgrading schema WITHOUT incrementing the version number.
  • Dexie@4 is now able to open a previous version of the database without throwing VersionError.

It's still recommended to increment version number when schema has been updated before publishing new versions of an application since it can make opening the db fractions of ms faster. But it's not required.

(If the native version has diverged from the declared version - which happen when extending schema without incrementing version, dexie need to increment the native version to extend schema - and after a page refresh dexie will detect diverged version by catching VersionError and will redo open with the exact installed version under the hood. When measuring the extra time to open an older version in indexedDB and catch VersionError 10,000 times, it only took 1000 ms - 0.1 ms per try (on a macbook pro), so it should be negligible (https://jsfiddle.net/dfahlander/9tg13fwk/19/))

Cache

Non-transactional live queries utilize memory cache to assist in query resolution. It is possible to opt-out from using the cache using the option {cache: 'disabled'}. The cache can greatly improve simple pure range-based live queries and reduce the queries towards IndexedDB by reusing common queries from different components. The cache will be continously developed and optimized further to improve the new paging support in Dexie 5.0.

Workarounds for flaky browsers

Dexie 4 catches various issues in the IndexedDB support for Chrome and Safari. Without dexie@4 tranasactions and write operations can suddenly fail in modern versions of Chrome and Safari but dexie makes sure to protect the end user from experience any issues. It does this by reopening the database or redoing the transaction when these things happen - all without the developer having to worry about it. See issues #543 and #613. (A close upcoming release on the 4.0-track will also address #1660 and #1829).

Supports Dexie Cloud

With Dexie 4.0, you can optionally use dexie-cloud-addon and connect your local database with a cloud based database. Dexie Cloud is a complete solution for authorization and synchronization of personal data with support for sharing data between users.

Improved Typing

Dexie 4 has some improved typing. Specifically, Collection.modify() and Table.update() use template literals to suggest code completion and type checking of keypaths to update.

Distinguish insert- from output types

The type passed to db.table.add() can be different from the type returned from db.table.get() and tb.table.toArray(). This mirrors reality better since some properties may be optional when adding (such as an auto-incremented primary key or dexie-cloud properties realmId and owner).

The generic type Table<T, TKey> is extended with a 3rd optional parameter TInsertType making it possible to declare a table as such:

class MyDB extends Dexie {
  friends!: Table<
    { id: number; name: string; age: number }, // T (id is always there)
    number, // TKey (type of primary key)
    { id?: number; name: string; age: number } // TInsertType (id is optional)
  >;
}

A new helper generic EntityTable<T> also exists as a "don't repeat yourself" sugar on top of this, and will also omit any method on the type. In case the type is a mapped class with helper methods, you are still able to pass simple POJO objects
to add() and put() with only data properties.

interface Friend {
  id: number;
  name: string;
  age: number;
}

class MyDB extends Dexie {
  friends!: EntityTable<Friend, 'id'>; // Automatically makes `id` optional when adding and picks its TKey type.
}

If using Dexie Cloud, there's a DexieCloudTable<T> generic that will declare the implicit Dexie Cloud properties on the entity correctly for insert- and output types:

interface Friend {
  id: string;
  name: string;
  age: number;
  realmId: string;
  owner: string;
}

class MyDexieCloudDB extends Dexie {
  friends!: DexieCloudTable<Friend, 'id'>; // Makes id, realmId and owner optional on insert operations.
}

A solution to dependency issues with mapped classes

In dexie 3, a mapped class that needs to access the database from its methods, will needs to access the a db instance. But it is a bit awkward to tie a method body to the same instance exported from the db module. For example, having two instances of db with different constructor parameters would not work as both would use one of the instances from their method bodies.

In Dexie 4.0, this is solved using a lightweight dependency injection. There is a generic class Entity that your classes may extend from in order to get your database instance injected as a protected property db on every entity instance. Your class methods can then perform queries onto the db without being dependant on the db module of your app. This use case will require a subclassed Dexie declaration though. There will still be cyclic import dependencies but only on the type level.

export class Friend extends Entity<AppDB> {
  id!: number;
  name!: string;
  age!: number;

  async birthday() {
    return await this.db.friends.update(this.id, (friend) => ++friend.age);
  }
}

Breaking Changes

No IE11 support

No support for Internet Explorer 11, legacy Edge (non-chromium) nor legacy Safari below version 14.

Dexie.js - Dexie v4.0.1-rc.1

Published by dfahlander 7 months ago

Release candidate of [email protected]

This is the first release candidate of dexie@4. Please upgrade your dexie@3 to this to help us verify that it is backward compatible and works well for you application. Unless any critical issue shows up within a 5 days, [email protected] will be released as the latest stable version of dexie. At that point, release notes will contain all the news in dexie@4 compared to dexie@3. These changes are briefly covered in https://dexie.org/roadmap/dexie4.0

Please file issue as soon as possible if you find any breaking change or critical issue with this release that would prevent it from being released as the latest stable version of dexie.

Dexie.js - Dexie v3.2.7

Published by dfahlander 7 months ago

Bugfix: Removed invalid dependency. Dexie has no dependencies #1924

NOTE: Prepare for [email protected] release candidate soon! It will have better stability by working around various browser issues and nicer version handling.

Dexie.js - Dexie v4.0.1-beta.14

Published by dfahlander 7 months ago

Support for sync-consistently moving tree structures (via PR #1910)

  • New version of dexie-cloud-addon: 4.0.1-beta.58
  • New version of dexie: 4.0.1-beta.14
  • New export in 'dexie': replacePrefix
  • New support for replacePrefix in Dexie Cloud

Background: The parentPath pattern:

One pattern for managing tree structures in a database is to have an indexed property representing the path to the parent node, such as parentPath. This makes it efficient to delete or list all descendants in one query without any need of recursion:

// Add new node
function addNode(childProps, parentId = null) {
  return db.transaction('rw', db.treeNodes, async ()=> {
    const parent = parentId && await db.treeNodes.get(parentId);
    await db.treeNodes.add({
      ...childProps,
      parentPath: parent
        ? `${parent.parentPath}${parent.id}/`
        : '' // If no parent, parentPath will be empty string (added at the root)
    });
  }
}

// List direct children
function listChildren(node) {
  return db.treeNodes.where({parentPath: `${node.parentPath}${node.id}/`}).toArray();
}

// List all descendants without recursion:
function listAllDescendants(node) {
  return db.treeNodes.where('parentPath').startsWith(`${node.parentPath}${node.id}/`).toArray();
}

// Load parent
function loadParent(node) {
  return db.treeNodes.get(node.parentPath.split('/').at(-2));
}

// Load all ancestors
function async loadAllAncestors(node) {
  return (node.parentPath
    ? await db.treeNodes.bulkGet(node.parentPath.substring(0, node.parentPath.length - 1).split('/'))
    : []
  );
}

// Delete the node and all its descendants:
function deleteNode(node) {
  return db.transaction('rw', db.treeNodes, () => {
    db.treeNodes.where('parentPath')
      .startsWith(`${node.parentPath}${node.id}/`)
      .delete();
    db.treeNodes.where({
      parentPath: node.parentPath, // for consistence
      id: node.id
    }).delete();
  });
}

// NOTE:
// Where schema is defined, use a compound index on '[parentPath+id]':
// db.version(x).stores({
//   treeNodes: 'id, [parentPath+id]' // enables where({parentPath: X, id: Y})
// });

All the mutating operations above are also sync consistent: If one offline client adds a child under "/a/b/c" and another offline client modifies all descendants under "/a/b/c" to have a new property {color: "blue"}, the merge of these operation will set {color: "blue"} on the added child also no matter in which order the clients became online. This works due to Dexie Cloud's built-in CRDT capabilities without the user having to use certain types in the objects they are storing.

The new support for moving trees

But modify-operations that use a JS callback does not benefit from sync consistency, only local consistency. Moving an entire tree from one node to another has been one of those operation that need a JS function because the new parentPath's value depends on its existing value. So a tree move has only been possible with local consistency but not sync consistency before:

function moveNode(node, newParentPath) {
  return db.transaction('rw', db.treeNodes, () => {
    // Move node. Having the parentPath criteria here is for consistency:
    // Only perform the 2 moves if parentPath is still the same.
    db.treeNodes.where({
      parentPath: node.parentPath,
      id: node.id
    }).modify({
      parentPath: newParentPath
    });
    // Move all its descendants in relation to their sub path:
    db.treeNodes.where('parentPath').startsWith(`${node.parentPath}${node.id}/`).modify(node => {
      // This is a JS callback that cannot be expressed to the server
      node.parentPath = newParentPath + node.parentPath.substring(node.parentPath.length);
    });
  });
}

JS code cannot securely be sent to the server due to several reasons: closures information missing + the risk of sending code that injects arbitrary code on the server. The operation above won't be sync consistent. If an offline client did add a new node under /a/b/c and that node is moved to /x/y/z, the merging of these operations would not be consistent - a node would still be placed under /a/b/c even though the c node has moved and doesn't exist anymore. So there is a need for declarative ways of doing certain operations, and moving trees is one of them.

A new export replacePrefix now available for this purpose. We will add more of these in coming versions (such as increment, push, deleteArrayItem, etc). replacePrefix is the first "complex" operation that already has support in Dexie Cloud (if upgrading dexie-cloud-addon to 4.0.1-beta.58) and can be executed to perform sync consistent tree moves:

import { replacePrefix } from 'dexie';

// Move subtree with sync consistency:
function moveNode(node, newParentPath) {
  return db.transaction('rw', db.treeNodes, () => {
    // Move node
    db.treeNodes.where({
      parentPath: node.parentPath, // consistency-check
      id: node.id
    }).modify({
      parentPath: newParentPath
    });
    // Move all its descendants in relation to their sub path:
    db.treeNodes
      .where('parentPath')
      .startsWith(`${node.parentPath}${node.id}/`)
      .modify({
        // Here we're in a declarative object - not a JS callback - ==> Consistent operation.
        parentPath: replacePrefix(node.parentPath, newParentPath);
      });
  });
}

This transaction does it all - it moves the node and all its descendants consistently in one atomic all-or-nothing transaction but also preserves the where-condition and the replacePrefix operation in the information to the server so that if an offline client added a node under /a/b/c, and then this operation happened, moving all descendants to the new location, and then the offline client comes online again and syncs, the new node would be placed on the correct new location and be hanging below a non-existing /a/b/c.

Consistency in conflicting move operations

If two operations competes in a move operation involving the same nodes, consistency is maintained by the extra criteria on parentPath in both the move of the parent node and the operation to move its descendants. A move operation will not be performed if another move operation came first. The end result will always be a consistent tree. The last syncer might then experience that the move operation they made got rolled back after a sync and they would instead see the peer's hierarchy.

Dexie.js - Dexie v4.0.1-beta.11

Published by dfahlander 8 months ago

Minor fix: Since 4.0.1-beta.10, we're allowing argument { disableAutoOpen: false} to db.delete() (not yet in docs), but it still failed if doing it.

Dexie.js - Dexie v3.2.6

Published by dfahlander 8 months ago

Bugfix

  • Resolve #1883: Exception when having nested index and inserting null value of nested parent (cherry-picked from 4.0.1-beta.10)
Dexie.js - Dexie v4.0.1-beta.10

Published by dfahlander 8 months ago

Fixed bug introduced the recent release [email protected]

  • Support for bfcache (to resolve #1776) had an issue that pagehide event resulted in closing down Dexie instances to a state where they did not auto-open again on pageshow.
  • The closing of connections happened no matter if event was a true bfcache event or not (didn't check the persisted property correctly)

Other

  • Fixed #1883 Exception when having nested index and inserting null value of nested parent.
  • Removed workarounds for IE11 as we are not supporting IE11 anymore
Dexie.js - Dexie v3.2.5

Published by dfahlander 9 months ago

Bugfix

  • Fix issue with BigInt64Array (#1890) (and BigUint64Array) - cherry picked from 4.0.1-beta.8
Dexie.js - Dexie v4.0.1-beta.9

Published by dfahlander 9 months ago

This is the last planned release in the series of small releases on the 4.0-track. The goal is to get a stable 4.0 release as soon as possible, but I'll wait to see some reports from usage before moving on.

Isolate readwrite transactions from live queries (#1881)

  • Don't let dexie4's new cache get optimistic updates from explicit 'rw' transactions since it breaks isolation. Still, let "transaction-less" operations (no explicit transactions from user code) shine immediately through to liveQueries if cache isn't disabled in the constructor options.
  • This makes dexie 4 behave exactly like dexie 3 when transactions are used, but may still optimize common liveQueries using the cache.
  • Still, if there are 10 identical liveQuery subscriptions on a page, only one of them will need to requery IndexedDB after a write transaction and the other 9 will get their values from the cache. This is also the case after an explicit 'rw' transaction has committed.

Improved debugging experience (#1879)

  • We're using Chrome's Async Task Tagging API to track failing operations down to the app code that initiated the operation. As long as Dexie.debug = true, we will print out call stacks in the console for any failed operation where the application code that initiated the operation is visible in the stack trace, no matter if the operation had to go through a bunch of async jobs before failing, such as implicitely opening the db in the backround, run some upgraders etc, while the only thing the user code did was a simple operation such as db.friends.get(1), but since it triggered a db open in the backround led to all these background work being performed. Before these situations were hard or almost impossible to track down to the application code.
  • Fail fast on table.get(undefined) (To avoid unreadable call stacks like this: https://github.com/dexie/Dexie.js/issues/1806#issuecomment-1884977367)
  • Remove old proprietary "long stacks" support that was tailored for older browsers and have no gain anymore.

Optimizations

  • #1821 liveQueries of the form db.someTable.orderBy('id').primaryKeys() won't be affected by a property change on an object of one of the observed keys, since the keys don't change. Only object adds and deletions will trigger the query to update.

Typings

  • Use TInsertType in Table.update and Collection.modify (#1764)

[email protected]

  • Bugfix: [email protected] was missing types (#1900)
  • Support for skipTables option to export and import (#1896)
Dexie.js -

Published by dfahlander 9 months ago

NOTE: We're aiming for a stable 4.0 to be released as soon as possible. To get there, we're releasing new versions quite frequently now. Reason: splitting up major changes into smaller releases allows users to revert versions in steps rather than the whole version.

Changed Version Handling (See PR #1880)

  • Dexie will now accept upgrading schema WITHOUT incrementing the version number
  • Dexie will now be able to open a previous version of the database without complaining

Version numbering is now only useful when you need to:

  • ...migrate the data (attaching an .upgrade() onto a version.
  • ...delete tables

Other issues:

  • Fix issue with BigInt64Array (#1890)
Dexie.js - Dexie v4.0.1-beta.7

Published by dfahlander 9 months ago

This is the first release in a series of small releases on the 4.0-track before it goes release candidate. Expect a few additional beta versions coming out soon. The goal is to get a stable 4.0 release as soon as possible.

Dexie Cloud

  • Dexie Cloud Manager where you can purchase a production subscription, manage database login policy, describe your databases and view and upgrade individual users. Also possible to specify a custom SMTP settings to relay all OTP and invite emails.
  • Latest version of dexie-cloud-addon is 4.0.1-beta.56.
  • Allow database owners to troubeshoot issues that their users are facing. A database owner with full access to the all database content through the API or through npx dexie-cloud export can now also login to their app with " as " in the email field and get the OTP sent to their own email but be authenticated as the other user.
  • Support {otp, otpId} as arguments to db.cloud.login(). The parameters must come from an OTP challenge. This will bypass the login dialog and directly authenticate the user. Usefule when customizing email templates to generate magic links with the otp and otpId as part of the query to the app.

Bugfixes

  • #1863 useLiveQuery with multi-entry-index
  • #1776 Support bfcache

dexie-export-import

Other

Dexie.js - Dexie v4.0.1-beta.6

Published by dfahlander 10 months ago

[email protected]

  • Don't patch Promise.prototype.then (#1293)
  • Resolved #1858 'Entity' is not exported from 'dexie' (imported as 'Entity')
  • Fixes to run on LambdaTest (#1752). The migration from Browserstack to Lambdatest is now complete.

[email protected]

  • Resolved #1724: Allows plus signs in email address (in order to use a single email address act as multiple users for testing)
  • Resolved dexie/dexie-cloud#4 - Automatically make "email" property of "members" lowercase and trimmed (avoid inviting members with different casing in email address)
Dexie.js - Dexie v4.0.1-beta.5

Published by dfahlander 11 months ago

  • Resolved #1831 again: Make sure liveQueries always run in own macro tasks (7c13770ffc0b8cb1189921ee6d5b4c64c4654950)
  • Resolved #1843: Avoid running dexie in double module instances (EMS module is now ESM wrapper around UMD module + detect and avoid double imports of dexie) fc572aa71a652e7c01b8bac81da6a242aef47e2c
Dexie.js - Dexie v4.0.1-beta.4

Published by dfahlander 11 months ago

[email protected]

[email protected]

Fixes #1837 - a bug in dexie-cloud-addon woken up when upgrading dexie to in 4.0.1-beta.2.

Recommended to:

Dexie.js - Dexie v4.0.1-beta.3

Published by dfahlander 11 months ago

Replaced by Dexie v4.0.1-beta.4

Dexie.js - Dexie v4.0.1-beta.2

Published by dfahlander 11 months ago

Various issues fixed, summary:

  • General stability (work around chrome issue + fix dexie issues)
  • Vite experience with dexie-react-hooks
  • Dexie Cloud developer experience

[email protected]

  • Workaround for UnknownError in Chrome (issue #543)
  • Dexie 4 optimistic updates are not reverted (issue #1823)
  • Fixed "Readwrite transaction in liveQuery context" (issue #1831)
  • Correction of Promise.finally (commit 09058eab1563d3b4eaee9c9dd3a9a03705bac132)

[email protected]

  • Improved vite experience (commit 3ff7d50a1bb263dfd15370ee674b66cfd20fa3d3)
  • Improved typing for usePermissions so that it can be used in plain interface typed tables Table (commit 437b697ffa3582fbedc0a786572e93f4b2b3e422)

[email protected]

  • Fix value of db.cloud.version (did not reveal the version of dexie-cloud-addon)
  • Fixen an issue with source map (better debugging experience)
  • Export types and helpers needed for customizing built-in OTP authentication (commit 241a76c1e4a9abb9743bd34c093505039a8bf944)
Dexie.js - Dexie v4.0.1-beta.1

Published by dfahlander about 1 year ago

[email protected]

[email protected]

  • Implementation of the new subscription model https://medium.com/dexie-js/dexie-cloud-subscription-model-cbf9a709ce7
  • Updated dexie-cloud-todo-app sample with license eval expiration alert.
  • Support for logout API instead of having to delete or clear the database: db.cloud.logout().
  • Support for logging in another user without logging out the current one (in db.cloud.login())
  • Other fixes and improvements of dexie-cloud-addon.
  • Allow expired eval users to pull down data but not to push.
  • Treat expired eval users as being forever offline (may still use app but without sync) until they are upgraded to prod by the database admin.
  • Remove console logs from the production build.
  • Default OTP GUI: Auto-submit OTP when 8 characters are pasted or written.
  • Bugfix: Syncing failed if table had inbound compound keys (#1777)
  • Handle API-Rate-limits gracefully, avoiding 429 responses by slowing down sync calls when less than 50% of remaining rate-limit are available. https://github.com/dexie/Dexie.js/commit/3c4e698464ca78c402a25b0ad4faeb539f0d4700
    New dexie-cloud option: disableEagerSync

To install / upgrade:

npm i dexie@next
npm i dexie-cloud-addon@latest
Dexie.js - Dexie v4.0.1-alpha.25

Published by dfahlander over 1 year ago

PR #1766: Dexie Cloud stuck in login-phase if option {requireAuth: true} was used to db.cloud.configure()

The fix is generic in dexie libary for db.on('ready') callbacks so that the Dexie instance passed to the callback can be used without blocking.

Background:

When the on('ready') callback executes, the ready state shall still not be resolved because any on-ready subscriber's flow is part of making the db ready to resume application queries. But the callback itself need exclusive access before application queries resume - otherwise any db call will block like if it was an application-made db call. This works fine and has been working fine since dexie@2, but has been exclusively based on an async context that spans over the entire flow of db-on-ready callbacks. However, some on-ready callbacks (specifically dexie-cloud's) need to do calls outside of Dexie - such as fetch() calls - those calls will loose the AsyncContext and thus the exclusive access to the db. Therefore, we're now providing a Dexie instance as argument to the on-ready callback - an instance that can call dexie exclusively regardless of the async context. However, a bug prevented this from functioning properly until this release.