Code Monkey home page Code Monkey logo

hive's Introduction

Fast, Enjoyable & Secure NoSQL Database

GitHub Workflow Status (branch) Codecov branch Pub Version GitHub

Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by Bitcask.

Documentation & Samples ๐Ÿ“–

Before you start

Consider using Isar, a Flutter database by the author of Hive that is superior in every way!

Features

  • ๐Ÿš€ Cross platform: mobile, desktop, browser
  • โšก Great performance (see benchmark)
  • โค๏ธ Simple, powerful, & intuitive API
  • ๐Ÿ”’ Strong encryption built in
  • ๐ŸŽˆ NO native dependencies
  • ๐Ÿ”‹ Batteries included

Getting Started

Check out the Quick Start documentation to get started.

Usage

You can use Hive just like a map. It is not necessary to await Futures.

var box = Hive.box('myBox');

box.put('name', 'David');

var name = box.get('name');

print('Name: $name');

BoxCollections

BoxCollections are a set of boxes which can be similarly used as normal boxes, except of that they dramatically improve speed on web. They support opening and closing all boxes of a collection at once and more efficiently store data in indexed DB on web.

Aside, they also expose Transactions which can be used to speed up tremendous numbers of database transactions on web.

On dart:io platforms, there is no performance gain by BoxCollections or Transactions. Only BoxCollections might be useful for some box hierarchy and development experience.

// Create a box collection
  final collection = await BoxCollection.open(
    'MyFirstFluffyBox', // Name of your database
    {'cats', 'dogs'}, // Names of your boxes
    path: './', // Path where to store your boxes (Only used in Flutter / Dart IO)
    key: HiveCipher(), // Key to encrypt your boxes (Only used in Flutter / Dart IO)
  );

  // Open your boxes. Optional: Give it a type.
  final catsBox = collection.openBox<Map>('cats');

  // Put something in
  await catsBox.put('fluffy', {'name': 'Fluffy', 'age': 4});
  await catsBox.put('loki', {'name': 'Loki', 'age': 2});

  // Get values of type (immutable) Map?
  final loki = await catsBox.get('loki');
  print('Loki is ${loki?['age']} years old.');

  // Returns a List of values
  final cats = await catsBox.getAll(['loki', 'fluffy']);
  print(cats);

  // Returns a List<String> of all keys
  final allCatKeys = await catsBox.getAllKeys();
  print(allCatKeys);

  // Returns a Map<String, Map> with all keys and entries
  final catMap = await catsBox.getAllValues();
  print(catMap);

  // delete one or more entries
  await catsBox.delete('loki');
  await catsBox.deleteAll(['loki', 'fluffy']);

  // ...or clear the whole box at once
  await catsBox.clear();

  // Speed up write actions with transactions
  await collection.transaction(
    () async {
      await catsBox.put('fluffy', {'name': 'Fluffy', 'age': 4});
      await catsBox.put('loki', {'name': 'Loki', 'age': 2});
      // ...
    },
    boxNames: ['cats'], // By default all boxes become blocked.
    readOnly: false,
  );

Store objects

Hive not only supports primitives, lists and maps but also any Dart object you like. You need to generate a type adapter before you can store objects.

@HiveType(typeId: 0)
class Person extends HiveObject {

  @HiveField(0)
  String name;

  @HiveField(1)
  int age;
}

Extending HiveObject is optional but it provides handy methods like save() and delete().

var box = await Hive.openBox('myBox');

var person = Person()
  ..name = 'Dave'
  ..age = 22;
box.add(person);

print(box.getAt(0)); // Dave - 22

person.age = 30;
person.save();

print(box.getAt(0)) // Dave - 30

Hive โค๏ธ Flutter

Hive was written with Flutter in mind. It is a perfect fit if you need a lightweight datastore for your app. After adding the required dependencies and initializing Hive, you can use Hive in your project:

import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

class SettingsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: Hive.box('settings').listenable(),
      builder: (context, box, widget) {
        return Switch(
          value: box.get('darkMode'),
          onChanged: (val) {
            box.put('darkMode', val);
          }
        );
      },
    );
  }
}

Boxes are cached and therefore fast enough to be used directly in the build() method of Flutter widgets.

Native AES crypto implementation

When using Flutter, Hive supports native encryption using package:cryptography and package:cryptography_flutter.

Native AES implementations tremendously speed up operations on encrypted Boxes.

Please follow these steps:

  1. add dependency to pubspec.yaml
dependencies:
  cryptography_flutter: ^2.0.2
  1. enable native implementations
import 'package:cryptography_flutter/cryptography_flutter.dart';

void main() {
  // Enable Flutter cryptography
  FlutterCryptography.enable();

  // ....
}

Benchmark

1000 read iterations 1000 write iterations
SharedPreferences is on par with Hive when it comes to read performance. SQLite performs much worse. Hive greatly outperforms SQLite and SharedPreferences when it comes to writing or deleting.

The benchmark was performed on a Oneplus 6T with Android Q. You can run the benchmark yourself.

*Take this benchmark with a grain of salt. It is very hard to compare databases objectively since they were made for different purposes.

Licence

Copyright 2019 Simon Leier

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

hive's People

Contributors

afsar-pasha avatar amondnet avatar dev-horacebg avatar dipu-bd avatar inconnu08 avatar jgtm2024 avatar jibiel avatar jukqaz avatar kalildev avatar kranfix avatar krille-chan avatar marcelgarus avatar marci002 avatar michael77 avatar miltoneiji avatar nico-famedly avatar reprevise avatar ricardorb avatar ryojiro avatar saibotma avatar sergeshkurko avatar shroff avatar simc avatar sorunome avatar themisir avatar theonewiththebraid avatar tomassasovsky avatar victoruvarov avatar wbusey0 avatar wenhaowu avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.