├── .github ├── hive.svg ├── logo.svg ├── logo_transparent.svg └── workflows │ ├── release.yml │ └── test.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── example └── README.md ├── lib ├── hive.dart └── src │ ├── box.dart │ ├── hive.dart │ └── impl │ ├── box_impl.dart │ ├── frame.dart │ ├── frame.g.dart │ ├── isolate_stub.dart │ └── type_registry.dart ├── pubspec.yaml └── test ├── box_test.dart └── common.dart /.github/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/logo_transparent.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Hive release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | jobs: 9 | release: 10 | name: Release 11 | runs-on: ubuntu-latest 12 | permissions: 13 | id-token: write 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Setup Dart 17 | uses: dart-lang/setup-dart@v1 18 | - name: Wait for tests to succeed 19 | uses: lewagon/wait-on-check-action@v1.3.1 20 | with: 21 | ref: ${{ github.ref }} 22 | running-workflow-name: "Release" 23 | repo-token: ${{ secrets.GITHUB_TOKEN }} 24 | wait-interval: 10 25 | - name: pub.dev credentials 26 | run: | 27 | mkdir -p $HOME/.config/dart 28 | echo '${{ secrets.PUB_JSON }}' >> $HOME/.config/dart/pub-credentials.json 29 | - name: Publish hive 30 | run: | 31 | dart pub get 32 | dart pub publish --force 33 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Dart CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | format: 7 | name: Check formatting 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v3 11 | - name: Setup Dart 12 | uses: dart-lang/setup-dart@v1 13 | - name: Install dependencies 14 | run: dart pub get 15 | - name: Check formatting 16 | run: dart format -o none . --set-exit-if-changed 17 | 18 | lint: 19 | name: Check lints 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@v3 23 | - name: Setup Dart 24 | uses: dart-lang/setup-dart@v1 25 | - name: Install dependencies 26 | run: dart pub get 27 | - name: Check Lints 28 | run: dart analyze 29 | 30 | test: 31 | name: Test 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v3 35 | - name: Setup Dart 36 | uses: dart-lang/setup-dart@v1 37 | - name: Install dependencies 38 | run: dart pub get 39 | - name: Run tests 40 | run: dart test 41 | 42 | coverage: 43 | name: Code Coverage 44 | runs-on: ubuntu-latest 45 | steps: 46 | - uses: actions/checkout@v3 47 | - name: Setup Flutter 48 | uses: subosito/flutter-action@v2 49 | - name: Install dependencies 50 | run: flutter pub get 51 | - name: Code Coverage 52 | run: flutter test --coverage --coverage-path lcov.info 53 | - name: Upload Coverage 54 | uses: codecov/codecov-action@v3 55 | with: 56 | token: ${{ secrets.CODECOV_TOKEN }} 57 | files: lcov.info 58 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.hive 2 | .test_coverage.dart 3 | coverage_badge.svg 4 | 5 | 6 | # Miscellaneous 7 | *.class 8 | *.lock 9 | *.log 10 | *.pyc 11 | *.swp 12 | .DS_Store 13 | .atom/ 14 | .buildlog/ 15 | .history 16 | .svn/ 17 | 18 | # IntelliJ related 19 | *.iml 20 | *.ipr 21 | *.iws 22 | .idea/ 23 | 24 | # Visual Studio Code related 25 | .vscode/ 26 | 27 | # Flutter repo-specific 28 | /bin/cache/ 29 | /bin/mingit/ 30 | /dev/benchmarks/mega_gallery/ 31 | /dev/bots/.recipe_deps 32 | /dev/bots/android_tools/ 33 | /dev/docs/doc/ 34 | /dev/docs/flutter.docs.zip 35 | /dev/docs/lib/ 36 | /dev/docs/pubspec.yaml 37 | /packages/flutter/coverage/ 38 | version 39 | 40 | # packages file containing multi-root paths 41 | .packages.generated 42 | 43 | # Flutter/Dart/Pub related 44 | **/doc/api/ 45 | .dart_tool/ 46 | .flutter-plugins 47 | .packages 48 | .pub-cache/ 49 | .pub/ 50 | build/ 51 | flutter_*.png 52 | linked_*.ds 53 | unlinked.ds 54 | unlinked_spec.ds 55 | 56 | # Android related 57 | **/android/**/gradle-wrapper.jar 58 | **/android/.gradle 59 | **/android/captures/ 60 | **/android/gradlew 61 | **/android/gradlew.bat 62 | **/android/local.properties 63 | **/android/**/GeneratedPluginRegistrant.java 64 | **/android/key.properties 65 | *.jks 66 | 67 | # iOS/XCode related 68 | **/ios/**/*.mode1v3 69 | **/ios/**/*.mode2v3 70 | **/ios/**/*.moved-aside 71 | **/ios/**/*.pbxuser 72 | **/ios/**/*.perspectivev3 73 | **/ios/**/*sync/ 74 | **/ios/**/.sconsign.dblite 75 | **/ios/**/.tags* 76 | **/ios/**/.vagrant/ 77 | **/ios/**/DerivedData/ 78 | **/ios/**/Icon? 79 | **/ios/**/Pods/ 80 | **/ios/**/.symlinks/ 81 | **/ios/**/profile 82 | **/ios/**/xcuserdata 83 | **/ios/.generated/ 84 | **/ios/Flutter/App.framework 85 | **/ios/Flutter/Flutter.framework 86 | **/ios/Flutter/Generated.xcconfig 87 | **/ios/Flutter/app.flx 88 | **/ios/Flutter/app.zip 89 | **/ios/Flutter/flutter_assets/ 90 | **/ios/Flutter/flutter_export_environment.sh 91 | **/ios/ServiceDefinitions.json 92 | **/ios/Runner/GeneratedPluginRegistrant.* 93 | 94 | # Coverage 95 | coverage/ 96 | 97 | # JavaScipt 98 | web_worker.dart.js* 99 | 100 | # Exceptions to above rules. 101 | !**/ios/**/default.mode1v3 102 | !**/ios/**/default.mode2v3 103 | !**/ios/**/default.pbxuser 104 | !**/ios/**/default.perspectivev3 105 | !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages 106 | 107 | *.dylib 108 | *.so 109 | *.dll -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 4.0.0-dev.2 2 | 3 | ⚠️ THIS VERSION OF HIVE IS UNSTABLE AND NOT READY FOR PRODUCTION USE ⚠️ 4 | 5 | This is a complete rewrite of Hive. It is not compatible with older versions of Hive yet. 6 | 7 | Hive now uses Isar internally which brings all the benefits of a native database to Hive. 8 | 9 | ### Enchantments 10 | 11 | - Much more resource efficiency 12 | - Support for access from multiple isolates 13 | - Support for transactions 14 | - No more issues with concurrent access and corruption 15 | - Vastly reduced startup time 16 | - No more code generation 17 | 18 | # 3.0.0-dev 19 | 20 | ### Enchantments 21 | 22 | - Implemented in-memory storage backend 23 | - Added `notify` parameter to public APIs 24 | - Web Worker support 25 | - Threaded AesCipher support (requires hive_flutter >=2.0.0-dev) 26 | 27 | # 2.2.3 28 | 29 | ### Enhancements 30 | 31 | - Exposed `resetAdapters` method for testing - [#1014](https://github.com/hivedb/hive/pull/1014) 32 | - Removed unnecessary print statement - [#1015](https://github.com/hivedb/hive/pull/1015) 33 | 34 | # 2.2.2 35 | 36 | ### Fixes 37 | 38 | - Register DateTime adapter on web - [#983](https://github.com/hivedb/hive/pull/983) 39 | 40 | # 2.2.1 41 | 42 | ### Fixes 43 | 44 | - Retracted hive@2.2.0 from pub.dev 45 | - Fixed hive web backend null value exception - [#968](https://github.com/hivedb/hive/pull/968) 46 | 47 | # 2.2.0 48 | 49 | ### Enhancements 50 | 51 | - Added multiple storage backends for web - [#956](https://github.com/hivedb/hive/pull/956) 52 | 53 | # 2.1.0 54 | 55 | ### Fixes 56 | 57 | - Do not return uninitialized box - [#916](https://github.com/hivedb/hive/pull/916) 58 | 59 | ### Enhancements 60 | 61 | - Adapter type inheritance - [#927](https://github.com/hivedb/hive/pull/927) 62 | - UTF8 keys - [#928](https://github.com/hivedb/hive/pull/928) 63 | 64 | # 2.0.6 65 | 66 | ### Fixes 67 | 68 | - Fixed issue caused database to crash when executing crash recovery - [#914](https://github.com/hivedb/hive/pull/914) 69 | 70 | # 2.0.5 71 | 72 | ### Enhancements 73 | 74 | - Get IndexedDB selectively based on window property - [#802](https://github.com/hivedb/hive/pull/802) 75 | - Added `path` parameter to `boxExists` and `deleteBoxFromDisk` methods - [#776](https://github.com/hivedb/hive/pull/776) 76 | - Added `flush` method to boxes - [#852](https://github.com/hivedb/hive/pull/852) 77 | 78 | ### Fixes 79 | 80 | - Don't loose track of box objects if init crashes - [#846](https://github.com/hivedb/hive/pull/846) 81 | 82 | # 2.0.4 83 | 84 | ### Enhancements 85 | 86 | - Adds default value support to hive_generator generated class adapters 87 | 88 | # 2.0.3 89 | 90 | ### Fixes 91 | 92 | - Fix regression where lists are no longer growable - [#631](https://github.com/hivedb/hive/pull/631) 93 | 94 | # 2.0.2 95 | 96 | ### Fixes 97 | 98 | - `HiveObjectMixin` not assigning box to object - [#618](https://github.com/hivedb/hive/issues/618) 99 | 100 | # 2.0.1 101 | 102 | ### Fixes 103 | 104 | - `BoxEvent` value is `null` when watching a `LazyBox` - [#592](https://github.com/hivedb/hive/pull/592) 105 | - Allow calling `.init()` multiple times, instead of throwing error Hive will print warning to console 106 | - Hive will warn developers when registering adapters for `dynamic` type 107 | 108 | # 2.0.0 109 | 110 | ### Fixes 111 | 112 | - Stable null-safety version 113 | 114 | # 1.6.0-nullsafety.2 115 | 116 | ### Fixes 117 | 118 | - Added `defaultValue` property to `@HiveField()` annotation - [#557](https://github.com/hivedb/hive/pull/557) 119 | 120 | # 1.6.0-nullsafety.1 121 | 122 | ### Fixes 123 | 124 | - Changed `meta` dependency version to `^1.3.0-nullsafety` to support null-safety 125 | 126 | # 1.6.0-nullsafety.0 127 | 128 | ### Breaking changes 129 | 130 | - Migrate to null-safety - [#521](https://github.com/hivedb/hive/pull/521) 131 | - Update minimum Dart sdk constraint to 2.12.0-0. 132 | - In order to generate null-safe code use hive_generator >= 0.9.0-nullsafety.0 133 | 134 | # 1.5.0-pre 135 | 136 | ### Enhancements 137 | 138 | - Timezone support for DateTime - [#419](https://github.com/hivedb/hive/issues/419) 139 | 140 | # 1.4.4+1 141 | 142 | ### Fixes 143 | 144 | - Browser support for `BackendManager.boxExists(boxName, path)` - [#451](https://github.com/hivedb/hive/issues/451) 145 | 146 | # 1.4.4 147 | 148 | ### Fixes 149 | 150 | - Edge browser support - [#357](https://github.com/hivedb/hive/issues/357) 151 | 152 | # 1.4.3 153 | 154 | ### Enhancements 155 | 156 | - Added `Hive.ignoreTypeId(typeId)` - [#397](https://github.com/hivedb/hive/pull/397) 157 | 158 | ### Fixes 159 | 160 | - `open(Lazy)Box` can potentially open a box twice - [#345](https://github.com/hivedb/hive/issues/345) 161 | - Remove extra byte reservation in writeBoolLis - [#398](https://github.com/hivedb/hive/pull/398) 162 | 163 | # 1.4.2 164 | 165 | ### Fixes 166 | 167 | - Fixed dependency issues and minor improvements 168 | 169 | # 1.4.1+1 170 | 171 | ### Other 172 | 173 | - Added docs to all public members 174 | 175 | # 1.4.1 176 | 177 | ### Enhancements 178 | 179 | - Minor performance improvements 180 | 181 | ### Fixes 182 | 183 | - When a database operation failed, subsequent operations would not be performed 184 | 185 | ### Other 186 | 187 | - Fixed GitHub homepage path 188 | 189 | # 1.4.0+1 190 | 191 | ### Enhancements 192 | 193 | - Minor performance improvements 194 | 195 | ### Fixes 196 | 197 | - Allow more versions of `crypto` 198 | 199 | # 1.4.0 200 | 201 | ### Enhancements 202 | 203 | - ~1000% encryption / decryption performance improvement 204 | - Added option to implement custom encryption algorithm 205 | - Added `box.valuesBetween(startKey, endKey)` 206 | - Allow tree shaking to drop encryption engine if no encryption is used 207 | 208 | ### Fixes 209 | 210 | - `Hive.deleteBoxFromDisk()` did not work for boxes with upper-case names 211 | 212 | ### More 213 | 214 | - Deprecated `encryptionKey` parameter. Use `Hive.openBox('name', encryptionCipher: HiveAesCipher(yourKey))`. 215 | - Dropped `pointycastle` dependency 216 | - Dropped `path` dependency 217 | 218 | # 1.3.0 219 | 220 | _Use latest version of `hive_generator`_ 221 | 222 | ### Breaking changes 223 | 224 | - `TypeAdapters` and `@HiveType()` now require a `typeId` 225 | - `Hive.registerAdapter()` does not need a `typeId` anymore. 226 | - Removed `BinaryReader.readAsciiString()` 227 | - Removed `BinaryWriter.writeAsciiString()` 228 | 229 | ### Enhancements 230 | 231 | - New documentation with tutorials and live code 232 | 233 | ### Fixes 234 | 235 | - `box.clear()` resets auto increment counter 236 | 237 | ### More 238 | 239 | - Not calling `Hive.init()` results in better exception 240 | 241 | # 1.2.0 242 | 243 | ### Breaking changes 244 | 245 | - Removed the `Hive.path` getter 246 | - Removed `Hive.openBoxFromBytes()` (use the `bytes` parameter of `Hive.openBox()` instead) 247 | - `LazyBox` and `Box` now have a common parent class: `BoxBase` 248 | - Lazy boxes need to be opened using `Hive.openLazyBox()` 249 | - Open lazy boxes can be acquired using `Hive.lazyBox()` 250 | - Box name bug resolved (more information below) 251 | 252 | ### Enhancements 253 | 254 | - Support for relationships, `HiveLists` (see docs for details) 255 | - Support for inheritance 256 | - Lazy boxes can now have a type argument `LazyBox` 257 | - Added method to delete boxes without opening them `Hive.deleteBoxFromDisk()` 258 | - Added `path` parameter to open boxes in a custom path 259 | - Improved documentation 260 | 261 | ### Fixes 262 | 263 | - `HiveObjects` have not been initialized correctly in lazy boxes 264 | - Fixed bug where uppercase box name resulted in an uppercase filename 265 | - Fixed compaction bug which caused corrupted boxes 266 | - Fixed bug which did not allow the key `0xFFFFFFFF` 267 | - Fixed bug where not all `BoxEvent`s have been broadcasted 268 | 269 | ### More 270 | 271 | - Changed type of `encryptionKey` from `Uint8List` to `List` 272 | 273 | ### Important: 274 | 275 | Due to a bug in previous Hive versions, boxes whose name contains uppercase characters were stored in a file that also contains upper case characters (e.g. 'myBox' -> 'myBox.hive'). 276 | 277 | To avoid different behavior on case sensitive file systems, Hive should store files with lower case names. This bug has been resolved in version 1.2.0. 278 | 279 | If your box name contains upper case characters, the new version will not find a box stored by an older version. Please rename the hive file manually in that case. 280 | This also applies to the web version. 281 | 282 | # 1.1.1 283 | 284 | ### Breaking changes 285 | 286 | - `object.delete()` now throws exception if object is not stored in a box 287 | 288 | ### Fixes 289 | 290 | - Fixed bug where `object.save()` would fail on subsequent calls 291 | 292 | # 1.1.0+2 293 | 294 | ### Fixes 295 | 296 | - Fixed bug that it was not possible to open typed boxes (`Box`) 297 | 298 | # 1.1.0+1 299 | 300 | ### Fixes 301 | 302 | - Fixed bug that corrupted boxes were not detected 303 | 304 | # 1.1.0 305 | 306 | ### Breaking changes 307 | 308 | - Changed return type of `addAll()` from `List` to `Iterable`. 309 | - Removed the option to register `TypeAdapters` for a specific box. E.g. `box.registerTypeAdapter()`. 310 | - `getAt()`, `putAt()`, `deleteAt()` and `keyAt()` no longer allow indices out of range. 311 | 312 | ### Enhancements 313 | 314 | - Added `HiveObject` 315 | - Boxes have now an optional type parameter `Box` 316 | - Support opening boxes from assets 317 | 318 | ### Fixes 319 | 320 | - Fixed bug which was caused by not awaiting write operations 321 | - Fixed bug where custom compaction strategy was not applied 322 | - Hive now locks box files while they are open to prevent concurrent access from multiple processes 323 | 324 | ### More 325 | 326 | - Improved performance of `putAll()`, `deleteAll()`, `add()`, `addAll()` 327 | - Changed `values` parameter of `addAll()` from `List` to `Iterable` 328 | - Improved documentation 329 | - Preparation for queries 330 | 331 | # 1.0.0 332 | 333 | - First stable release 334 | 335 | # 0.5.1+1 336 | 337 | - Change `keys` parameter of `deleteAll` from `List` to `Iterable` 338 | - Fixed bug in `BinaryWriter` 339 | 340 | # 0.5.1 341 | 342 | - Fixed `Hive.init()` bug in browser 343 | - Fixed a bug with large lists or strings 344 | - Improved box opening time in the browser 345 | - Improved general write performance 346 | - Improved docs 347 | - Added integration tests 348 | 349 | # 0.5.0 350 | 351 | - Added `keyComparator` parameter for custom key order 352 | - Added `isEmpty` and `isNotEmpty` getters to box 353 | - Added support for reading and writing subclasses 354 | - Removed length limitation for Lists, Maps, and Strings 355 | - Greatly improved performance of storing Uint8Lists in browser 356 | - Removed CRC check in the browser (not needed) 357 | - Improved documentation 358 | - TypeIds are now allowed in the range of 0-223 359 | - Fixed compaction 360 | - Fixed writing longer Strings 361 | - **Breaking:** Binary format changed 362 | 363 | # 0.4.1+1 364 | 365 | - Document all public APIs 366 | - Fixed flutter_web error 367 | 368 | # 0.4.1 369 | 370 | - Allow different versions of the `path` package 371 | 372 | # 0.4.0 373 | 374 | - Added `BigInt` support 375 | - Added `compactionStrategy` parameter 376 | - Added automatic crash recovery 377 | - Added `add()` and `addAll()` for auto-increment keys 378 | - Added `getAt()`, `putAt()` and `deleteAt()` for working with indices 379 | - Support for int (32 bit unsigned) keys 380 | - Non-lazy boxes now notify their listeners immediately about changes 381 | - Bugfixes 382 | - More tests 383 | - **Breaking:** Open boxes with `openBox()` 384 | - **Breaking:** Writing `null` is no longer equivalent to deleting a key 385 | - **Breaking:** Temporarily removed support for transactions. New API design needed. Will be coming back in a future version. 386 | - **Breaking:** Binary format changed 387 | - **Breaking:** API changes 388 | 389 | # 0.3.0+1 390 | 391 | - Bugfix: `Hive['yourBox']` didn't work with uppercase box names 392 | 393 | # 0.3.0 394 | 395 | - Big step towards stable API 396 | - Support for transactions 397 | - Annotations for hive_generator 398 | - Bugfixes 399 | - Improved web support 400 | - **Breaking:** `inMemory` -> `lazy` 401 | - **Breaking:** Binary format changed 402 | 403 | # 0.2.0 404 | 405 | - Support for dart2js 406 | - Improved performance 407 | - Added `inMemory` option 408 | - **Breaking:** Minor API changes 409 | - **Breaking:** Changed Endianness to little 410 | - **Breaking:** Removed Migrator 411 | 412 | # 0.1.1 413 | 414 | - Downgrade to `meta: ^1.1.6` to support flutter 415 | 416 | # 0.1.0 417 | 418 | - First release 419 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 |

