documentsdb 0.0.3

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 54

DocumentsDB

Pub license GitHub stars

Persistent embedded document-oriented NoSQL database for Dart and Flutter. 100% Dart.

CAUTION This plugin is still in development. Use at your own risk. If you notice any bugs you can create an issue on GitHub. You're also welcome to contribute using pull requests. Please open an issue before spending time on any pull request.

NB The project was originally created by netz-chat on https://github.com/netz-chat/objectdb/blob/master/README.md.

How to use

final path = Directory.current.path + '/my.db';

// create database instance and open
final db = DocumentsDB(path);
db.open();

// insert document into database
db.insert({'name': {'first': 'Some', 'last': 'Body'}, 'age': 18, 'active': true);
db.insert({'name': {'first': 'Someone', 'last': 'Else'}, 'age': 25, 'active': false);

// update documents
db.update({Op.gte: {'age': 80}}, {'active': false});

// remove documents
db.remove({'active': false});

// search documents in database
var result = await db.find({'active': true, 'name.first': 'Some'});

// 'tidy up' the db file
db.tidy();

// close db
await db.close();

Methods

  • Future<DocumentsDB> db.open([bool tidy = true]) opens database
  • Future<void> db.tidy() 'tidy up' the .db file
  • Future<void> db.close() closes database (should be awaited to ensure all queries have been executed)

find

  • Future<List<Map>> db.find(Map query) List with all matched documents
  • Future<Map> db.first(Map query) first matched document
  • Future<Map> db.last(Map query) last matched document

insert

  • Future<ObjectId> db.insert(Map document) insert single document
  • Future<List<ObjectId>> db.insertMany(List<Map> documents) insert many documents

update

  • Future<int> db.update(Map query, Map changes, [bool replace = false]) update documents that mach query with changes (optionally replace whole document)

remove

  • Future<int> db.remove(Map query) remove documents that match query

Query

// Match fields in subdocuments
{Op.gte: {
    'birthday.year': 18
}}

// or-operator
{Op.or:{
    'active': true,
    Op.inArray: {'group': ['admin', 'moderator']}
}}

// not equal to
{Op.not: {'active': false}}

NOTE Querying arrays is not supportet yet.

Operators

Logical

  • and (default operator on first level)
  • or
  • not

Comparison

  • lt, lte: less than, less than or equal
  • gt, gte: greater than, greater than or equal
  • inList, notInList: value in list, value not in list

Modify

  • set: set value
  • max, min: set max or min int value
  • increment, multiply: increment/multiply by
  • unset: unset key/value
  • rename: rename key
  • currentDate, set current timestamp
  • add: push value
  • addAll: push many value
  • addToSet: push value if not exists
  • insert: insert value at any position in List
  • insertAll: insert many value at any position in List
  • pop, remove last value in List
  • remove, remove value
  • removeAt, remove value at any position
  • removeWhere, remove value where callback return true
  • clear: clear list/Map
  • slice: sublist List
  • sort : sort List
{Op.set: {'path.to.key': 'value'}} // set entry['path']['to']['key'] = 'value' (path will be created if not exists)
{Op.max: {'path.to.key': 200}} // set value 200 if value is greater than 200
{Op.min: {'path.to.key': 200}} // set value 200 if value is smaller than 200
{Op.increment: {'path.to.key': -5}} // increment value by negative 5
{Op.multiply: {'path.to.key': 2}} // multiply value by 2
{Op.unset: {'path.to.key': true}} // unset key/value at entry['path']['to']['key'] if exists
{Op.rename: {'path.to.key': 'new_key'}} // new value will be at entry['path']['to']['new_key']


db.update({
  'age': RegExp('[18-20]'),
  Op.gt: {'duration': 500},
}, {
  Op.max: {'stats.score': 100},
  Op.increment: {'stats.level': -5},
});

Examples

// query
var result = db.find({
    'active': true,
    Op.or: {
        Op.inList: {'state': ['Florida', 'Virginia', 'New Jersey']},
        Op.gte: {'age': 30},
    }
});

// same as
var match = (result['active'] == true && (['Florida', 'Virginia', 'New Jersey'].contains(result['state']) || result['age'] >= 30));

Todo's

  • [x] regex match
  • [ ] encryption
  • [ ] querying arrays
  • [ ] benchmarks
  • [ ] indexing

License

See License

[0.0.1] - TODO: Add release date.

  • TODO: Describe initial release.

example/main.dart

import 'dart:io';

import 'package:documentsdb/documentsdb.dart';

void main() async {
  final path = Directory.current.path + '/test/';

  /** 
     timestampData: if true fields createdAt and updatedAt will be added on insertion 
     
     inMemoryOnly : if true path will be ignore and all data will be in memory
    **/
  final db =
      DocumentsDB(path + 'test.db', timestampData: true, inMemoryOnly: false);
  await db.open();

  /**   Index field
   *    fieldNames is List of fields to index
   *    unique : if true verify if value of each field of List has unique value
   *    mandatory : if true each field of List is require on insertion and cannot remove on update
   * 
   * expireAfterSeconds options if set will remove indexing on each field on List at specified date
   * 
   * 
   */
  await db.ensureIndex(['type.at'], mandatory: true, unique: true);

  /**  Trigger  
   *   onInsert, onUpdate, onRemove to add trigger on these events
   * 
   *   There are also possibility to set trigger before or after each event
   * 
   *  **/
  Function condition = (dataToInsert) {
    //print('condition $dataToInsert');
    return true;
  };

  db.trigger.onInsert.onBefore.addAll({
    condition: (dataToInsert) {
      //print('trigger on insert $insertedData');
    }
  });

  /*
      Listen insert,update,remove event
    */
  db.onUpdate.listen((data) {
    //print('on update $data');
  });
  db.onInsert.listen((data) {
    //print('on onInsert $data');
  });
  db.onRemove.listen((data) {
    //print('on onRemove $data');
  });
  db.watch().listen((data) {
    //print('db changes without query $data');
  });
  db.watch({"a": "1"}).listen((data) {
    //print('db changes with query $data');
  });

  db.insert({'a': '6'}).then((data) {
    print("insert  $data");
  }).catchError((e) {
    print("catch insert 6 $e");
  });

  db.insertMany([
    {
      'type': {'at': '1'}
    },
    {
      'type': {'at': '2'}
    },
    {
      'type': {'at': '3'}
    },
    {
      'type': {'at': '4'}
    }
  ]).then((data) {
    print("insert many $data");
  }).catchError((e) {
    print("catch insertion many $e");
  });
  db.update({
    "type.at": "4"
  }, {
    'type': {'eee': '4'}
  }, upsert: true).then((data) {
    print("update $data");
  }).catchError((e) {
    print("catch with query `'type.at': '4'` $e");
  });

  db.findAndUpdate({
    "type.at": "four"
  }, {
    'type': {'eee': 'four'}
  }).then((count) {
    print("update where type.at equals four : $count");
  }).catchError((e) {
    print("failed to update where type.at equals four $e");
  });

  db.findOneAndUpdate({
    "type.at": "one"
  }, {
    'type': {'eee': '4'}
  }).then((count) {
    print("update where type.at equals one : $count");
  }).catchError((e) {
    print("failed to update where type.at equals one $e");
  });

  db.update({
    'type.at': '4'
  }, {
    Op.unset: {"type.at": true}
  }, upsert: true).then((data) {
    print("unset where type.at equals 4 : $data");
  }).catchError((e) {
    print("failed to unset where type.at equals 4 : $e");
  });

  print(await db.remove({'a': RegExp('[3-6]')}));

  print(await db.removeOne({'a': RegExp('[3-6]')}));

  db.findOneAndRemove({"type.at": "4"}).then((count) {
    print("findOneAndRemove where at = '4' $count");
  }).catchError((e) {
    print("failed to findOneAndRemove where at = '4': $e");
  });

  print(await db.find({
    Op.exists: {'e.c.d[0]': true, 'a': true}
  }, projection: {
    'e': false,
    'a': false
  }, sort: {
    'e.c.d[0].dsqd': 1,
    'a': 1
  }, skip: 2, limit: 1));

  db.insertMany([
    {'a': '1'},
    {'a': '2'},
    {'a': '3'},
    {'a': '4'},
  ]).then((ids) async {
    print("ids = $ids");
    print(await db.find({'_id': ids[2]}));
  }).catchError((e) {
    print('failed to insert many a: $e');
  });

  /* db.insert({'a': '6'});
  db.insert({'a': '7'});
  db.insert({'a': '8'});
  db.insert({'a': '9'}); */

  db.update({
    Op.gt: {'a': '0'},
    'a': RegExp('[4-7]'),
  }, {
    Op.max: {'n': 100},
    'b': 'c'
  }).then((count) {
    print("update to max where Op.gt $count");
  }).catchError((e) {
    print("failed to update to max where Op.gt $e");
  });

  db.update({
    Op.gt: {'a': '0'},
    'a': RegExp('[4-7]'),
  }, {
    Op.rename: {'b': 'ΓΌ'},
    Op.unset: {'n': true},
    Op.addToSet: {"script": 'dart', "year": "2018"},
    Op.currentDate: {"year": true}
  }).then((count) {
    print("update where Op.gt $count");
  }).catchError((e) {
    print("failed to update where Op.gt $e");
  });

  print(await db.last({
    Op.gt: {'a': 0},
  }));

  print(await db.find({
    Op.gt: {'a': 0},
  }));

  db.removeIndex(['type']);
  print(await db.findOneAndRemove({'a': '5'}));
  // count data where match query
  print(await db.count({}));

  /*
  import data from File or Map
   */
  db.importFromFile([
    {"_id": "5b78bdb6702de39b30e6f68b", "b": "6"},
    {"_id": "5b78bdb6702de39b30e6f68c", "b": "12"},
    {"_id": "5b78bdb6702de39b30e6f68d", "b": "script"},
    {
      "b": "102",
      'type': {'at': 'title'},
      "_id": "5b77480133bd7f87d4030e15",
      "o": {"sqdq": []}
    }
  ]).then((data) {
    print('import data');
  }).catchError((e) {
    print("failed to import data $e");
  });

  await db.tidy();
  await db.close();
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  documentsdb: ^0.0.3

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:documentsdb/documentsdb.dart';
  
Version Uploaded Documentation Archive
0.0.3 Aug 22, 2018 Go to the documentation of documentsdb 0.0.3 Download documentsdb 0.0.3 archive
0.0.2 Aug 20, 2018 Go to the documentation of documentsdb 0.0.2 Download documentsdb 0.0.2 archive
0.0.1 Aug 20, 2018 Go to the documentation of documentsdb 0.0.1 Download documentsdb 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
20
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
70
Overall:
Weighted score of the above. [more]
54
Learn more about scoring.

We analyzed this package on Dec 5, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.7
  • Flutter: 1.0.0

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Fix lib/src/documentsdb_base.dart. (-0.50 points)

Analysis of lib/src/documentsdb_base.dart reported 1 hint:

line 1088 col 14: The value of the local variable 'formattedI' isn't used.

Maintenance suggestions

The description is too short. (-20 points)

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Package is pre-v0.1 release. (-10 points)

While there is nothing inherently wrong with versions of 0.0.*, it usually means that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.68.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test