Fast, Enjoyable & Secure NoSQL Database

5 | 6 |

7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 |

23 | 24 | Hive is a lightweight and buzzing-fast key-value database made for Flutter and Dart. 25 | 26 | ## Features 🌟 27 | 28 | - 🌍 Bee everywhere: mobile, desktop, browser 29 | - 🚀 Buzzing speed: Faster than a bee on caffeine! 30 | - 💡 Sweet, powerful, & intuitive API 31 | - 🔐 Queen's Guard: Encryption built right in. 32 | - 🧠 Thinking in swarms: Multi-isolate support. 33 | - 🍯 Everything a bee needs and more! 34 | 35 | > Bee fact: A single bee can visit 5,000 flowers in a day! 36 | 37 | ## Buzz into Action 🐝 38 | 39 | Feeling the excitement? Great! Let's help you take your first flight with Hive. 40 | 41 | #### 🔗 Add dependencies 42 | 43 | To kickstart the journey add `hive`, `isar_flutter_libs` and `path_provider` to your `pubspec.yaml`. 44 | 45 | ```yaml 46 | dependencies: 47 | hive: ^4.0.0 48 | isar_flutter_libs: ^4.0.0-dev.13 49 | path_provider: ^2.1.0 50 | ``` 51 | 52 | Pssst! 🤫 `path_provider` will help you to find the optimal directory for each platform. 53 | 54 | #### 🏡 Designate a Home 55 | 56 | Hive needs a place to call home. Using `path_provider` we can find a valid directory. 57 | 58 | ```dart 59 | void main() async { 60 | WidgetsFlutterBinding.ensureInitialized(); 61 | final dir = await getApplicationDocumentsDirectory(); 62 | Hive.defaultDirectory = dir.path; 63 | 64 | // ... 65 | } 66 | ``` 67 | 68 | #### 🏁 And... Action! 69 | 70 | Woohoo! You're all set. Jump in and let your Hive adventure begin! 71 | 72 | ```dart 73 | import 'package:hive/hive.dart'; 74 | 75 | final box = Hive.box(); 76 | box.put('name', 'David'); 77 | 78 | final name = box.get('name'); 79 | print('Name: $name'); 80 | ``` 81 | 82 | > Bee fact: Honeybees can fly at a speed of up to 30 kilometers per hour! 83 | 84 | # 📚 Hive Handbook 85 | 86 | In Hive, data is neatly organized into containers known as boxes. Think of boxes as tables you'd find in SQL, but far more flexible — they don't stick to a set structure and can contain a variety of data. Boxes can be encrypted to store sensitive data. 87 | 88 | ## Table of Contents 89 | 90 | Want to jump to a specific section? Here's a handy table of contents: 91 | 92 | - [Opening Boxes](#-opening-boxes) 93 | - [Closing Boxes](#-bidding-adieu-closing-boxes) 94 | - [Inserting](#-filling-the-honeycomb-inserting-data) 95 | - [Reading](#-extracting-honey-i-mean-data) 96 | - [Deleting](#-deleting-data) 97 | - [Using Boxes like Lists](#-using-boxes-like-lists) 98 | - [Type safety](#-type-safety) 99 | - [Non-primitive Objects](#-bee-yond-the-basics-non-primitive-objects) 100 | - [Transactions](#-transactions) 101 | - [Isolates](#-the-isolate-dance) 102 | - [FAQ](#-buzzworthy-questions) 103 | 104 | > Bee fact: Bees have five eyes – three simple eyes on top of the head, and two compound eyes, with numerous hexagonal facets. 105 | 106 | ### 📦 Opening Boxes 107 | 108 | Your journey with Hive begins with opening your first box. Trust me, it's unbee-lievably easy: 109 | 110 | ```dart 111 | final box = Hive.box(name: 'myBox'); 112 | ``` 113 | 114 | When you call `Hive.box(name: 'myBox')` for the first time with a given name, Hive will create a new box for you. If you call it again with the same name, Hive will return the already existing box. 115 | 116 | You can also use `Hive.box()` without providing a name. In this case, Hive will return the default box. 117 | 118 | There are optional parameters you can pass to `Hive.box()`: 119 | 120 | | Parameter | Description | 121 | | --------------- | ------------------------------------------------------------------------- | 122 | | `name` | Label your box with a distinct name | 123 | | `directory` | Select a home for your box. If omitted, Hive uses the `defaultDirectory`. | 124 | | `encryptionKey` | Hand over this key, and Hive will encrypt your box. Keep it safe! | 125 | | `maxSizeMiB` | The maximum size of the box in MiB. Go for a modest number. | 126 | 127 | > Bee fact: Beeswax, which is secreted from the abdomen of worker bees, is used to construct the honeycomb. 128 | 129 | ### 🌂 Bidding Adieu: Closing Boxes 130 | 131 | It's not advised to close boxes that might be accessed again. This prevents unnecessary overhead of reopening the box and ensures smooth data retrieval. 132 | 133 | To close a box just call `box.close()`. Wipe the box from the face of the earth with `box.deleteFromDisk()`. 134 | 135 | > Bee fact: When a bee finds a good source of nectar, it flies back to the hive and shows its friends where the nectar source is by doing a dance. 136 | 137 | ### ✍️ Filling the Honeycomb: Inserting Data 138 | 139 | Once we have a box, it's time to fill it with sweet data! At its core, a box is just a key-value store. String keys are mapped to arbitrary primitive values. You can think of a box as a persisted `Map`. 140 | 141 | ```dart 142 | final box = Hive.box(); 143 | box.put('danceMoves', 'Waggle Dance'); 144 | box.put('wingSpeed', 200); 145 | ``` 146 | 147 | Updating values? If a particular key already exists, Hive simply updates its corresponding value. And complex types like lists and maps? They're in too! 148 | 149 | ```dart 150 | box.put('friends', ['Buzzy', 'Stinger', 'Honey']); 151 | box.put('memories', {'firstFlight': 'Sunny Day', 'bestNectar': 'Rose'}); 152 | ``` 153 | 154 | Instead of `.put()` you prefer the syntax of maps? Hive gets you: 155 | 156 | ```dart 157 | box['danceMoves'] = 'Round Dance'; 158 | box['wingSpeed'] = 220; 159 | ``` 160 | 161 | Got a bucket of honey facts? Drop them all at once with `box.putAll()`: 162 | 163 | ```dart 164 | box.putAll({'favoriteFlower': 'Lavender', 'wingSpeed': 210}); 165 | ``` 166 | 167 | > Bee fact: A single bee colony can produce anywhere from 30 to 100 pounds of honey in a year, depending on the availability of nectar sources. 168 | 169 | ### 👀 Extracting Honey... I mean, Data! 170 | 171 | Need a snippet of info from your Hive? No need to don the beekeeper suit; just scoop it out using `box.get()` or `box.getAll()`. If a key doesn't exist, `box.get()` simply return a `null`. But fret not; you can tell it to have a backup plan: 172 | 173 | ```dart 174 | final box = Hive.box(name: 'beeees'); 175 | final fav = box.get('favoriteFlower'); 176 | final moves = box.get('danceMoves', defaultValue: 'waggle'); 177 | ``` 178 | 179 | Oh, and if you're feeling fancy, use the `[]` operator for a more stylish approach: 180 | 181 | ```dart 182 | final fav = box['favoriteFlower']; 183 | final moves = box['danceMoves'] ?? 'waggle'; 184 | ``` 185 | 186 | > Bee fact: Worker bees are the only bees most people ever see flying around outside the hive. They're female, and their roles are to forage for food, build and protect the hive, and more. 187 | 188 | ### 🧹 Deleting Data 189 | 190 | Time for some spring cleaning in the hive! To remove a single entry from your box, use `box.delete()`: 191 | 192 | ```dart 193 | final deleted = box.delete('lavenderHoney'); 194 | print('Honey eaten: $deleted'); // Honey eaten: true 195 | ``` 196 | 197 | Perhaps it's time for a complete reset, making space for a fresh batch of honey. If you're looking to remove all key-value pairs from a box, use `box.clear()`: 198 | 199 | ```dart 200 | box.clear(); 201 | ``` 202 | 203 | > Bee fact: Bees have been around for more than 30 million years! Their long history predates the existence of humans and even dinosaurs. 204 | 205 | ### ✨ Using Boxes like Lists 206 | 207 | In the bee world, honeycombs aren't just random compartments; they're methodically organized. Similarly, while we've been viewing Hive boxes as maps so far, they can be used just like lists: 208 | 209 | ```dart 210 | final box = Hive.box(); 211 | 212 | box.add('Rose'); 213 | box.add('Tulip'); 214 | 215 | print(box.getAt(0)); // Rose 216 | print(box.getAt(1)); // Tulip 217 | ``` 218 | 219 | But remember, bees can't retrieve honey from a comb that's empty or doesn't exist. Likewise, index-based operations will throw an error if you try an index out of bounds: 220 | 221 | ```dart 222 | final box = Hive.box(); 223 | box.add('Daisy'); 224 | print(box.getAt(1)); // Error! This will make the bees buzz in confusion 225 | ``` 226 | 227 | Even if we insert a key-value pair we can still access the values by index. 228 | 229 | ```dart 230 | final box = Hive.box(); 231 | 232 | box.add('Lily'); 233 | box.put('key', 'Orchid'); 234 | 235 | print(box.getAt(0)); // Lily 236 | print(box.getAt(1)); // Orchid 237 | ``` 238 | 239 | Of course, we can also use the `[]` operator in combination with indexes : 240 | 241 | ```dart 242 | final box = Hive.box(); 243 | 244 | box.add('Marigold'); 245 | print(box[0]); // Marigold 246 | 247 | box[0] = 'Daffodil'; 248 | box[1] = 'Bluebell'; // Error! This will get the bees in a whirl 249 | ``` 250 | 251 | > Bee fact: To produce one pound of honey, a hive's bees must visit 2 million flowers and fly over 55,000 miles. 252 | 253 | ### 🛡️ Type safety 254 | 255 | Safety is the bee's priority! To keep your data sweet and pure boxes have an optional generic type parameter. It allows you to store only values of a specific type in a box: 256 | 257 | ```dart 258 | final box = Hive.box(name: 'BeeTreasures'); 259 | box.put('DaisyDance', 'SweetNectarShake'); 260 | box.put('RoseRumba', 'GoldenPollenParty'); 261 | box.put('TulipTango', 777); // Error - You can't fool the bees! 262 | ``` 263 | 264 | Make sure to use the same type whenever you get the box. Otherwise, you'll get an error: 265 | 266 | ```dart 267 | Hive.box(name: 'BeeTreasures'); // Error - We already have a String box! 268 | ``` 269 | 270 | > Bee fact: Bees have two stomachs. One is for eating, and the other is for storing nectar collected from flowers or water so they can carry it back to their hive. Talk about a sweet backpack! 271 | 272 | ### 🧩 Bee-yond the Basics: Non-primitive Objects 273 | 274 | Hive goes beyond storing just basic data types! Along with primitives, lists, and maps, Hive can store any Dart object of your liking. The only buzz you need to know? Your object should come equipped with a `.fromJson()` and `.toJson()` method: 275 | 276 | ```dart 277 | class Bee { 278 | Bee({required this.name, required this.role}); 279 | 280 | factory Bee.fromJson(Map json) => Bee( 281 | name: json['name'] as String, 282 | role: json['role'] as String, 283 | ); 284 | 285 | final String name; 286 | final String role; 287 | 288 | Map toJson() => { 289 | 'name': name, 290 | 'role': role, 291 | }; 292 | } 293 | ``` 294 | 295 | Before our bee-friends can buzz around in Hive, you need to do the beekeeper's job and register the `Bee` class: 296 | 297 | ```dart 298 | Hive.registerAdapter('Bee', Bee.fromJson); 299 | ``` 300 | 301 | Now, you're all set to let your bees fly: 302 | 303 | ```dart 304 | final box = Hive.box(); 305 | 306 | final bumble = Bee(name: 'Bumble', role: 'Worker'); 307 | box.put('BumbleID', bumble); 308 | 309 | print(box.get('BumbleID')); // Bumble - Worker 310 | ``` 311 | 312 | > Bee fact: Bees are responsible for pollinating about one-third of the world's food crops. 313 | 314 | ### 🪢 Transactions 315 | 316 | Transactions are an efficient way to update multiple values at once. They are also useful if you want to make sure that a Box is not changed by other code while you are working with it. 317 | 318 | ```dart 319 | final box = Hive.box(); 320 | 321 | box.write(() { 322 | box.store('nectar1', 'GoldenNectar'); 323 | box.store('nectar2', 'WildflowerBrew'); 324 | box.store('nectar3', 'CloverDew'); 325 | }); 326 | 327 | box.read(() { 328 | box.get('nectar1'); // GoldenNectar 329 | }); 330 | ``` 331 | 332 | Changes made in a transaction are always atomic. Either all changes are applied or none of them. So if an error occurs during a transaction, the box will not be changed. 333 | 334 | ```dart 335 | final box = Hive.box(); 336 | box.put('honeyLevel', 5); 337 | 338 | box.write(() { 339 | box.put('honeyLevel', 6); 340 | throw Exception('Oh no!!!'); 341 | }); 342 | 343 | print(box.get('honeyLevel')); // 5 344 | ``` 345 | 346 | > Bee fact: Bees can recognize human faces, and they can even be trained to associate a picture of a face with sweet treats! 347 | 348 | ### 💃 The Isolate Dance 349 | 350 | Just like a beehive where multiple bees work simultaneously, you can buzz into Hive from various Isolates at the same time. This nifty trick is great when you wish to keep those database activities separate from your UI thread. 351 | 352 | Hive comes with a sweet `Hive.compute()` method that runs a function in a different isolate. The best part? It also does the honey-making job of setting up and tidying resources for you. 353 | 354 | ```dart 355 | // Opening the bee's box 356 | final box = Hive.box(); 357 | 358 | // Storing some sweet nectar 359 | box.put('nectarType', 'wildflower'); 360 | 361 | await Hive.compute(() { 362 | // Accessing the same box from another worker bee 363 | final box = Hive.box(); 364 | print(box.get('nectarType')); // wildflower 365 | 366 | // Updating the nectar's quality 367 | box.put('nectarType', 'lavender'); 368 | }); 369 | 370 | // Tasting the updated honey flavor 371 | print(honeycomb.get('nectarType')); // lavender 372 | ``` 373 | 374 | Just remember, while the bees dance in harmony, ensure your Isolates do too! 🐝🎶 375 | 376 | > Bee fact: Bees have two pairs of wings, and they beat 11,400 times per minute. 377 | 378 | ### 🍯 Buzzworthy Questions 379 | 380 | #### 🐝 To bee or not to bee: Hive or Isar? 381 | 382 | > It's not always black and yellow! 🖤💛 Both Hive and Isar have their sweet spots. Hive is a lightweight wrapper around Isar so if you are looking for a simple key-value store, Hive might be enough. Isar is the way to go if you need queries, relations, and more advanced features. 383 | 384 | #### 🚀 Will using Hive make my app as fast as a bee? 385 | 386 | > While we can't promise your app will gain wings, 🦋 Hive sure will give it the speed it deserves. Hive is very resource efficient and optimized for mobile devices. Flutter like a butterfly, sting like a bee! 🐝 387 | 388 | #### 🗂 Where in the beehive does Hive hide my honey... I mean, data? 389 | 390 | > Remember the `defaultDirectory` we set at the beginning? 📍 That's where Hive stores your data in a file named `yourBoxName.isar` or `yourBoxName.sqlite`. 391 | 392 | #### 📸 I've got some bee-autiful images! Can I store them directly in Hive? 393 | 394 | > While you might be tempted to put those pics right into Hive, 🖼️ it's best to store your images and other binary data as files outside Hive. You can then store the file path in Hive. Think of it like leaving honey out in the open; it's better to keep it neatly stored in the appropriate place. 🏺 395 | 396 | #### 😲 Yikes! What if my app meets an untimely demise (gets killed)? What becomes of my Hive? 397 | 398 | > No need for a bee-mergency! 🚨 If your app buzzes off unexpectedly, Hive ensures that your data remains safe and sound. Transactions are atomic, so either all changes are applied or none of them. If an error occurs during a transaction, the box will not be changed. 399 | 400 | #### 🔐 How does Hive keep our data safe from sticky fingers? 401 | 402 | > We've got the queen's guard on duty! 🛡️ If you encrypt your box Hive uses 256-bit AES in CBC mode. Every database page is safeguarded separately, ensuring your sweet stuff remains secure and only accessible to those with the right key. Buzz-worthy protection, right? 🗝️ 403 | 404 | #### 🤝 When should I rally the troops and use transactions? 405 | 406 | > Just like a hive making big decisions together, 🌐 you'll want to use transactions when you have several operations that should be executed together. If one fails, they all fail. It ensures your data stays consistent, safe, and buzzing in harmony! 🎶 407 | 408 | #### 🤣 What if I'm allergic to bees? 409 | 410 | > No worries! Hive is 100% sting-free, 🚫 although we're pretty sure you'll get a buzz out of its performance. 411 | 412 | #### ⏳ Hive operations are synchronous. Doesn't that make the bee waltz a bit slow? 413 | 414 | > Hive is incredibly fast and efficient. 🚄 It's built on top of Isar, a high-performance database engine. If you want to keep database operations away from your UI isolate, you can use `compute()` or `Isolate.run()` to run them in a separate isolate. 415 | 416 | #### 📦 How many boxes should a wise beekeeper have? 417 | 418 | > While the sky's the limit in the world of bees, 🌌 in Hive, every box becomes a separate file. So, even if you're buzzing with excitement, it's wise not to overdo it. 📚 419 | 420 | ### 📜 License 421 | 422 | ``` 423 | Copyright 2023 Simon Choi 424 | 425 | Licensed under the Apache License, Version 2.0 (the "License"); 426 | you may not use this file except in compliance with the License. 427 | You may obtain a copy of the License at 428 | 429 | http://www.apache.org/licenses/LICENSE-2.0 430 | 431 | Unless required by applicable law or agreed to in writing, software 432 | distributed under the License is distributed on an "AS IS" BASIS, 433 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 434 | See the License for the specific language governing permissions and 435 | limitations under the License. 436 | ``` 437 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:very_good_analysis/analysis_options.yaml 2 | analyzer: 3 | exclude: 4 | - "**/*.g.dart" 5 | 6 | linter: 7 | rules: 8 | cascade_invocations: false 9 | use_string_in_part_of_directives: false 10 | always_put_required_named_parameters_first: false 11 | use_setters_to_change_properties: false 12 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | ## 🌼 Welcome, Beekeeper! 🐝 2 | 3 | Let's embark on a buzzworthy journey into the world of Flutter and Dart using Hive! Ready to see Hive in action? This example will walk you through setting up a Flutter project and implementing Hive to store data on a list of favorite flowers for bees. 4 | 5 | ## 🌺 Buzzy Beginnings 6 | 7 | Create a new Flutter app: 8 | 9 | ```bash 10 | flutter create bee_favorites 11 | cd bee_favorites 12 | ``` 13 | 14 | Now we can add some sweet dependencies to our `pubspec.yaml`: 15 | 16 | ```yaml 17 | dependencies: 18 | flutter: 19 | sdk: flutter 20 | hive: ^4.0.0 21 | isar_flutter_libs: ^4.0.0-dev.13 22 | path_provider: ^2.0.0 23 | ``` 24 | 25 | ## 🌻 Setting up Hive 26 | 27 | Before we get into the code, let's set up Hive: 28 | 29 | ```dart 30 | import 'package:flutter/material.dart'; 31 | import 'package:hive/hive.dart'; 32 | import 'package:path_provider/path_provider.dart'; 33 | 34 | void main() async { 35 | WidgetsFlutterBinding.ensureInitialized(); 36 | 37 | final directory = await getApplicationDocumentsDirectory(); 38 | Hive.defaultDirectory = directory.path; 39 | 40 | runApp(BeeApp()); 41 | } 42 | ``` 43 | 44 | ## 🌸 Bee Favorites App 45 | 46 | Let's build a simple Flutter app where bees can vote for their favorite flowers! 47 | 48 | ```dart 49 | class BeeApp extends StatelessWidget { 50 | @override 51 | Widget build(BuildContext context) { 52 | return MaterialApp( 53 | title: 'Bee Favorites', 54 | theme: ThemeData(primarySwatch: Colors.yellow), 55 | home: FavoriteFlowers(), 56 | ); 57 | } 58 | } 59 | 60 | class FavoriteFlowers extends StatefulWidget { 61 | @override 62 | _FavoriteFlowersState createState() => _FavoriteFlowersState(); 63 | } 64 | 65 | class _FavoriteFlowersState extends State { 66 | final Box favoriteBox = Hive.box('favorites'); 67 | 68 | final List flowers = ['Rose', 'Tulip', 'Daisy', 'Lily', 'Sunflower']; 69 | 70 | @override 71 | Widget build(BuildContext context) { 72 | return Scaffold( 73 | appBar: AppBar(title: Text('Bee Favorites 🐝')), 74 | body: ListView.builder( 75 | itemCount: flowers.length, 76 | itemBuilder: (context, index) { 77 | final flower = flowers[index]; 78 | return ListTile( 79 | title: Text(flower), 80 | trailing: IconButton( 81 | icon: Icon(Icons.star), 82 | onPressed: () { 83 | favoriteBox.add(flower); 84 | ScaffoldMessenger.of(context).showSnackBar( 85 | SnackBar(content: Text('$flower added to favorites! 🌼')), 86 | ); 87 | }, 88 | ), 89 | ); 90 | }, 91 | ), 92 | floatingActionButton: FloatingActionButton( 93 | child: Icon(Icons.view_list), 94 | onPressed: () { 95 | showDialog( 96 | context: context, 97 | builder: (context) => FavoritesDialog(favorites: favoriteBox.values.toList()), 98 | ); 99 | }, 100 | ), 101 | ); 102 | } 103 | } 104 | 105 | class FavoritesDialog extends StatelessWidget { 106 | final List favorites; 107 | 108 | FavoritesDialog({required this.favorites}); 109 | 110 | @override 111 | Widget build(BuildContext context) { 112 | return AlertDialog( 113 | title: Text('Bee Favorites 🌼'), 114 | content: Container( 115 | width: 300, 116 | height: 200, 117 | child: ListView.builder( 118 | itemCount: favorites.length, 119 | itemBuilder: (context, index) { 120 | return ListTile(title: Text(favorites[index])); 121 | }, 122 | ), 123 | ), 124 | actions: [ 125 | TextButton( 126 | child: Text('Close'), 127 | onPressed: () => Navigator.of(context).pop(), 128 | ), 129 | ], 130 | ); 131 | } 132 | } 133 | ``` 134 | 135 | ## 🐝 Bee-fore You Go... 136 | 137 | Once you've completed this tutorial, run your app! Every time a bee (or user) selects a flower, it's added to the favorites list, and you can view the favorites with the FloatingActionButton! 138 | 139 | > **Bee fact:** Bees communicate through a combination of chemical scents and movements. One known movement is the waggle dance, which indicates the location of a food source! 140 | 141 | Check out the full documentation in Hive's readme and the other example apps. 142 | -------------------------------------------------------------------------------- /lib/hive.dart: -------------------------------------------------------------------------------- 1 | /// Hive is a lightweight and blazing fast key-value store made for Flutter and 2 | /// Dart. It is strongly encrypted using AES-256. 3 | library hive; 4 | 5 | import 'dart:async'; 6 | import 'dart:isolate' 7 | if (dart.library.html) 'package:hive/src/impl/isolate_stub.dart'; 8 | 9 | import 'package:hive/src/impl/frame.dart'; 10 | import 'package:isar/isar.dart'; 11 | 12 | part 'src/impl/box_impl.dart'; 13 | part 'src/impl/type_registry.dart'; 14 | part 'src/box.dart'; 15 | part 'src/hive.dart'; 16 | -------------------------------------------------------------------------------- /lib/src/box.dart: -------------------------------------------------------------------------------- 1 | part of hive; 2 | 3 | /// A box contains and manages a collection of key-value pairs. 4 | @pragma('vm:isolate-unsendable') 5 | abstract interface class Box { 6 | /// Whether this box is currently open. 7 | /// 8 | /// Most of the operations on a box require it to be open. 9 | bool get isOpen; 10 | 11 | /// The name of the box. 12 | String get name; 13 | 14 | /// The location of the box in the file system. In the browser, this is null. 15 | String? get directory; 16 | 17 | /// The number of entries in the box. 18 | int get length; 19 | 20 | /// Whether the box is empty. 21 | bool get isEmpty; 22 | 23 | /// Whether the box is not empty. 24 | bool get isNotEmpty; 25 | 26 | /// Start a read transaction on the box. 27 | /// 28 | /// Transactions provides and atomic view on the box. All read operations 29 | /// inside the transaction will see the same state of the box. 30 | T read(T Function() callback); 31 | 32 | /// Start a write transaction on the box. 33 | /// 34 | /// Transactions provides and atomic view on the box. All read operations 35 | /// inside the transaction will see the same state of the box. 36 | T write(T Function() callback); 37 | 38 | /// All the keys in the box. 39 | /// 40 | /// The keys are sorted by their insertion order. 41 | List get keys; 42 | 43 | /// Get the n-th key in the box. 44 | String? keyAt(int index); 45 | 46 | /// Checks whether the box contains the [key]. 47 | bool containsKey(String key); 48 | 49 | // Returns the value associated with the given [key]. If the key does not 50 | /// exist, `null` is returned. 51 | /// 52 | /// If [defaultValue] is specified, it is returned in case the key does not 53 | /// exist. 54 | E? get(String key, {E? defaultValue}); 55 | 56 | /// Returns the value associated with the n-th key. 57 | E getAt(int index); 58 | 59 | /// Returns the value associated with the given [key]. The key can either be 60 | /// a [String] or an [int] to get an entry by its index. 61 | E? operator [](Object key); 62 | 63 | /// Returns all values associated with the given [keys] or `null` if a key 64 | /// does not exist. 65 | List getAll(Iterable keys); 66 | 67 | /// Returns all values in the given range. 68 | /// 69 | /// Throws a [RangeError] if [start] or [end] are out of bounds. 70 | List getRange(int start, int end); 71 | 72 | /// Returns all values between [startKey] and [endKey] (inclusive). 73 | List getBetween({String? startKey, String? endKey}); 74 | 75 | /// Saves the [key] - [value] pair. 76 | void put(String key, E value); 77 | 78 | /// Associates the [value] with the n-th key. An exception is raised if the 79 | /// key does not exist. 80 | void putAt(int index, E value); 81 | 82 | /// Saves the [key] - [value] pair. The key can either be a [String] or an 83 | /// [int] to save an entry by its index. 84 | void operator []=(Object key, E value); 85 | 86 | /// Saves all the key - value pairs in the [entries] map. 87 | void putAll(Map entries); 88 | 89 | /// Overwrites the values in the given range with the given [values]. 90 | void putRange(int start, int end, Iterable values); 91 | 92 | /// Saves the [value] with an auto-increment key. 93 | void add(E value); 94 | 95 | /// Saves all the [values] with auto-increment keys. 96 | void addAll(Iterable values); 97 | 98 | /// Deletes the given [key] from the box. 99 | /// 100 | /// If it does not exist, nothing happens. 101 | bool delete(String key); 102 | 103 | /// Deletes the n-th key from the box. 104 | /// 105 | /// If it does not exist, nothing happens. 106 | void deleteAt(int index); 107 | 108 | /// Deletes all the given [keys] from the box. 109 | /// 110 | /// If a key does not exist, it is skipped. 111 | int deleteAll(Iterable keys); 112 | 113 | /// Deletes all the entries in the given range. 114 | void deleteRange(int start, int end); 115 | 116 | /// Removes all entries from the box. 117 | void clear({bool notify = true}); 118 | 119 | /// Closes the box. 120 | /// 121 | /// Be careful, this closes all instances of this box. You have to make sure 122 | /// that you don't access the box anywhere else after that. 123 | void close(); 124 | 125 | /// Removes the file which contains the box and closes the box. 126 | /// 127 | /// If a box is still open in another isolate, it will not be deleted. 128 | void deleteFromDisk(); 129 | 130 | /// Watch for changes to the given [key]. 131 | Stream watchKey(String key); 132 | 133 | /// Returns a broadcast stream of all changes to the box. This should mainly 134 | /// be used to be notified of changes in background isolates. 135 | Stream watch(); 136 | } 137 | -------------------------------------------------------------------------------- /lib/src/hive.dart: -------------------------------------------------------------------------------- 1 | part of hive; 2 | 3 | /// Open boxes and register adapters. 4 | class Hive { 5 | static var _typeRegistry = _TypeRegistry(); 6 | static final _openBoxes = >{}; 7 | 8 | /// The default name if you don't specify a name for a box. 9 | static const defaultName = 'hive'; 10 | 11 | /// The default directory for all boxes. 12 | static String? defaultDirectory; 13 | 14 | /// Registers a type adapter to allow Hive to (de)serialize your objects. 15 | /// 16 | /// Example: 17 | /// ```dart 18 | /// class Person { 19 | /// String name; 20 | /// int age; 21 | /// 22 | /// factory Person.fromJson(Map json) { 23 | /// return Person() 24 | /// ..name = json['name'] as String 25 | /// ..age = json['age'] as int; 26 | /// } 27 | /// 28 | /// Map toJson() { 29 | /// return { 30 | /// 'name': name, 31 | /// 'age': age, 32 | /// }; 33 | /// } 34 | /// } 35 | /// 36 | /// Hive.registerAdapter('Person', Person.fromJson); 37 | /// ``` 38 | static void registerAdapter( 39 | String typeName, 40 | T? Function(dynamic json) fromJson, 41 | ) { 42 | _typeRegistry.register(Isar.fastHash(typeName), fromJson); 43 | } 44 | 45 | /// Get or open the box with [name] in the given [directory]. If no directory 46 | /// is specified, the default directory is used. 47 | /// 48 | /// If the box is already open, the same instance is returned. 49 | /// 50 | /// The [encryptionKey] is used to encrypt the box. If the box was already 51 | /// opened with a different encryption key, an error is thrown. 52 | /// 53 | /// The [maxSizeMiB] is the maximum size of the box in MiB. If the box grows 54 | /// bigger than this, an exception is thrown. It is recommended to set this 55 | /// value to a small value if possible. 56 | static Box box({ 57 | String name = defaultName, 58 | String? directory, 59 | String? encryptionKey, 60 | int maxSizeMiB = 5, 61 | }) { 62 | final box = _openBoxes[name]; 63 | if (box != null) { 64 | if (box is Box) { 65 | return box; 66 | } else { 67 | throw ArgumentError('Box was already opened with a different type. ' 68 | 'Expected Box<${box.runtimeType}> but got Box<$E>.'); 69 | } 70 | } 71 | 72 | final dir = directory ?? defaultDirectory; 73 | if (dir == null) { 74 | throw ArgumentError( 75 | 'No directory specified and no default directory set.', 76 | 'directory', 77 | ); 78 | } 79 | 80 | final isar = Isar.open( 81 | name: name, 82 | schemas: [FrameSchema], 83 | directory: dir, 84 | engine: encryptionKey != null ? IsarEngine.sqlite : IsarEngine.isar, 85 | maxSizeMiB: maxSizeMiB, 86 | encryptionKey: encryptionKey, 87 | inspector: false, 88 | ); 89 | final newBox = _BoxImpl(isar); 90 | _openBoxes[name] = newBox; 91 | return newBox; 92 | } 93 | 94 | /// Runs [computation] in a new isolate and returns the result. Also takes 95 | /// care of initializing Hive and closing all boxes afterwards. 96 | /// 97 | /// The optional [debugName] can be used to identify the isolate in debuggers. 98 | static Future compute( 99 | FutureOr Function() computation, { 100 | String? debugName, 101 | }) { 102 | final registry = _typeRegistry; 103 | final dir = defaultDirectory; 104 | return Isolate.run( 105 | () async { 106 | Hive._typeRegistry = registry; 107 | Hive.defaultDirectory = dir; 108 | try { 109 | return await computation(); 110 | } finally { 111 | Hive.closeAllBoxes(); 112 | } 113 | }, 114 | debugName: debugName ?? 'Hive Isolate', 115 | ); 116 | } 117 | 118 | /// Closes all open boxes. 119 | static void closeAllBoxes() { 120 | for (final box in _openBoxes.values) { 121 | box.close(); 122 | } 123 | } 124 | 125 | /// Closes all open boxes and delete their data. 126 | /// 127 | /// If a box is still open in another isolate, it will not be deleted. 128 | static void deleteAllBoxesFromDisk() { 129 | for (final box in _openBoxes.values) { 130 | box.deleteFromDisk(); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /lib/src/impl/box_impl.dart: -------------------------------------------------------------------------------- 1 | part of hive; 2 | 3 | class _BoxImpl implements Box { 4 | _BoxImpl(this.isar) : collection = isar.frames; 5 | 6 | final Isar isar; 7 | final IsarCollection collection; 8 | 9 | bool? writeTxn; 10 | 11 | @override 12 | bool get isOpen => isar.isOpen; 13 | 14 | @override 15 | String get name => isar.name; 16 | 17 | @override 18 | String get directory => isar.directory; 19 | 20 | @override 21 | int get length => collection.count(); 22 | 23 | @override 24 | bool get isEmpty => length == 0; 25 | 26 | @override 27 | bool get isNotEmpty => length != 0; 28 | 29 | @override 30 | T read(T Function() callback) { 31 | if (writeTxn == null) { 32 | return isar.read((isar) { 33 | writeTxn = false; 34 | try { 35 | return callback(); 36 | } finally { 37 | writeTxn = null; 38 | } 39 | }); 40 | } else { 41 | return callback(); 42 | } 43 | } 44 | 45 | @override 46 | T write(T Function() callback) { 47 | if (writeTxn == null) { 48 | return isar.write((isar) { 49 | writeTxn = true; 50 | try { 51 | return callback(); 52 | } finally { 53 | writeTxn = null; 54 | } 55 | }); 56 | } else if (writeTxn!) { 57 | return callback(); 58 | } else { 59 | throw StateError('Cannot write inside a read transaction.'); 60 | } 61 | } 62 | 63 | @override 64 | List get keys { 65 | return collection.where().keyIsNotNull().keyProperty().findAll().cast(); 66 | } 67 | 68 | @override 69 | String? keyAt(int index) { 70 | final frame = collection.where().findFirst(offset: index); 71 | 72 | if (frame == null) { 73 | throw IndexError.withLength(index, length); 74 | } 75 | 76 | return frame.key; 77 | } 78 | 79 | E _frameFromJson(Frame frame) { 80 | return Hive._typeRegistry.fromJson(frame.typeId, frame.value); 81 | } 82 | 83 | @override 84 | bool containsKey(String key) { 85 | return !collection.where().keyEqualTo(key).isEmpty(); 86 | } 87 | 88 | @override 89 | E? get(String key, {E? defaultValue}) { 90 | final frame = collection.where().keyEqualTo(key).findFirst(); 91 | return frame != null ? _frameFromJson(frame) : defaultValue; 92 | } 93 | 94 | @override 95 | E getAt(int index) { 96 | final frame = collection.where().findFirst(offset: index); 97 | 98 | if (frame == null) { 99 | throw IndexError.withLength(index, length); 100 | } 101 | 102 | return _frameFromJson(frame); 103 | } 104 | 105 | @override 106 | E? operator [](dynamic key) { 107 | if (key is int) { 108 | return getAt(key); 109 | } else if (key is String) { 110 | return get(key); 111 | } else { 112 | throw ArgumentError.value(key, 'key', 'must be a String or int'); 113 | } 114 | } 115 | 116 | @override 117 | List getAll(Iterable keys) { 118 | if (keys.isEmpty) return []; 119 | 120 | final frames = collection 121 | .where() 122 | // ignore: inference_failure_on_function_invocation 123 | .anyOf( 124 | keys, 125 | (q, key) => q.keyEqualTo(key), 126 | ) 127 | .findAll(); 128 | 129 | return frames.map(_frameFromJson).toList(); 130 | } 131 | 132 | @override 133 | List getRange(int start, int end) { 134 | if (start == 0 && end == 0) { 135 | return []; 136 | } 137 | 138 | final frames = collection 139 | .where() 140 | .findAll(offset: start, limit: end - start) 141 | .map(_frameFromJson) 142 | .toList(); 143 | 144 | if (frames.length != end - start) { 145 | RangeError.checkValidRange(start, end, length); 146 | } 147 | 148 | return frames; 149 | } 150 | 151 | @override 152 | List getBetween({String? startKey, String? endKey}) { 153 | final frames = collection 154 | .where() 155 | .optional( 156 | endKey != null, 157 | (q) => q.keyBetween(startKey ?? '', endKey), 158 | ) 159 | .optional( 160 | endKey == null, 161 | (q) => q.keyGreaterThanOrEqualTo(startKey ?? ''), 162 | ) 163 | .findAll() 164 | .map(_frameFromJson) 165 | .toList(); 166 | 167 | return frames; 168 | } 169 | 170 | @override 171 | void put(String key, E value) { 172 | write(() { 173 | final frame = Frame( 174 | id: collection.autoIncrement(), 175 | typeId: Hive._typeRegistry.findTypeId(value), 176 | key: key, 177 | value: value, 178 | ); 179 | collection.put(frame); 180 | }); 181 | } 182 | 183 | @override 184 | void putAt(int index, E value) { 185 | write(() { 186 | final idAtIndex = 187 | collection.where().idProperty().findFirst(offset: index); 188 | if (idAtIndex == null) { 189 | throw IndexError.withLength(index, length); 190 | } 191 | 192 | final frame = Frame( 193 | id: idAtIndex, 194 | typeId: Hive._typeRegistry.findTypeId(value), 195 | value: value, 196 | ); 197 | collection.put(frame); 198 | }); 199 | } 200 | 201 | @override 202 | void operator []=(Object key, E value) { 203 | if (key is int) { 204 | putAt(key, value); 205 | } else if (key is String) { 206 | put(key, value); 207 | } else { 208 | throw ArgumentError.value(key, 'key', 'must be a String or int'); 209 | } 210 | } 211 | 212 | @override 213 | void putAll(Map entries) { 214 | write(() { 215 | if (entries.isEmpty) return; 216 | 217 | final frames = []; 218 | for (final entry in entries.entries) { 219 | final frame = Frame( 220 | id: collection.autoIncrement(), 221 | typeId: Hive._typeRegistry.findTypeId(entry.value), 222 | key: entry.key, 223 | value: entry.value, 224 | ); 225 | frames.add(frame); 226 | } 227 | collection.putAll(frames); 228 | }); 229 | } 230 | 231 | @override 232 | void putRange(int start, int end, Iterable values) { 233 | write(() { 234 | if (start == 0 && end == 0) { 235 | return; 236 | } 237 | 238 | final idsInRange = collection 239 | .where() 240 | .idProperty() 241 | .findAll(offset: start, limit: end - start); 242 | 243 | if (idsInRange.length != end - start) { 244 | RangeError.checkValidRange(start, end, length); 245 | throw ArgumentError.value( 246 | values, 247 | 'values', 248 | 'must have the same length as the range', 249 | ); 250 | } 251 | 252 | final frames = []; 253 | for (final value in values) { 254 | final frame = Frame( 255 | id: idsInRange[frames.length], 256 | typeId: Hive._typeRegistry.findTypeId(value), 257 | value: value, 258 | ); 259 | frames.add(frame); 260 | } 261 | collection.putAll(frames); 262 | }); 263 | } 264 | 265 | @override 266 | void add(E value, {String? key}) { 267 | write(() { 268 | final frame = Frame( 269 | id: collection.autoIncrement(), 270 | typeId: Hive._typeRegistry.findTypeId(value), 271 | key: key, 272 | value: value, 273 | ); 274 | collection.put(frame); 275 | }); 276 | } 277 | 278 | @override 279 | void addAll(Iterable values) { 280 | write(() { 281 | final frames = []; 282 | for (final value in values) { 283 | final frame = Frame( 284 | id: collection.autoIncrement(), 285 | typeId: Hive._typeRegistry.findTypeId(value), 286 | value: value, 287 | ); 288 | frames.add(frame); 289 | } 290 | collection.putAll(frames); 291 | }); 292 | } 293 | 294 | @override 295 | bool delete(String key) { 296 | return write(() { 297 | return collection.where().keyEqualTo(key).deleteFirst(); 298 | }); 299 | } 300 | 301 | @override 302 | void deleteAt(int index) { 303 | return write(() { 304 | final deleted = collection.where().deleteFirst(offset: index); 305 | if (!deleted) { 306 | throw IndexError.withLength(index, length); 307 | } 308 | }); 309 | } 310 | 311 | @override 312 | int deleteAll(Iterable keys) { 313 | return write(() { 314 | if (keys.isEmpty) return 0; 315 | return collection 316 | .where() 317 | // ignore: inference_failure_on_function_invocation 318 | .anyOf(keys, (q, key) => q.keyEqualTo(key)) 319 | .deleteAll(); 320 | }); 321 | } 322 | 323 | @override 324 | void deleteRange(int start, int end) { 325 | return write(() { 326 | if (start == 0 && end == 0) { 327 | return; 328 | } 329 | 330 | final deleted = 331 | collection.where().deleteAll(offset: start, limit: end - start); 332 | 333 | if (deleted != end - start) { 334 | RangeError.checkValidRange(start, end, length); 335 | } 336 | }); 337 | } 338 | 339 | @override 340 | void clear({bool notify = true}) { 341 | isar.write((isar) { 342 | collection.clear(); 343 | }); 344 | } 345 | 346 | @override 347 | void close() { 348 | Hive._openBoxes.remove(name); 349 | isar.close(); 350 | } 351 | 352 | @override 353 | void deleteFromDisk() { 354 | Hive._openBoxes.remove(name); 355 | isar.close(deleteFromDisk: true); 356 | } 357 | 358 | @override 359 | Stream watchKey(String key) { 360 | return isar.frames.where().keyEqualTo(key).watch().map((frames) { 361 | final frame = frames.firstOrNull; 362 | if (frame == null) { 363 | return null; 364 | } else { 365 | return _frameFromJson(frame); 366 | } 367 | }); 368 | } 369 | 370 | @override 371 | Stream watch() { 372 | return isar.frames.watchLazy(); 373 | } 374 | } 375 | -------------------------------------------------------------------------------- /lib/src/impl/frame.dart: -------------------------------------------------------------------------------- 1 | import 'package:isar/isar.dart'; 2 | 3 | part 'frame.g.dart'; 4 | 5 | /// @nodoc 6 | @collection 7 | class Frame { 8 | /// @nodoc 9 | const Frame({ 10 | required this.id, 11 | required this.typeId, 12 | this.key, 13 | required this.value, 14 | }); 15 | 16 | /// @nodoc 17 | final int id; 18 | 19 | /// @nodoc 20 | final int? typeId; 21 | 22 | /// @nodoc 23 | @Index(unique: true, hash: true) 24 | final String? key; 25 | 26 | /// @nodoc 27 | final dynamic value; 28 | } 29 | -------------------------------------------------------------------------------- /lib/src/impl/frame.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'frame.dart'; 4 | 5 | // ************************************************************************** 6 | // _IsarCollectionGenerator 7 | // ************************************************************************** 8 | 9 | // coverage:ignore-file 10 | // ignore_for_file: duplicate_ignore, invalid_use_of_protected_member, lines_longer_than_80_chars, constant_identifier_names, avoid_js_rounded_ints, no_leading_underscores_for_local_identifiers, require_trailing_commas, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_in_if_null_operators, library_private_types_in_public_api, prefer_const_constructors 11 | // ignore_for_file: type=lint 12 | 13 | extension GetFrameCollection on Isar { 14 | IsarCollection get frames => this.collection(); 15 | } 16 | 17 | const FrameSchema = IsarGeneratedSchema( 18 | schema: IsarSchema( 19 | name: 'Frame', 20 | idName: 'id', 21 | embedded: false, 22 | properties: [ 23 | IsarPropertySchema( 24 | name: 'typeId', 25 | type: IsarType.long, 26 | ), 27 | IsarPropertySchema( 28 | name: 'key', 29 | type: IsarType.string, 30 | ), 31 | IsarPropertySchema( 32 | name: 'value', 33 | type: IsarType.json, 34 | ), 35 | ], 36 | indexes: [ 37 | IsarIndexSchema( 38 | name: 'key', 39 | properties: [ 40 | "key", 41 | ], 42 | unique: true, 43 | hash: true, 44 | ), 45 | ], 46 | ), 47 | converter: IsarObjectConverter( 48 | serialize: serializeFrame, 49 | deserialize: deserializeFrame, 50 | deserializeProperty: deserializeFrameProp, 51 | ), 52 | embeddedSchemas: [], 53 | ); 54 | 55 | @isarProtected 56 | int serializeFrame(IsarWriter writer, Frame object) { 57 | IsarCore.writeLong(writer, 1, object.typeId ?? -9223372036854775808); 58 | { 59 | final value = object.key; 60 | if (value == null) { 61 | IsarCore.writeNull(writer, 2); 62 | } else { 63 | IsarCore.writeString(writer, 2, value); 64 | } 65 | } 66 | IsarCore.writeString(writer, 3, isarJsonEncode(object.value)); 67 | return object.id; 68 | } 69 | 70 | @isarProtected 71 | Frame deserializeFrame(IsarReader reader) { 72 | final int _id; 73 | _id = IsarCore.readId(reader); 74 | final int? _typeId; 75 | { 76 | final value = IsarCore.readLong(reader, 1); 77 | if (value == -9223372036854775808) { 78 | _typeId = null; 79 | } else { 80 | _typeId = value; 81 | } 82 | } 83 | final String? _key; 84 | _key = IsarCore.readString(reader, 2); 85 | final dynamic _value; 86 | _value = isarJsonDecode(IsarCore.readString(reader, 3) ?? 'null') ?? null; 87 | final object = Frame( 88 | id: _id, 89 | typeId: _typeId, 90 | key: _key, 91 | value: _value, 92 | ); 93 | return object; 94 | } 95 | 96 | @isarProtected 97 | dynamic deserializeFrameProp(IsarReader reader, int property) { 98 | switch (property) { 99 | case 0: 100 | return IsarCore.readId(reader); 101 | case 1: 102 | { 103 | final value = IsarCore.readLong(reader, 1); 104 | if (value == -9223372036854775808) { 105 | return null; 106 | } else { 107 | return value; 108 | } 109 | } 110 | case 2: 111 | return IsarCore.readString(reader, 2); 112 | case 3: 113 | return isarJsonDecode(IsarCore.readString(reader, 3) ?? 'null') ?? null; 114 | default: 115 | throw ArgumentError('Unknown property: $property'); 116 | } 117 | } 118 | 119 | sealed class _FrameUpdate { 120 | bool call({ 121 | required int id, 122 | int? typeId, 123 | String? key, 124 | }); 125 | } 126 | 127 | class _FrameUpdateImpl implements _FrameUpdate { 128 | const _FrameUpdateImpl(this.collection); 129 | 130 | final IsarCollection collection; 131 | 132 | @override 133 | bool call({ 134 | required int id, 135 | Object? typeId = ignore, 136 | Object? key = ignore, 137 | }) { 138 | return collection.updateProperties([ 139 | id 140 | ], { 141 | if (typeId != ignore) 1: typeId as int?, 142 | if (key != ignore) 2: key as String?, 143 | }) > 144 | 0; 145 | } 146 | } 147 | 148 | sealed class _FrameUpdateAll { 149 | int call({ 150 | required List id, 151 | int? typeId, 152 | String? key, 153 | }); 154 | } 155 | 156 | class _FrameUpdateAllImpl implements _FrameUpdateAll { 157 | const _FrameUpdateAllImpl(this.collection); 158 | 159 | final IsarCollection collection; 160 | 161 | @override 162 | int call({ 163 | required List id, 164 | Object? typeId = ignore, 165 | Object? key = ignore, 166 | }) { 167 | return collection.updateProperties(id, { 168 | if (typeId != ignore) 1: typeId as int?, 169 | if (key != ignore) 2: key as String?, 170 | }); 171 | } 172 | } 173 | 174 | extension FrameUpdate on IsarCollection { 175 | _FrameUpdate get update => _FrameUpdateImpl(this); 176 | 177 | _FrameUpdateAll get updateAll => _FrameUpdateAllImpl(this); 178 | } 179 | 180 | sealed class _FrameQueryUpdate { 181 | int call({ 182 | int? typeId, 183 | String? key, 184 | }); 185 | } 186 | 187 | class _FrameQueryUpdateImpl implements _FrameQueryUpdate { 188 | const _FrameQueryUpdateImpl(this.query, {this.limit}); 189 | 190 | final IsarQuery query; 191 | final int? limit; 192 | 193 | @override 194 | int call({ 195 | Object? typeId = ignore, 196 | Object? key = ignore, 197 | }) { 198 | return query.updateProperties(limit: limit, { 199 | if (typeId != ignore) 1: typeId as int?, 200 | if (key != ignore) 2: key as String?, 201 | }); 202 | } 203 | } 204 | 205 | extension FrameQueryUpdate on IsarQuery { 206 | _FrameQueryUpdate get updateFirst => _FrameQueryUpdateImpl(this, limit: 1); 207 | 208 | _FrameQueryUpdate get updateAll => _FrameQueryUpdateImpl(this); 209 | } 210 | 211 | class _FrameQueryBuilderUpdateImpl implements _FrameQueryUpdate { 212 | const _FrameQueryBuilderUpdateImpl(this.query, {this.limit}); 213 | 214 | final QueryBuilder query; 215 | final int? limit; 216 | 217 | @override 218 | int call({ 219 | Object? typeId = ignore, 220 | Object? key = ignore, 221 | }) { 222 | final q = query.build(); 223 | try { 224 | return q.updateProperties(limit: limit, { 225 | if (typeId != ignore) 1: typeId as int?, 226 | if (key != ignore) 2: key as String?, 227 | }); 228 | } finally { 229 | q.close(); 230 | } 231 | } 232 | } 233 | 234 | extension FrameQueryBuilderUpdate on QueryBuilder { 235 | _FrameQueryUpdate get updateFirst => 236 | _FrameQueryBuilderUpdateImpl(this, limit: 1); 237 | 238 | _FrameQueryUpdate get updateAll => _FrameQueryBuilderUpdateImpl(this); 239 | } 240 | 241 | extension FrameQueryFilter on QueryBuilder { 242 | QueryBuilder idEqualTo( 243 | int value, 244 | ) { 245 | return QueryBuilder.apply(this, (query) { 246 | return query.addFilterCondition( 247 | EqualCondition( 248 | property: 0, 249 | value: value, 250 | ), 251 | ); 252 | }); 253 | } 254 | 255 | QueryBuilder idGreaterThan( 256 | int value, 257 | ) { 258 | return QueryBuilder.apply(this, (query) { 259 | return query.addFilterCondition( 260 | GreaterCondition( 261 | property: 0, 262 | value: value, 263 | ), 264 | ); 265 | }); 266 | } 267 | 268 | QueryBuilder idGreaterThanOrEqualTo( 269 | int value, 270 | ) { 271 | return QueryBuilder.apply(this, (query) { 272 | return query.addFilterCondition( 273 | GreaterOrEqualCondition( 274 | property: 0, 275 | value: value, 276 | ), 277 | ); 278 | }); 279 | } 280 | 281 | QueryBuilder idLessThan( 282 | int value, 283 | ) { 284 | return QueryBuilder.apply(this, (query) { 285 | return query.addFilterCondition( 286 | LessCondition( 287 | property: 0, 288 | value: value, 289 | ), 290 | ); 291 | }); 292 | } 293 | 294 | QueryBuilder idLessThanOrEqualTo( 295 | int value, 296 | ) { 297 | return QueryBuilder.apply(this, (query) { 298 | return query.addFilterCondition( 299 | LessOrEqualCondition( 300 | property: 0, 301 | value: value, 302 | ), 303 | ); 304 | }); 305 | } 306 | 307 | QueryBuilder idBetween( 308 | int lower, 309 | int upper, 310 | ) { 311 | return QueryBuilder.apply(this, (query) { 312 | return query.addFilterCondition( 313 | BetweenCondition( 314 | property: 0, 315 | lower: lower, 316 | upper: upper, 317 | ), 318 | ); 319 | }); 320 | } 321 | 322 | QueryBuilder typeIdIsNull() { 323 | return QueryBuilder.apply(this, (query) { 324 | return query.addFilterCondition(const IsNullCondition(property: 1)); 325 | }); 326 | } 327 | 328 | QueryBuilder typeIdIsNotNull() { 329 | return QueryBuilder.apply(not(), (query) { 330 | return query.addFilterCondition(const IsNullCondition(property: 1)); 331 | }); 332 | } 333 | 334 | QueryBuilder typeIdEqualTo( 335 | int? value, 336 | ) { 337 | return QueryBuilder.apply(this, (query) { 338 | return query.addFilterCondition( 339 | EqualCondition( 340 | property: 1, 341 | value: value, 342 | ), 343 | ); 344 | }); 345 | } 346 | 347 | QueryBuilder typeIdGreaterThan( 348 | int? value, 349 | ) { 350 | return QueryBuilder.apply(this, (query) { 351 | return query.addFilterCondition( 352 | GreaterCondition( 353 | property: 1, 354 | value: value, 355 | ), 356 | ); 357 | }); 358 | } 359 | 360 | QueryBuilder typeIdGreaterThanOrEqualTo( 361 | int? value, 362 | ) { 363 | return QueryBuilder.apply(this, (query) { 364 | return query.addFilterCondition( 365 | GreaterOrEqualCondition( 366 | property: 1, 367 | value: value, 368 | ), 369 | ); 370 | }); 371 | } 372 | 373 | QueryBuilder typeIdLessThan( 374 | int? value, 375 | ) { 376 | return QueryBuilder.apply(this, (query) { 377 | return query.addFilterCondition( 378 | LessCondition( 379 | property: 1, 380 | value: value, 381 | ), 382 | ); 383 | }); 384 | } 385 | 386 | QueryBuilder typeIdLessThanOrEqualTo( 387 | int? value, 388 | ) { 389 | return QueryBuilder.apply(this, (query) { 390 | return query.addFilterCondition( 391 | LessOrEqualCondition( 392 | property: 1, 393 | value: value, 394 | ), 395 | ); 396 | }); 397 | } 398 | 399 | QueryBuilder typeIdBetween( 400 | int? lower, 401 | int? upper, 402 | ) { 403 | return QueryBuilder.apply(this, (query) { 404 | return query.addFilterCondition( 405 | BetweenCondition( 406 | property: 1, 407 | lower: lower, 408 | upper: upper, 409 | ), 410 | ); 411 | }); 412 | } 413 | 414 | QueryBuilder keyIsNull() { 415 | return QueryBuilder.apply(this, (query) { 416 | return query.addFilterCondition(const IsNullCondition(property: 2)); 417 | }); 418 | } 419 | 420 | QueryBuilder keyIsNotNull() { 421 | return QueryBuilder.apply(not(), (query) { 422 | return query.addFilterCondition(const IsNullCondition(property: 2)); 423 | }); 424 | } 425 | 426 | QueryBuilder keyEqualTo( 427 | String? value, { 428 | bool caseSensitive = true, 429 | }) { 430 | return QueryBuilder.apply(this, (query) { 431 | return query.addFilterCondition( 432 | EqualCondition( 433 | property: 2, 434 | value: value, 435 | caseSensitive: caseSensitive, 436 | ), 437 | ); 438 | }); 439 | } 440 | 441 | QueryBuilder keyGreaterThan( 442 | String? value, { 443 | bool caseSensitive = true, 444 | }) { 445 | return QueryBuilder.apply(this, (query) { 446 | return query.addFilterCondition( 447 | GreaterCondition( 448 | property: 2, 449 | value: value, 450 | caseSensitive: caseSensitive, 451 | ), 452 | ); 453 | }); 454 | } 455 | 456 | QueryBuilder keyGreaterThanOrEqualTo( 457 | String? value, { 458 | bool caseSensitive = true, 459 | }) { 460 | return QueryBuilder.apply(this, (query) { 461 | return query.addFilterCondition( 462 | GreaterOrEqualCondition( 463 | property: 2, 464 | value: value, 465 | caseSensitive: caseSensitive, 466 | ), 467 | ); 468 | }); 469 | } 470 | 471 | QueryBuilder keyLessThan( 472 | String? value, { 473 | bool caseSensitive = true, 474 | }) { 475 | return QueryBuilder.apply(this, (query) { 476 | return query.addFilterCondition( 477 | LessCondition( 478 | property: 2, 479 | value: value, 480 | caseSensitive: caseSensitive, 481 | ), 482 | ); 483 | }); 484 | } 485 | 486 | QueryBuilder keyLessThanOrEqualTo( 487 | String? value, { 488 | bool caseSensitive = true, 489 | }) { 490 | return QueryBuilder.apply(this, (query) { 491 | return query.addFilterCondition( 492 | LessOrEqualCondition( 493 | property: 2, 494 | value: value, 495 | caseSensitive: caseSensitive, 496 | ), 497 | ); 498 | }); 499 | } 500 | 501 | QueryBuilder keyBetween( 502 | String? lower, 503 | String? upper, { 504 | bool caseSensitive = true, 505 | }) { 506 | return QueryBuilder.apply(this, (query) { 507 | return query.addFilterCondition( 508 | BetweenCondition( 509 | property: 2, 510 | lower: lower, 511 | upper: upper, 512 | caseSensitive: caseSensitive, 513 | ), 514 | ); 515 | }); 516 | } 517 | 518 | QueryBuilder keyStartsWith( 519 | String value, { 520 | bool caseSensitive = true, 521 | }) { 522 | return QueryBuilder.apply(this, (query) { 523 | return query.addFilterCondition( 524 | StartsWithCondition( 525 | property: 2, 526 | value: value, 527 | caseSensitive: caseSensitive, 528 | ), 529 | ); 530 | }); 531 | } 532 | 533 | QueryBuilder keyEndsWith( 534 | String value, { 535 | bool caseSensitive = true, 536 | }) { 537 | return QueryBuilder.apply(this, (query) { 538 | return query.addFilterCondition( 539 | EndsWithCondition( 540 | property: 2, 541 | value: value, 542 | caseSensitive: caseSensitive, 543 | ), 544 | ); 545 | }); 546 | } 547 | 548 | QueryBuilder keyContains(String value, 549 | {bool caseSensitive = true}) { 550 | return QueryBuilder.apply(this, (query) { 551 | return query.addFilterCondition( 552 | ContainsCondition( 553 | property: 2, 554 | value: value, 555 | caseSensitive: caseSensitive, 556 | ), 557 | ); 558 | }); 559 | } 560 | 561 | QueryBuilder keyMatches(String pattern, 562 | {bool caseSensitive = true}) { 563 | return QueryBuilder.apply(this, (query) { 564 | return query.addFilterCondition( 565 | MatchesCondition( 566 | property: 2, 567 | wildcard: pattern, 568 | caseSensitive: caseSensitive, 569 | ), 570 | ); 571 | }); 572 | } 573 | 574 | QueryBuilder keyIsEmpty() { 575 | return QueryBuilder.apply(this, (query) { 576 | return query.addFilterCondition( 577 | const EqualCondition( 578 | property: 2, 579 | value: '', 580 | ), 581 | ); 582 | }); 583 | } 584 | 585 | QueryBuilder keyIsNotEmpty() { 586 | return QueryBuilder.apply(this, (query) { 587 | return query.addFilterCondition( 588 | const GreaterCondition( 589 | property: 2, 590 | value: '', 591 | ), 592 | ); 593 | }); 594 | } 595 | } 596 | 597 | extension FrameQueryObject on QueryBuilder {} 598 | 599 | extension FrameQuerySortBy on QueryBuilder { 600 | QueryBuilder sortById() { 601 | return QueryBuilder.apply(this, (query) { 602 | return query.addSortBy(0); 603 | }); 604 | } 605 | 606 | QueryBuilder sortByIdDesc() { 607 | return QueryBuilder.apply(this, (query) { 608 | return query.addSortBy(0, sort: Sort.desc); 609 | }); 610 | } 611 | 612 | QueryBuilder sortByTypeId() { 613 | return QueryBuilder.apply(this, (query) { 614 | return query.addSortBy(1); 615 | }); 616 | } 617 | 618 | QueryBuilder sortByTypeIdDesc() { 619 | return QueryBuilder.apply(this, (query) { 620 | return query.addSortBy(1, sort: Sort.desc); 621 | }); 622 | } 623 | 624 | QueryBuilder sortByKey( 625 | {bool caseSensitive = true}) { 626 | return QueryBuilder.apply(this, (query) { 627 | return query.addSortBy( 628 | 2, 629 | caseSensitive: caseSensitive, 630 | ); 631 | }); 632 | } 633 | 634 | QueryBuilder sortByKeyDesc( 635 | {bool caseSensitive = true}) { 636 | return QueryBuilder.apply(this, (query) { 637 | return query.addSortBy( 638 | 2, 639 | sort: Sort.desc, 640 | caseSensitive: caseSensitive, 641 | ); 642 | }); 643 | } 644 | 645 | QueryBuilder sortByValue() { 646 | return QueryBuilder.apply(this, (query) { 647 | return query.addSortBy(3); 648 | }); 649 | } 650 | 651 | QueryBuilder sortByValueDesc() { 652 | return QueryBuilder.apply(this, (query) { 653 | return query.addSortBy(3, sort: Sort.desc); 654 | }); 655 | } 656 | } 657 | 658 | extension FrameQuerySortThenBy on QueryBuilder { 659 | QueryBuilder thenById() { 660 | return QueryBuilder.apply(this, (query) { 661 | return query.addSortBy(0); 662 | }); 663 | } 664 | 665 | QueryBuilder thenByIdDesc() { 666 | return QueryBuilder.apply(this, (query) { 667 | return query.addSortBy(0, sort: Sort.desc); 668 | }); 669 | } 670 | 671 | QueryBuilder thenByTypeId() { 672 | return QueryBuilder.apply(this, (query) { 673 | return query.addSortBy(1); 674 | }); 675 | } 676 | 677 | QueryBuilder thenByTypeIdDesc() { 678 | return QueryBuilder.apply(this, (query) { 679 | return query.addSortBy(1, sort: Sort.desc); 680 | }); 681 | } 682 | 683 | QueryBuilder thenByKey( 684 | {bool caseSensitive = true}) { 685 | return QueryBuilder.apply(this, (query) { 686 | return query.addSortBy(2, caseSensitive: caseSensitive); 687 | }); 688 | } 689 | 690 | QueryBuilder thenByKeyDesc( 691 | {bool caseSensitive = true}) { 692 | return QueryBuilder.apply(this, (query) { 693 | return query.addSortBy(2, sort: Sort.desc, caseSensitive: caseSensitive); 694 | }); 695 | } 696 | 697 | QueryBuilder thenByValue() { 698 | return QueryBuilder.apply(this, (query) { 699 | return query.addSortBy(3); 700 | }); 701 | } 702 | 703 | QueryBuilder thenByValueDesc() { 704 | return QueryBuilder.apply(this, (query) { 705 | return query.addSortBy(3, sort: Sort.desc); 706 | }); 707 | } 708 | } 709 | 710 | extension FrameQueryWhereDistinct on QueryBuilder { 711 | QueryBuilder distinctByTypeId() { 712 | return QueryBuilder.apply(this, (query) { 713 | return query.addDistinctBy(1); 714 | }); 715 | } 716 | 717 | QueryBuilder distinctByKey( 718 | {bool caseSensitive = true}) { 719 | return QueryBuilder.apply(this, (query) { 720 | return query.addDistinctBy(2, caseSensitive: caseSensitive); 721 | }); 722 | } 723 | 724 | QueryBuilder distinctByValue() { 725 | return QueryBuilder.apply(this, (query) { 726 | return query.addDistinctBy(3); 727 | }); 728 | } 729 | } 730 | 731 | extension FrameQueryProperty1 on QueryBuilder { 732 | QueryBuilder idProperty() { 733 | return QueryBuilder.apply(this, (query) { 734 | return query.addProperty(0); 735 | }); 736 | } 737 | 738 | QueryBuilder typeIdProperty() { 739 | return QueryBuilder.apply(this, (query) { 740 | return query.addProperty(1); 741 | }); 742 | } 743 | 744 | QueryBuilder keyProperty() { 745 | return QueryBuilder.apply(this, (query) { 746 | return query.addProperty(2); 747 | }); 748 | } 749 | 750 | QueryBuilder valueProperty() { 751 | return QueryBuilder.apply(this, (query) { 752 | return query.addProperty(3); 753 | }); 754 | } 755 | } 756 | 757 | extension FrameQueryProperty2 on QueryBuilder { 758 | QueryBuilder idProperty() { 759 | return QueryBuilder.apply(this, (query) { 760 | return query.addProperty(0); 761 | }); 762 | } 763 | 764 | QueryBuilder typeIdProperty() { 765 | return QueryBuilder.apply(this, (query) { 766 | return query.addProperty(1); 767 | }); 768 | } 769 | 770 | QueryBuilder keyProperty() { 771 | return QueryBuilder.apply(this, (query) { 772 | return query.addProperty(2); 773 | }); 774 | } 775 | 776 | QueryBuilder valueProperty() { 777 | return QueryBuilder.apply(this, (query) { 778 | return query.addProperty(3); 779 | }); 780 | } 781 | } 782 | 783 | extension FrameQueryProperty3 784 | on QueryBuilder { 785 | QueryBuilder idProperty() { 786 | return QueryBuilder.apply(this, (query) { 787 | return query.addProperty(0); 788 | }); 789 | } 790 | 791 | QueryBuilder typeIdProperty() { 792 | return QueryBuilder.apply(this, (query) { 793 | return query.addProperty(1); 794 | }); 795 | } 796 | 797 | QueryBuilder keyProperty() { 798 | return QueryBuilder.apply(this, (query) { 799 | return query.addProperty(2); 800 | }); 801 | } 802 | 803 | QueryBuilder valueProperty() { 804 | return QueryBuilder.apply(this, (query) { 805 | return query.addProperty(3); 806 | }); 807 | } 808 | } 809 | -------------------------------------------------------------------------------- /lib/src/impl/isolate_stub.dart: -------------------------------------------------------------------------------- 1 | import 'dart:async'; 2 | 3 | /// @nodoc 4 | class Isolate { 5 | /// @nodoc 6 | static Future run( 7 | FutureOr Function() computation, { 8 | String? debugName, 9 | }) { 10 | throw UnimplementedError( 11 | 'Isolate.run is not implemented on this platform.', 12 | ); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /lib/src/impl/type_registry.dart: -------------------------------------------------------------------------------- 1 | part of hive; 2 | 3 | const _builtinTypes = { 4 | bool: _TypeHandler.builtin(), 5 | num: _TypeHandler.builtin(), 6 | String: _TypeHandler.builtin(), 7 | List: _TypeHandler>.builtin(), 8 | Map: _TypeHandler>.builtin(), 9 | }; 10 | 11 | class _TypeRegistry { 12 | final Map> _registry = {}; 13 | final Map> _reverseRegistry = {..._builtinTypes}; 14 | 15 | void register(int typeId, T? Function(dynamic json) fromJson) { 16 | if (T == dynamic) { 17 | throw ArgumentError('Cannot register dynamic type.'); 18 | } 19 | 20 | final handler = _TypeHandler(typeId, fromJson); 21 | _registry[typeId] = handler; 22 | _reverseRegistry[T] = handler; 23 | } 24 | 25 | T fromJson(int? typeId, dynamic json) { 26 | dynamic value = json; 27 | if (typeId != null) { 28 | final handler = _registry[typeId]; 29 | if (handler == null) { 30 | throw StateError( 31 | 'Type is not registered. Did you forget to register it?', 32 | ); 33 | } 34 | if (json is Map) { 35 | value = handler.fromJson(json); 36 | } else { 37 | throw ArgumentError('Type mismatch. Expected Map ' 38 | 'but got ${json.runtimeType}.'); 39 | } 40 | } 41 | 42 | if (value is T) { 43 | return value; 44 | } else { 45 | throw ArgumentError( 46 | 'Type mismatch. Expected $T but got ${value.runtimeType}.', 47 | ); 48 | } 49 | } 50 | 51 | int? findTypeId(dynamic value) { 52 | final handler = _reverseRegistry[value.runtimeType]; 53 | if (handler != null) { 54 | return handler.typeId; 55 | } 56 | 57 | for (final MapEntry(key: type, value: handler) 58 | in _reverseRegistry.entries) { 59 | if (handler.handlesValue(value)) { 60 | _reverseRegistry[type] = handler; 61 | return handler.typeId; 62 | } 63 | } 64 | 65 | return null; 66 | } 67 | 68 | void reset() { 69 | _registry.clear(); 70 | _reverseRegistry.clear(); 71 | _reverseRegistry.addAll(_builtinTypes); 72 | } 73 | } 74 | 75 | T? _noop(Map json) { 76 | throw UnimplementedError(); 77 | } 78 | 79 | class _TypeHandler { 80 | const _TypeHandler(this.typeId, this.fromJson); 81 | 82 | const _TypeHandler.builtin() 83 | : typeId = null, 84 | fromJson = _noop; 85 | 86 | final int? typeId; 87 | 88 | final T? Function(Map json) fromJson; 89 | 90 | bool handlesValue(dynamic value) { 91 | return value is T; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: hive 2 | description: Lightweight and buzzing-fast key-value database made for Flutter and Dart. 3 | version: 4.0.0-dev.2 4 | repository: https://github.com/isar/hive 5 | homepage: https://github.com/isar/hive 6 | issue_tracker: https://github.com/isar/hive/issues 7 | funding: 8 | - https://github.com/sponsors/simc/ 9 | topics: 10 | - database 11 | - hive 12 | - nosql 13 | - encryption 14 | - storage 15 | 16 | environment: 17 | sdk: ">=3.1.0 <4.0.0" 18 | 19 | dependencies: 20 | isar: ^4.0.0-dev.13 21 | meta: ^1.9.0 22 | 23 | dev_dependencies: 24 | build_runner: ^2.4.6 25 | test: ^1.23.0 26 | very_good_analysis: ^5.0.0 27 | -------------------------------------------------------------------------------- /test/box_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:test/test.dart'; 4 | 5 | import 'common.dart'; 6 | 7 | void main() { 8 | group('Box', () { 9 | test('.isOpen', () async { 10 | final box = await openTestBox(); 11 | expect(box.isOpen, true); 12 | box.deleteFromDisk(); 13 | expect(box.isOpen, false); 14 | }); 15 | 16 | test('.name', () async { 17 | final box = await openTestBox(name: 'testBox'); 18 | expect(box.name, 'testBox'); 19 | }); 20 | 21 | test('.directory', () async { 22 | final box = await openTestBox(); 23 | expect(box.directory, Directory.systemTemp.path); 24 | }); 25 | 26 | test('.length', () async { 27 | final box = await openTestBox(); 28 | expect(box.length, 0); 29 | box.put('key1', 'hello'); 30 | expect(box.length, 1); 31 | box.put('key2', 'world'); 32 | expect(box.length, 2); 33 | box.delete('key1'); 34 | expect(box.length, 1); 35 | box.delete('key2'); 36 | expect(box.length, 0); 37 | }); 38 | 39 | group('.keys', () { 40 | test('empty', () async { 41 | final box = await openTestBox(); 42 | expect(box.keys, isEmpty); 43 | }); 44 | 45 | test('contains all String only keys', () async { 46 | final box = await openTestBox(); 47 | box.put('key1', 'hello'); 48 | box.put('key2', 'world'); 49 | box.put('key1', 'hello2'); 50 | expect(box.keys, ['key2', 'key1']); 51 | }); 52 | 53 | test('contains no int keys', () async { 54 | final box = await openTestBox(); 55 | box.add('hello'); 56 | box.add('world'); 57 | box.add('hello2'); 58 | expect(box.keys, isEmpty); 59 | }); 60 | 61 | test('contains only String keys if there are both', () async { 62 | final box = await openTestBox(); 63 | box.put('key2', 'hello'); 64 | box.add('world'); 65 | box.put('key2', 'hello2'); 66 | expect(box.keys, ['key2']); 67 | }); 68 | }); 69 | 70 | group('.keyAt()', () { 71 | test('throws IndexError for non-existing index', () async { 72 | final box = await openTestBox(); 73 | expect(() => box.keyAt(0), throwsA(isA())); 74 | }); 75 | 76 | test('returns null if key is not set', () async { 77 | final box = await openTestBox(); 78 | box.put('key2', 'hello'); 79 | box.add('world'); 80 | expect(box.keyAt(1), null); 81 | }); 82 | 83 | test('returns key', () async { 84 | final box = await openTestBox(); 85 | box.put('key2', 'hello'); 86 | box.put('key1', 'world'); 87 | box.put('key2', 'hello2'); 88 | expect(box.keyAt(0), 'key1'); 89 | expect(box.keyAt(1), 'key2'); 90 | }); 91 | }); 92 | 93 | test('.containsKey()', () async { 94 | final box = await openTestBox(); 95 | expect(box.containsKey('key1'), false); 96 | box.put('key1', 'hello'); 97 | expect(box.containsKey('key1'), true); 98 | }); 99 | 100 | group('.get()', () { 101 | test('non-existing key returns null', () async { 102 | final box = await openTestBox(); 103 | expect(box.get('key1'), null); 104 | box.put('key1', true); 105 | expect(box.get('key2'), null); 106 | }); 107 | 108 | test('non-existing key returns default value', () async { 109 | final box = await openTestBox(); 110 | expect(box.get('key1', defaultValue: 'hello'), 'hello'); 111 | box.put('key1', true); 112 | expect(box.get('key2', defaultValue: 'hello'), 'hello'); 113 | }); 114 | 115 | test('returns value', () async { 116 | final box = await openTestBox(); 117 | box.put('key1', 'hello'); 118 | expect(box.get('key1'), 'hello'); 119 | }); 120 | }); 121 | 122 | group('.getAt()', () { 123 | test('throws IndexError for non-existing index', () async { 124 | final box = await openTestBox(); 125 | expect(() => box.getAt(0), throwsA(isA())); 126 | }); 127 | 128 | test('returns value', () async { 129 | final box = await openTestBox(); 130 | box.put('key1', 'hello'); 131 | box.put('key2', 'world'); 132 | box.put('key3', '!'); 133 | expect(box.getAt(0), 'hello'); 134 | expect(box.getAt(1), 'world'); 135 | 136 | box.putAt(1, 'world2'); 137 | expect(box.getAt(1), 'world2'); 138 | }); 139 | }); 140 | 141 | group('operator []', () { 142 | test('throws ArgumentError for non-int and non-String key', () async { 143 | final box = await openTestBox(); 144 | expect(() => box[true], throwsArgumentError); 145 | }); 146 | 147 | test('returns null for non-existing key', () async { 148 | final box = await openTestBox(); 149 | expect(box['key1'], null); 150 | box.put('key1', true); 151 | expect(box['key2'], null); 152 | }); 153 | 154 | test('throws IndexError for non-existing index', () async { 155 | final box = await openTestBox(); 156 | expect(() => box[0], throwsA(isA())); 157 | }); 158 | 159 | test('returns value', () async { 160 | final box = await openTestBox(); 161 | box.put('key1', 'hello'); 162 | expect(box['key1'], 'hello'); 163 | expect(box[0], 'hello'); 164 | }); 165 | }); 166 | 167 | group('.getAll()', () { 168 | test('returns empty list for empty keys', () async { 169 | final box = await openTestBox(); 170 | expect(box.getAll([]), isEmpty); 171 | }); 172 | 173 | test('returns empty list for non-existing keys', () async { 174 | final box = await openTestBox(); 175 | box.put('key1', 'hello'); 176 | box.put('key2', 'world'); 177 | expect(box.getAll(['key3', 'key4']), isEmpty); 178 | }); 179 | 180 | test('returns values', () async { 181 | final box = await openTestBox(); 182 | box.put('key1', 'hello'); 183 | box.put('key2', 'world'); 184 | box.put('key3', '!'); 185 | expect(box.getAll(['key1', 'key3']), ['hello', '!']); 186 | }); 187 | }); 188 | 189 | group('.getRange()', () { 190 | test('throws RangeError for invalid range', () async { 191 | final box = await openTestBox(); 192 | expect(() => box.getRange(-1, 1), throwsRangeError); 193 | expect(() => box.getRange(0, -1), throwsRangeError); 194 | expect(() => box.getRange(1, 0), throwsRangeError); 195 | expect(() => box.getRange(0, 1), throwsRangeError); 196 | }); 197 | 198 | test('returns empty list for empty range', () async { 199 | final box = await openTestBox(); 200 | box.add('hello'); 201 | expect(box.getRange(0, 0), isEmpty); 202 | }); 203 | 204 | test('returns values', () async { 205 | final box = await openTestBox(); 206 | box.put('key1', 'hello'); 207 | box.put('key2', 'world'); 208 | box.put('key3', '!'); 209 | expect(box.getRange(0, 2), ['hello', 'world']); 210 | }); 211 | }); 212 | 213 | group('.getBetween()', () { 214 | test('returns all values if start end end key are null', () async { 215 | final box = await openTestBox(); 216 | box.add('hello'); 217 | box.put('key', 'value'); 218 | expect(box.getBetween(), ['value']); 219 | }); 220 | 221 | test('returns empty list if start key is greater than end key', () async { 222 | final box = await openTestBox(); 223 | box.put('a', 'value1'); 224 | box.put('b', 'value2'); 225 | expect(box.getBetween(startKey: 'b', endKey: 'a'), isEmpty); 226 | }); 227 | 228 | test('returns values', () async { 229 | final box = await openTestBox(); 230 | box.put('key1', 'hello'); 231 | box.put('key2', 'world'); 232 | box.put('key3', '!'); 233 | expect(box.getBetween(), ['hello', 'world', '!']); 234 | expect(box.getBetween(startKey: 'key2'), ['world', '!']); 235 | expect(box.getBetween(endKey: 'key2'), ['hello', 'world']); 236 | expect(box.getBetween(startKey: 'key2', endKey: 'key2'), ['world']); 237 | }); 238 | }); 239 | 240 | group('.put()', () { 241 | test('overrides existing entry if it exists', () async { 242 | final box = await openTestBox(); 243 | box.put('key1', 'hello'); 244 | box.put('key2', 'world'); 245 | box.put('key3', '!'); 246 | box.put('key2', 'world2'); 247 | expect(box.getAt(2), 'world2'); 248 | expect(box.keys, ['key1', 'key3', 'key2']); 249 | }); 250 | 251 | test('adds new entry if it does not exist', () async { 252 | final box = await openTestBox(); 253 | box.put('key1', 'hello'); 254 | box.put('key2', 'world'); 255 | box.put('key3', '!'); 256 | box.put('key4', 'world2'); 257 | expect(box.getAt(3), 'world2'); 258 | expect(box.keys, ['key1', 'key2', 'key3', 'key4']); 259 | }); 260 | }); 261 | 262 | group('.putAt()', () { 263 | test('throws IndexError for non-existing index', () async { 264 | final box = await openTestBox(); 265 | expect(() => box.putAt(0, 'hello'), throwsA(isA())); 266 | }); 267 | 268 | test('overrides existing entry', () async { 269 | final box = await openTestBox(); 270 | box.put('key1', 'hello'); 271 | box.put('key2', 'world'); 272 | box.put('key3', '!'); 273 | box.putAt(1, 'world2'); 274 | expect(box.getAt(1), 'world2'); 275 | expect(box.keys, ['key1', 'key3']); 276 | }); 277 | }); 278 | 279 | group('operator []=', () { 280 | test('throws ArgumentError for non-int and non-String key', () async { 281 | final box = await openTestBox(); 282 | expect(() => box[true] = 'hello', throwsArgumentError); 283 | }); 284 | 285 | test('overrides existing entry if String key exists', () async { 286 | final box = await openTestBox(); 287 | box['key1'] = 'hello'; 288 | box['key2'] = 'world'; 289 | box['key3'] = '!'; 290 | box['key2'] = 'world2'; 291 | expect(box.getAt(2), 'world2'); 292 | expect(box.keys, ['key1', 'key3', 'key2']); 293 | }); 294 | 295 | test('adds new entry if String key does not exist', () async { 296 | final box = await openTestBox(); 297 | box['key1'] = 'hello'; 298 | box['key2'] = 'world'; 299 | box['key3'] = '!'; 300 | box['key4'] = 'world2'; 301 | expect(box.getAt(3), 'world2'); 302 | expect(box.keys, ['key1', 'key2', 'key3', 'key4']); 303 | }); 304 | 305 | test('throws IndexError for non-existing index', () async { 306 | final box = await openTestBox(); 307 | expect(() => box[0] = 'hello', throwsA(isA())); 308 | }); 309 | 310 | test('overrides existing entry if int key exists', () async { 311 | final box = await openTestBox(); 312 | box.add('hello'); 313 | box.add('world'); 314 | box.add('!'); 315 | box[1] = 'world2'; 316 | expect(box.getAt(1), 'world2'); 317 | expect(box.keys, isEmpty); 318 | }); 319 | }); 320 | 321 | test('.putAll()', () async { 322 | final box = await openTestBox(); 323 | box.putAll({'key1': 'hello', 'key2': 'world'}); 324 | expect(box.getAt(0), 'hello'); 325 | expect(box.getAt(1), 'world'); 326 | expect(box.keys, ['key1', 'key2']); 327 | 328 | box.putAll({'key3': '!', 'key1': 'hello2'}); 329 | expect(box.keys, ['key2', 'key3', 'key1']); 330 | expect(box.getAt(0), 'world'); 331 | expect(box.getAt(1), '!'); 332 | expect(box.getAt(2), 'hello2'); 333 | }); 334 | 335 | group('.putRange()', () { 336 | test('throws RangeError for invalid range', () async { 337 | final box = await openTestBox(); 338 | expect(() => box.putRange(-1, 1, ['hello']), throwsRangeError); 339 | expect(() => box.putRange(0, -1, ['hello']), throwsRangeError); 340 | expect(() => box.putRange(1, 0, ['hello']), throwsRangeError); 341 | expect(() => box.putRange(0, 1, ['hello']), throwsRangeError); 342 | }); 343 | 344 | test('does nothing for empty range', () async { 345 | final box = await openTestBox(); 346 | box.putRange(0, 0, ['hello']); 347 | expect(box.keys, isEmpty); 348 | }); 349 | 350 | test('overrides existing entries', () async { 351 | final box = await openTestBox(); 352 | box.putAll({ 353 | 'key1': 'value1', 354 | 'key2': 'value2', 355 | 'key3': 'value3', 356 | 'key4': 'value4', 357 | }); 358 | box.putRange(1, 3, ['newValue2', 'newValue3']); 359 | expect(box.getAt(0), 'value1'); 360 | expect(box.getAt(1), 'newValue2'); 361 | expect(box.getAt(2), 'newValue3'); 362 | expect(box.getAt(3), 'value4'); 363 | expect(box.keys, ['key1', 'key4']); 364 | }); 365 | }); 366 | 367 | test('.add()', () async { 368 | final box = await openTestBox(); 369 | box.add('hello'); 370 | box.add('world'); 371 | box.add('!'); 372 | expect(box.getAt(0), 'hello'); 373 | expect(box.getAt(1), 'world'); 374 | expect(box.getAt(2), '!'); 375 | expect(box.keys, isEmpty); 376 | }); 377 | 378 | test('.addAll()', () async { 379 | final box = await openTestBox(); 380 | box.addAll(['hello', 'world']); 381 | expect(box.getAt(0), 'hello'); 382 | expect(box.getAt(1), 'world'); 383 | expect(box.keys, isEmpty); 384 | 385 | box.addAll(['!', 'hello2']); 386 | expect(box.getAt(0), 'hello'); 387 | expect(box.getAt(1), 'world'); 388 | expect(box.getAt(2), '!'); 389 | expect(box.getAt(3), 'hello2'); 390 | expect(box.keys, isEmpty); 391 | }); 392 | 393 | group('.delete()', () { 394 | test('returns false for non-existing key', () async { 395 | final box = await openTestBox(); 396 | box.put('key2', true); 397 | box.add(false); 398 | expect(box.delete('key1'), false); 399 | expect(box.length, 2); 400 | }); 401 | 402 | test('returns true for existing key', () async { 403 | final box = await openTestBox(); 404 | box.put('key1', 'hello'); 405 | box.put('key2', true); 406 | box.add(false); 407 | expect(box.delete('key1'), true); 408 | expect(box.length, 2); 409 | }); 410 | }); 411 | 412 | group('.deleteAt()', () { 413 | test('throws IndexError for non-existing index', () async { 414 | final box = await openTestBox(); 415 | expect(() => box.deleteAt(0), throwsA(isA())); 416 | }); 417 | 418 | test('deletes entry', () async { 419 | final box = await openTestBox(); 420 | box.put('key1', 'hello'); 421 | box.put('key2', true); 422 | box.add(false); 423 | box.deleteAt(1); 424 | expect(box.length, 2); 425 | expect(box.keys, ['key1']); 426 | }); 427 | }); 428 | 429 | group('.deleteAll()', () { 430 | test('returns 0 for empty keys', () async { 431 | final box = await openTestBox(); 432 | box.put('key1', 'hello'); 433 | box.put('key2', true); 434 | box.add(false); 435 | expect(box.deleteAll([]), 0); 436 | expect(box.length, 3); 437 | }); 438 | 439 | test('returns 0 for non-existing keys', () async { 440 | final box = await openTestBox(); 441 | box.put('key1', 'hello'); 442 | box.put('key2', true); 443 | box.add(false); 444 | expect(box.deleteAll(['key3', 'key4']), 0); 445 | expect(box.length, 3); 446 | }); 447 | 448 | test('returns number of deleted entries', () async { 449 | final box = await openTestBox(); 450 | box.put('key1', 'hello'); 451 | box.put('key2', true); 452 | box.add(false); 453 | expect(box.deleteAll(['key1', 'key3', 'key2']), 2); 454 | expect(box.length, 1); 455 | expect(box.keys, isEmpty); 456 | }); 457 | }); 458 | 459 | group('.deleteRange()', () { 460 | test('throws RangeError for invalid range', () async { 461 | final box = await openTestBox(); 462 | expect(() => box.deleteRange(-1, 1), throwsRangeError); 463 | expect(() => box.deleteRange(0, -1), throwsRangeError); 464 | expect(() => box.deleteRange(1, 0), throwsRangeError); 465 | expect(() => box.deleteRange(0, 1), throwsRangeError); 466 | }); 467 | 468 | test('does nothing for empty range', () async { 469 | final box = await openTestBox(); 470 | box.add('hello'); 471 | box.deleteRange(0, 0); 472 | expect(box.length, 1); 473 | }); 474 | 475 | test('deletes entries', () async { 476 | final box = await openTestBox(); 477 | box.putAll({ 478 | 'key1': 'value1', 479 | 'key2': 'value2', 480 | 'key3': 'value3', 481 | 'key4': 'value4', 482 | }); 483 | box.deleteRange(1, 3); 484 | expect(box.length, 2); 485 | expect(box.keys, ['key1', 'key4']); 486 | }); 487 | }); 488 | }); 489 | } 490 | -------------------------------------------------------------------------------- /test/common.dart: -------------------------------------------------------------------------------- 1 | import 'dart:ffi'; 2 | import 'dart:io'; 3 | import 'dart:math'; 4 | 5 | import 'package:hive/hive.dart'; 6 | import 'package:hive/src/impl/frame.dart'; 7 | import 'package:isar/isar.dart'; 8 | import 'package:test/test.dart'; 9 | 10 | const _releases = 'https://github.com/isar/isar/releases/download/'; 11 | 12 | Future initTests() async { 13 | final lib = switch (Abi.current()) { 14 | Abi.macosArm64 || Abi.macosX64 => 'libisar_macos.dylib', 15 | Abi.linuxX64 => 'libisar_linux_x64.so', 16 | Abi.windowsX64 => 'isar_windows_x64.dll', 17 | _ => throw UnsupportedError('Unsupported test platform'), 18 | }; 19 | 20 | final libPath = Directory.current.path + Platform.pathSeparator + lib; 21 | final file = File(libPath); 22 | if (!file.existsSync()) { 23 | final uri = Uri.parse('$_releases/${Isar.version}/$lib'); 24 | final request = await HttpClient().getUrl(uri); 25 | final response = await request.close(); 26 | await response.pipe(file.openWrite()); 27 | } 28 | 29 | Isar.initialize(file.path); 30 | Hive.defaultDirectory = Directory.systemTemp.path; 31 | } 32 | 33 | Future> openTestBox({String? name}) async { 34 | await initTests(); 35 | name ??= Random().nextInt(999999).toString(); 36 | final box = Hive.box(name: name); 37 | box.verify(); 38 | addTearDown(() async { 39 | if (box.isOpen) { 40 | box.verify(); 41 | box.deleteFromDisk(); 42 | } 43 | }); 44 | 45 | return box; 46 | } 47 | 48 | extension BoxVerify on Box { 49 | void verify() { 50 | final isar = Isar.get(schemas: [FrameSchema], name: name); 51 | final keys = 52 | isar.frames.where().keyProperty().findAll().whereType(); 53 | expect(keys.length, keys.toSet().length); 54 | } 55 | } 56 | --------------------------------------------------------------------------------