Moor is an easy to use, reactive, typesafe persistence library for Dart & Flutter

Overview

Moor

Build Status codecov Chat on Gitter

Proudly Sponsored by Stream 💙


Try the Flutter Chat Tutorial   💬

Core Flutter Generator
Generator version Flutter version Generator version

Moor is a reactive persistence library for Flutter and Dart, built ontop of sqlite. Moor is

  • Flexible: Moor let's you write queries in both SQL and Dart, providing fluent apis for both languages. You can filter and order results or use joins to run queries on multiple tables. You can even use complex sql features like WITH and WINDOW clauses.
  • 🔥 Feature rich: Moor has builtin support for transactions, schema migrations, complex filters and expressions, batched updates and joins. We even have a builtin IDE for SQL!
  • 📦 Modular: Thanks to builtin support for daos and imports in sql files, moor helps you keep your database code simple.
  • 🛡️ Safe: Moor generates typesafe code based on your tables and queries. If you make a mistake in your queries, moor will find it at compile time and provide helpful and descriptive lints.
  • Fast: Even though moor lets you write powerful queries, it can keep up with the performance of key-value stores like shared preferences and Hive. Moor is the only major persistence library with builtin threading support, allowing you to run database code across isolates with zero additional effort.
  • Reactive: Turn any sql query into an auto-updating stream! This includes complex queries across many tables
  • ⚙️ Cross-Platform support: Moor works on Android, iOS, macOS, Windows, Linux and the web. This template is a Flutter todo app that works on all platforms
  • 🗡️ Battle tested and production ready: Moor is stable and well tested with a wide range of unit and integration tests. It powers production Flutter apps.

With moor, persistence on Flutter is fun!

To start using moor, read our detailed docs.

If you have any questions, feedback or ideas, feel free to create an issue. If you enjoy this project, I'd appreciate your 🌟 on GitHub.


Packages in this repo:

  • moor: The main runtime for moor, which provides most apis
  • moor_ffi: New and faster executor for moor, built with dart:ffi.
  • moor_flutter: The standard executor wrapping the sqflite package
  • moor_generator: The compiler for moor tables, databases and daos. It also contains a fully-featured sql ide
  • sqlparser: A sql parser and static analyzer, written in pure Dart. This package can be used without moor to perform analysis on sql statements. It's on pub at sqlparser
Comments
  • Force quiting our app throws `file is not a database` error at startup of the app

    Force quiting our app throws `file is not a database` error at startup of the app

    We are using an encrypted database but I found that when using a long encryption key it is possible to find other combinations that will decrypt the database.

    Db key = 3d80ac84-6dff-40bb-b803-abeed6c5e297

    3d80ac84-6dff-40bb-b803-abeed6c5e297 + test -> :white_check_mark: test + 3d80ac84-6dff-40bb-b803-abeed6c5e297 + test -> :x: test + 3d80ac84-6dff-40bb-b803-abeed6c5e297 -> :x: 3d80ac84-6dff-4 -> :x: 3d80ac84-6dff-40 -> :white_check_mark:

    It seems that the max lenght for the encryption pragma key is 16. Other chars will be ignored. If this is intended behaviour this should be documented somewhere

    opened by vanlooverenkoen 55
  • Error: Unhandled Exception: Invalid argument(s): Failed to load dynamic library (dlopen failed: library

    Error: Unhandled Exception: Invalid argument(s): Failed to load dynamic library (dlopen failed: library "libsqlite3.so" not found)

    Edited by @simolus3 for visibility: If you encounter this problem, please check that you're using moor_ffi version 0.6.0 or later. There's a Flutter bug causing builds to not include native libraries: https://github.com/flutter/flutter/issues/55827#issuecomment-623779910. Please follow the workaround described in the linked comment.


    First, thank you very much for this wonderful project!

    I've get a problem. After upgrading Flutter and run my Flutter with moor based project, I've get the following error:

    E/flutter (21278): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Invalid argument(s): Failed to load dynamic library (dlopen failed: library "libsqlite3.so" not found)
    E/flutter (21278): #0      _open (dart:ffi-patch/ffi_dynamic_library_patch.dart:13:55)
    E/flutter (21278): #1      new DynamicLibrary.open (dart:ffi-patch/ffi_dynamic_library_patch.dart:22:12)
    E/flutter (21278): #2      _defaultOpen (package:moor_ffi/src/load_library.dart:24:27)
    E/flutter (21278): #3      OpenDynamicLibrary.openSqlite (package:moor_ffi/src/load_library.dart:78:12)
    E/flutter (21278): #4      new _SQLiteBindings (package:moor_ffi/src/bindings/bindings.dart:97:19)
    E/flutter (21278): #5      bindings (package:moor_ffi/src/bindings/bindings.dart:197:53)
    E/flutter (21278): #6      new Database.open (package:moor_ffi/src/impl/database.dart:40:9)
    E/flutter (21278): #7      new Database.openFile (package:moor_ffi/src/impl/database.dart:29:52)
    E/flutter (21278): #8      _VmDelegate.open (package:moor_ffi/src/vm_database.dart:39:22)
    E/flutter (21278): #9      DelegatedDatabase.ensureOpen.<anonymous closure> (package:moor/src/runtime/executor/helpers/engines.dart:246:22)
    E/flutter (21278): <asynchronous suspension>
    E/flutter (21278): #10     DelegatedDatabase.ensureOpen.<anonymous closure> (package:moor/src/runtime/executor/helpers/engines.dart)
    E/flutter (21278): #11     BasicLock.synchronized (package:synchronized/src/basic_lock.dart:32:26)
    E/flutter (21278): #12     DelegatedDatabase.ensureOpen (package:moor/src/runtime/executor/helpers/engines.dart:238:25)
    E/flutter (21278): #13     LazyDatabase.ensureOpen.<anonymous closure> (package:moor/src/utils/lazy_database.dart:50:49)
    E/flutter (21278): #14     _rootRunUnary (dart:async/zone.dart:1134:38)
    E/flutter (21278): #15     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
    E/flutter (21278): #16     _FutureListener.handleValue (dart:async/future_impl.dart:140:18)
    E/flutter (21278): #17     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
    E/flutter (21278): #18     Future._propagateToListeners (dart:async/future_impl.dart:711:32)
    E/flutter (21278): #19     Future._completeWithValue (dart:async/future_impl.dart:526:5)
    E/flutter (21278): #20     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:556:7)
    E/flutter (21278): #21     _rootRun (dart:async/zone.dart:1126:13)
    E/flutter (21278): #22     _CustomZone.run (dart:async/zone.dart:1023:19)
    E/flutter (21278): #23     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
    E/flutter (21278): #24     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
    E/flutter (21278): #25     _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
    E/flutter (21278): #26     _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
    E/flutter (21278): 
    

    I'm using the following moor dependencies:

      moor: ^2.4.1
      moor_ffi: ^0.4.0
    

    Here my flutter doctor result:

    Doctor summary (to see all details, run flutter doctor -v):
    [✓] Flutter (Channel master, v1.15.4-pre.235, on Linux, locale en_US.UTF-8)
     
    [✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    [✓] Linux toolchain - develop for Linux desktop
    [!] Android Studio (version 3.5)
        ✗ Flutter plugin not installed; this adds Flutter specific functionality.
        ✗ Dart plugin not installed; this adds Dart specific functionality.
    [✓] IntelliJ IDEA Community Edition (version 2019.3)
    [✓] Connected device (2 available)
    
    ! Doctor found issues in 1 category.
    

    Is this related to flutter version? If yes, what is the correct flutter version to temporarily fixing the problem?

    Thank you.

    opened by joielechong 54
  • Custom row classes

    Custom row classes

    This tracks enhancements to the custom row classes feature in moor 4.3. Custom row classes let users specify an existing class that moor will use as a data class:

    @UseRowClass(MyRowClass)
    class MyTable extends Table {
      IntColumn get id => integer().autoIncrement()();
    }
    
    class MyRowClass {
      final int id;
    
      MyRowClass(this.id);
    }
    

    Goals

    • [x] Basic support for custom row classes
    • [x] Proper type checking
    • [x] Support custom row classes for tables declared in moor files
    • [x] Support named constructors
    • [x] Aid in generating toColumns if desired (not urgent, we can delegate that method to the generated companion)
    • [x] Support something similar for generated queries?
    enhancement 
    opened by simolus3 36
  • Select based on month

    Select based on month

    I have this column in database

    TextColumn get createdAt => text().named('created_at').nullable()();

    where the created_at is this format "2019-07-22T11:42:01.000+08:00".

    I would like to write a select query, to retrieve data where month is July and year is 2019.

    Future<List<ABC>> getData() {
        return (select(abcs)..where(...)   // where the month of created_at is October and Year is 2019
              ..orderBy([
                (t) =>
                    OrderingTerm(expression: t.createdAt, mode: OrderingMode.desc)
              ]))
            .get();
      }
    

    How should I write?

    question 
    opened by tony123S 32
  • InconsistentAnalysisException

    InconsistentAnalysisException

    Running: flutter packages pub run build_runner build Lately, I get this error:

    [WARNING] No actions completed for 15.1s, waiting on:
      - moor_generator:moor_generator on test/widget_test.dart
      - moor_generator:moor_generator on lib/choose_icon.dart
      - moor_generator:moor_generator on lib/db_classes.dart
      .. and 11 more
    
    moor_generator:moor_generator on lib/db_classes.dart:
    Error running DaoGenerator
    InconsistentAnalysisException: Requested result might be inconsistent with previously returned results
    

    I tried the commands flutter clean and then -> Packages get and -> Packages update

    But the error persists

    bug generator 
    opened by apoleo88 31
  • UTC is returned in local time

    UTC is returned in local time

    First of all, thanks for this amazing package and the hard work you put into it!

    I noticed that DateTime objects in UTC are returned in local time. Storing the date in Iso8601 format instead of MillisecondsSinceEpoch should solve this.

    opened by Ufuk94 31
  • PostgreSQL support

    PostgreSQL support

    PostgresSQL experimental support

    All tests pass! (except migration) 🎉

    Missing features: - Migrations, versioning (in progress)

    Modifications: - SQL type names changed for Postgres (SQLite compatible)

    opened by westito 29
  • moor_ffi isn't working on devices with armeabi-v7a on release mode

    moor_ffi isn't working on devices with armeabi-v7a on release mode

    Edit by @simolus3: I've opened https://github.com/flutter/flutter/issues/54948 as it seems like this is a problem in Flutter or Dart. If you're affected by this, please consider upvoting that issue.

    The underlying issue has since been fixed, but the fix hasn't landed on the stable channel yet. Please try to switch to another channel (and run flutter clean).


    I was working normally with moor_ffi until I tried to launch a release mode of my app. When I launched some test users were reporting that the database wasn't accepting new entries. I've tried everything until I switched the version from moor_ffi 0.4.0 to moor_flutter 2.1.1.

    My flutter version is Flutter version 1.15.23-pre.11. But I was on stable and was facing the same issue.

    Sadly I cannot log the error because I don't have any devices with this architecture (armeabi-v7a) and on emulators the problem wasn't showing.

    But I think that these are the steps to reproduce:

    1. Build an app in release mode splitting the apk by abi with flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi

    2. Install the app-armeabi-v7a-release.apk in a phone with the armeabi-v7a architecture.

    3. Try to insert some data on moor database.

    Sorry for the lack of details about the error. I can explain more about how I was facing the issue if necessary, but I couldn't reproduce here with my devices and I don't have an easy access to the testers.

    opened by scostagabriel 29
  • Running Moor in an isolate

    Running Moor in an isolate

    I'm wondering if it's possible to use moor in an isolate. I'd like to fetch data from my server in the background, and then sync it with the database locally.

    Would this be possible?

    enhancement 
    opened by cadaniel 26
  • Query does not complete if the database is created outside WidgetTester.runAsync

    Query does not complete if the database is created outside WidgetTester.runAsync

    Sorry Simon, I've got another one! These tests pass with moor 3.4.0 and flutter 1.20.4, but tests 3 and 4 do not complete with moor 4.3.2 and flutter 2.2.1. I know in general you're supposed to mock or avoid async in widget tests, so this may be a case of "that should have never worked", but it'd at least be good to understand what's going on here.

    import 'dart:async';
    
    import 'package:flutter_test/flutter_test.dart';
    import 'package:moor/ffi.dart';
    import 'package:moor/moor.dart';
    
    class TestDb extends GeneratedDatabase {
      TestDb() : super(SqlTypeSystem.withDefaults(), VmDatabase.memory());
      @override
      final List<TableInfo> allTables = const [];
      @override
      final int schemaVersion = 1;
    }
    
    Future<int> selectOne(TestDb _db) => _db
        .customSelect('select 1 a')
        .map((row) => row.read<int>('a'))
        .getSingle();
    
    void main() {
      moorRuntimeOptions.dontWarnAboutMultipleDatabases = true;
    
      testWidgets('1', (tester) async {
        final db = TestDb();
        expect(await selectOne(db), 1); // completes
      });
    
      testWidgets('2', (tester) async {
        await tester.runAsync(() async {
          final db = TestDb();
          expect(await selectOne(db), 1); // completes
        });
      });
    
      testWidgets('3', (tester) async {
        final db = TestDb();
        await tester.runAsync(() async {
          expect(await selectOne(db), 1);  // does not complete
        });
      });
    
      testWidgets('4', (tester) async {
        final db = await tester.runAsync(() async {
          return TestDb();
        });
        expect(await selectOne(db), 1); // does not complete
      });
    }
    
    
    opened by Mike278 25
  • Support for null safety

    Support for null safety

    Hi, and thanks for the plugin!

    I'm having trouble using the null-safe version of sqflite as Moor is still dependent on the previous iteration of the said plugin.

    Trying to use sqflite 2.0.0-nullsafety.2 produces:

    $ flutter pub get
    Running "flutter pub get" in example_app...
    
    Because example_app depends on moor_flutter 3.1.0 which depends on sqflite ^1.1.6+5, sqflite ^1.1.6+5 is required.
    So, because example_app depends on sqflite 2.0.0-nullsafety.2, version solving failed.
    pub get failed (1; So, because example_app depends on sqflite 2.0.0-nullsafety.2, version solving failed.)
    Process finished with exit code 1
    

    Any plans to migrate to a null-safe Dart?

    PS: null safety will be the default beyond 2020.

    opened by noordawod 25
  • Why is the sqlite_sequence data queried empty?

    Why is the sqlite_sequence data queried empty?

    Why is the sqlite_sequence data queried empty?

    final result = await db.customSelect("select * from sqlite_sequence").get();
    print(result); // []
    
    opened by ddxl123 0
  • Support CAST for special dart types and MAPPED BY in queries

    Support CAST for special dart types and MAPPED BY in queries

    It would be nice to support CAST for special dart types (e.g. ENUMNAME, BOOLEAN, DATETIME) and MAPPED BY in queries.

    SELECT
      table.*,
      '{}' MAPPED BY `const JsonTypeConverter()` AS value,
      CAST('new' AS ENUMNAME(State)) AS state
    FROM table
    WHERE something
    

    (Not the best example)

    enhancement 
    opened by North101 0
  • Support nested result tables that don't reference an existing drift table or view

    Support nested result tables that don't reference an existing drift table or view

    It would be interesting to support nested result tables for result sets that aren't a direct reference to a defined table or view.

    Similar to what we're doing for LIST() columns, we could infer the inner result set recursively and then generate another result class for this if needed.

    enhancement 
    opened by simolus3 0
  • Why is the time difference between 1000 and 2000 so large?

    Why is the time difference between 1000 and 2000 so large?

    Without limit, 10,000 pieces of data can be queried, which takes a long time.

    If limit=1000, 293ms is required,

    But when limit=2000, 14244ms is required,

    Why is the time difference between 1000 and 2000 so large?

    How to optimize query statements?

        final limit = 1000;
        final selJoin = select(users).join([innerJoin(cats, users.id.equalsExp(cats.userId))])
          ..where(cats.age.equals(3))
          ..limit(limit);
        final start = DateTime.now().millisecondsSinceEpoch;
        final result = await selJoin.get();
        print('${DateTime.now().millisecondsSinceEpoch - start}');
    

    Can I use the offset of limit to perform multiple queries, which will be many times faster than one-time queries?

    limit(1000,offset:0)
    limit(1000,offset:1000)
    limit(1000,offset:2000)
    limit(1000,offset:3000)
    ...
    
    
    opened by ddxl123 1
  • Investigate generating CRUD accessors for individual tables

    Investigate generating CRUD accessors for individual tables

    I think that makes sense. I managed to migrate most of our code. But traditionally DAOs are often used for a single entity class. So far we mixed in basic CRUD queries into each DAO for a main entity class. Now there is not much left in the DAO except these CRUD queries and the concern is that, if we move them to drift files, we will have copy & paste errors.

    I wonder if Drift can help here with some TBD magic comment/query syntax that leads to Drift generating CRUD queries. I think that could also benefit a lot of people to get the initial jump start when testing or adopting the library.

    -- drift:generate-crud(foo)
    
    OR 
    
    crud(foo):
    

    leads to

    findAllFoo:
    SELECT * FROM foo;
    
    findFooById:
    SELECT * FROM foo WHERE PK = :PK;
    
    deleteFooById:
    DELETE * FROM foo WHERE PK = :PK;
    
    existsFooById:
    SELECT EXISTS (SELECT 1 FROM foo WHERE PK = :PK);
    
    ....
    

    Originally posted by @kuhnroyal in https://github.com/simolus3/drift/issues/490#issuecomment-1344590398

    opened by simolus3 0
  • [Documentation Suggestion] Address possible concerns about the order of compound primary keys and unique

    [Documentation Suggestion] Address possible concerns about the order of compound primary keys and unique

    Drift uses Set for setting compound primry keys and unique. Sqlite creates indexes for such fields and, in some cases, order of these fields might be important. Set, though, is usually considered to not preserve any order of its elements, which might result in some concerns. In Dart, though, default Set implementation is LinkedHashSet, which actually preserves the order of its elements and won't result in any problems.

    Maybe it should be mentioned in documentation to avoid any concerns from people not aware of the default Set implementation in Dart? Or maybe even change types of these fields in Table class from Set to LinkedHashSet to make it absolutely clear?

    opened by ZhulanovAA 2
Releases(drift-2.4.2)
  • drift-2.4.2(Jan 3, 2023)

    drift 2.4.2

    • Fix an exception when a client disconnects from a drift remote server while processing a pending table update.

    drift_dev 2.4.1

    • Improvements and fixes for schema files:
      • Fix views with an existing row type generating invalid SQL in schema files.
      • Fix schema generate --companions implicitly requiring --data-classes as well.
      • Fix toColumns() not being generated correctly.
      • Fix conflicting names being generated by schema generate when using existing row types on views.

    sqlparser 0.26.0

    • Remove token parameter from constructor in Literal subclasses and NumberedVariable.
    Source code(tar.gz)
    Source code(zip)
  • drift-2.4.0(Dec 29, 2022)

    This drift release extends support for existing row classes to queries, allows storing enums by their name and handles ANY columns. A full list of improvements and new features:

    New features

    • Support existing row types on queries defined in drift files.
    • Enums can now be stored by their name instead of their index - use the textEnum() column in Dart or the ENUMNAME column type in .drift files.
    • Add the DriftAny type to handle arbitrary SQL values. It will be used by the generator for columns types declared as ANY in strict tables.
    • drift_dev schema dump can now dump the schema of existing sqlite3 database files as well.
    • Adds the case_from_dart_to_sql option with the possible values: preserve, camelCase, CONSTANT_CASE, snake_case, PascalCase, lowercase and UPPERCASE (default: snake_case).
    • Add updates parameter to Batch.customStatement - it can be used to specify which tables are affected by the custom statement.
    • Add likeExp to generate LIKE expressions with any comparison expression.

    Notable improvements

    • Fix UNIQUE keys declared in drift files being written twice.
    • Lazily load columns in TypedResult.read, increasing performance for joins with lots of tables or columns.
    • Work-around an issue causing complex migrations via Migrator.alterTable not to work if a view references the altered table.
    • Warn about suspicious int or text literals being inserted into enum columns.
    • For Dart-defined columns, customConstraints are now parsed and respected by the generator.
    • It is now allowed to interleave queries and tables in a drift file.

    This drift release also adds experimental support for record types as existing types for tables or queries. Note that records are experimental in the Dart language, so the feature may be updated or removed depending on its development in the language.

    Source code(tar.gz)
    Source code(zip)
  • drift-2.3.0(Nov 27, 2022)

    • Add the JsonTypeConverter2 mixin. It behaves similar to the existing json type converters, but can use a different SQL and JSON type.
    • Add isInValues and isNotInValues methods to columns with type converters. They can be used to compare the column against a list of Dart expressions that will be mapped through a type converter.
    • Add TableStatements.insertAll to atomically insert multiple rows.
    • Add singleClientMode to remote() and DriftIsolate connections to make the common case with one client more efficient.
    • Fix a concurrency issue around transactions.
    • Add NativeDatabase.createInBackground as a drop-in replacement for NativeDatabase(). It creates a drift isolate behind the scenes, avoiding all of the boilerplate usually involved with drift isolates.
    • Experimental: Add a modular generation mode in which drift will generate multiple smaller files instead of one very large one with all tables and generated queries.
    Source code(tar.gz)
    Source code(zip)
  • drift-2.2.0(Oct 6, 2022)

    • Potentially breaking bug-fix: Fix the nullability of columns generated for Dart-defined views. See the documentation for details.
    • Always escape column names, avoiding the costs of using a regular expression to check whether they need to be escaped.
    • Add extensions for binary methods on integer expressions: operator ~, bitwiseAnd and bitwiseOr.
    • Serialize uniqueKeys overrides into a database schema, allowing them to be properly tested in schema tests.
    • Support the latest version of the analyzer package.
    Source code(tar.gz)
    Source code(zip)
  • drift-2.1.0(Aug 29, 2022)

    Changes in drift version 2.1.0:

    • Improve stack traces when using watchSingle() with a stream emitting a non-singleton list at some point.
    • Add OrderingTerm.nulls to control the NULLS FIRST or NULLS LAST clause in Dart.

    Changes in drift_dev version 2.1.0 and sqlparser version 0.23.2:

    • Analysis support for fts5 tables with external content tables.
    • Analysis support for the rtree module.
    • Internally prepare for an upcoming breaking analyzer change around how classes are mapped to elements.
    • Improve static analysis around subqueries in SQL.
    Source code(tar.gz)
    Source code(zip)
  • drift-2.0.2+1(Aug 21, 2022)

    This patch release fixes some issues introduced by the upgrade to drift 2.0:

    • drift 2.0.2: Revert the breaking change around QueryRow.read only returning non-nullable values now - it was causing issues with type inference in some cases.
    • drift_dev 2.0.2: Generate typedefs for the signatures of scoped_dart_components, making it easier to re-use them in your own methods.
    • sqlparser 0.23.1: Gracefully handle tokenizer errors related to @ or $ variables instead of crashing.
    Source code(tar.gz)
    Source code(zip)
  • drift-2.0.0(Aug 14, 2022)

    The first major update to the drift packages contains a number of breaking changes and removes some obsolete features. This includes:

    • Breaking: Type converters now return the types that they were defined to return (instead of the nullable variant of those types like before). It is an error to use a non-nullable type converter on a column that is nullable in SQL and vice-versa.
    • Breaking: Mapping methods on type converters are now called toSql and fromSql.
    • Breaking: Removed SqlTypeSystem and subtypes of SqlType:
      • To describe the type a column has, use the DriftSqlType enum
      • To map a value from Dart to SQL and vice-versa, use an instance of SqlTypes, reachable via database.options.types.
    • Breaking: Expressions (including Columns) always have a non-nullable type parameter now. They are implicitly nullable, so TypedResult.read now returns a nullable value.
    • Breaking: QueryRow.read can only read non-nullable values now. To read nullable values, use readNullable.
    • Breaking: Remove the includeJoinedTableColumns parameter on selectOnly(). The method now behaves as if that parameter was turned off. To use columns from a joined table, add them with addColumns.
    • Breaking: Remove the fromData factory on generated data classes. Use the map method on tables instead.
    • Add support for storing date times as (ISO-8601) strings. For details on how to use this, see the documentation.
    • Consistently handle transaction errors like a failing BEGIN or COMMIT across database implementations.
    • Add writeReturning to update statements; deleteReturning and goAndReturn to delete statatements.
    • Support nested transactions.
    • Support custom collations in the query builder API.
    • Custom row classes can now be constructed with static methods too. These static factories can also be asynchronous.

    💡: More information on how to migrate is available in the documentation.

    Source code(tar.gz)
    Source code(zip)
  • drift_dev-1.7.1(Aug 9, 2022)

    This small update to drift_dev supports the latest version of the analyzer_plugin package and removes usages of deprecated analyzer APIs.

    Source code(tar.gz)
    Source code(zip)
  • drift-1.7.1(Jul 2, 2022)

    This minor release fixes a bug where the NativedDatabase implementation would not dispose statements if running them threw an exception (https://github.com/simolus3/drift/issues/1917).

    Source code(tar.gz)
    Source code(zip)
  • drift-1.7.0(Jun 7, 2022)

    This drift release brings the following new features and improvements:

    • Add the int64() column builder to store large integers. These integers are still stored as 64-bit ints in the database, but represented as a BigInt in Dart. This enables better web support for integers larger than 2⁵². More details are in the documentation.
    • Add filter and distinct support to groupConcat.
    • Fix a deadlock with the sqflite-based implementation if the first operation in a transaction is a future backed by a query stream.
    • Support version 4.x of the analyzer package

    This release also uses version 0.22.0 of the sqlparser package with the following changes:

    • A new resolver for tables and columns in analyzed queries. If this breaks anything for you, please open an issue!
    • Lint for DISTINCT misuse in aggregate function calls.
    • Analysis support for new features in the upcoming sqlite 3.39 (RIGHT and FULL joins, IS (NOT) DISTINCT FROM expressions)
    • Fix type inference for SUM() calls around int "subtypes" like booleans.
    Source code(tar.gz)
    Source code(zip)
  • drift-1.6.0(May 4, 2022)

    • Add the unique() method to columns and the uniqueKeys override to define unique constraints in Dart tables.
    • Add the check() method to the Dart column builder to generate CHECK column constraints.
    • Also apply type converters for json serialization and deserialization if they mix in JsonTypeConverter.
    • Add the very experimental package:drift/wasm.dart library. It uses WebAssembly to access sqlite3 without any external JavaScript libraries, but requires you to add a WebAssembly module to the web/ folder. Please note that this specific library is not subject to semantic versioning until it leaves its experimental state. It also isn't suitable for production use at the moment.
    • Internally use package:js to wrap sql.js.
    Source code(tar.gz)
    Source code(zip)
  • drift-1.5.0(Mar 13, 2022)

    • Add DataClassName.extending to control the superclass of generated row classes.
    • Add setup parameter to the constructors of WebDatabase too.
    • Don't write variables for expressions in CREATE VIEW statements.
    • Improve stack traces for errors on a remote isolate.
    • Add MultiExecutor.withReadPool constructor to load-balance between multiple reading executors. This can be used in a multi-isolate approach if some queries are expensive.

    drift_dev also has new features:

    • Add validateDatabaseSchema extension to package:drift_dev/api/migrations.dart. It validates that the schema of a database at runtime matches what one would expect. This can be used to test the correctness of migrations at runtime without special testing code.
    • New features in sqlite 3.38 are supported in analyzed queries and drift files when changing the dialect version in the build options.
    Source code(tar.gz)
    Source code(zip)
  • drift-1.4.0(Feb 9, 2022)

    1.4.0

    • Most methods to compose statements are now available as an extension on tables. As an alternative to update(todos).replace(newEntry), you can now write todos.replaceOne(newEntry).
    • Deprecate the from(table) API introduced in 1.3.0. Having the methods on the table instances turned out to be even easier!
    • In drift files, you can now use LIST(SELECT ...) as a result column to get all results of the inner select as a List in the result set.
    Source code(tar.gz)
    Source code(zip)
  • drift-1.3.0(Jan 14, 2022)

    • Add the from(table) method to generated databases. It can be used to write common queries more concisely.
    • Make groupConcat nullable in the Dart API.
    • Throw an exception in a NativeDatabase when multiple statements are run in a single call. In previous versions, parts of the SQL string would otherwise be ignored.
    • Close the underlying database when a drift isolate is shut down.
    Source code(tar.gz)
    Source code(zip)
  • drift_dev-1.2.1(Jan 10, 2022)

  • drift-1.2.0(Dec 30, 2021)

    This minor release implements changes in the generated code necessary to support streams from views in the Dart API.

    Additionally,

    • Reading blobs from the database is more lenient now.
    • watchSingle() and watchSingleOrNull() now throws an error with a stack trace when used on a query emitting multiple rows.
    • With sqlparser 0.19.1, group_concat was made nullable as evaluates to NULL for empty groups.
    Source code(tar.gz)
    Source code(zip)
  • drift-1.1.1(Dec 23, 2021)

    This patch release contains the following changes:

    • Rollback transactions when a commit fails.
    • Revert a change from 1.1.0 to stop serializing messages over isolates. Instead, please set the serialize parameter to false on the DriftIsolate methods.

    The generator, released as drift_dev version 1.1.1 contains a fix related to custom row classes with generateInsertable: true.

    Source code(tar.gz)
    Source code(zip)
  • drift-1.1.0(Dec 11, 2021)

    This release consists of drift version 1.1.0, drift_dev version 1.1.0 and sqlparser version 0.19.0:

    • Add the references method to BuildColumn to reference a column declared in another Dart table.
    • Add the generateInsertable option to @UseRowClass. When enabled, the generator will emit an extension to use the row class as an Insertable.
    • Allow the generator to emit correct SQL code when using arrays with the new_sql_code_generation option in specific scenarios.
    • Add support for strict tables in .drift files.
    • Add the generatedAs method to declare generated columns for Dart tables.
    • Add OrderingTerm.random to fetch rows in a random order.
    • Improved support for pausing query stream subscriptions. Instead of buffering events, query streams will suspend fetching data if all listeners are paused.
    • Drift isolates no longer serialize messages into a primitive format. This will reduce the overhead of using isolates with Drift.
    • Initial support for STRICT tables defined in .drift files.
    • Support for generated columns for tables defined in .drift files.

    Big thanks to everyone who contributed to this release!

    Source code(tar.gz)
    Source code(zip)
  • sqlparser-0.18.1(Dec 2, 2021)

    This hotfix release fixes a bug when comparing AST nodes with a different amount of children (#1575). The broken comparison may have caused false-positives in migration tests.

    Source code(tar.gz)
    Source code(zip)
  • drift_dev-1.0.2(Oct 13, 2021)

  • drift-1.0.1(Oct 12, 2021)

    • Add DoUpdate.withExcluded to refer to the excluded row in an upsert clause.
    • Add optional where clause to DoUpdate constructors

    Please note

    With this release, moor has been renamed to drift. No immediate action is necessary, the moor package will continue to work until the next breaking release. The functionality of moor 4.6.0 is identical to drift 1.0.1.

    An automatic migration tool can help you make the switch from moor to drift in minutes. See the documentation for all the details. Thanks!

    Source code(tar.gz)
    Source code(zip)
  • moor_ffi-0.3.0(Dec 18, 2019)

    0.3.0

    • Better setup for compiling sqlite3 on Android
      • Compilation options to increase runtime performance, enable fts5 and json1
      • We no longer download sqlite sources on the first run, they now ship with the plugin
    Source code(tar.gz)
    Source code(zip)
  • 2.0.1+1(Oct 20, 2019)

    Version 2.0.1+1 version of the moor package fixes #199, a bug that causes your app to crash when you use customStatement directly after opening the database.

    Source code(tar.gz)
    Source code(zip)
  • 2.0.1(Oct 11, 2019)

    • Introduced isBetween and isBetweenValues methods for comparable expressions (int, double, datetime) to check values for both an upper and lower bound
    • Automatically map BOOLEAN and DATETIME columns declared in a sql file to the appropriate type (both used to be double before).
    • Fix streams not emitting cached data when listening multiple times
    • Accept \r as whitespace in moor files and compiled queries
    • Breaking: Remove the type parameter from Insertable.createCompanion (it was declared as an internal method, but you will have to re-run the build)
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(Oct 3, 2019)

    2.0.0

    This is the first major update after the initial release and moor and we have a lot to cover: .moor files can now have their own imports and queries, you can embed Dart in sql queries using the new templates feature and we have a prototype of a pure-Dart SQL IDE ready. Finally, we also removed a variety of deprecated features. See the breaking changes section to learn what components are affected and what alternatives are available.

    New features

    Updates to the sql parser

    .moor files were introduced in moor 1.7 as an experimental way to declare tables by using CREATE TABLE statements. In this version, they become stable and support their own import and query system. This allows you to write queries in their own file:

    CREATE TABLE users (
      id INT NOT NULL PRIMARY KEY AUTOINCREMENT,
      name VARCHAR NOT NULL
    );
    
    findByName: SELECT * FROM users WHERE name LIKE :query;
    

    When this file is included from a @UseMoor annotation, moor will generate methods to run the query. Of course, you can also write Dart queries for tables declared in sql:

    Stream<User> loadUserById(int id) {
     return (select(users)..where((u) => u.id.equals(2))).watchSingle();
    }
    

    Moor files can also import other moor files by using an import 'other.moor'; statement at the top. Then, all tables defined in other.moor will also be available to the current file.

    Moor takes Dart and SQL interop even further with the new "Dart in SQL templates". You can define a query like this:

    findDynamic: SELECT * FROM users WHERE $condition;
    

    And moor will generate a method findDynamic(Expression<bool, BoolType> condition) for you. This allows you to bind the template with a predicate as complex as you'd like. At the moment, Dart templates are supported for expressions, OrderBy, OrderingTerm and Limit.

    INSERT statements can now be used as a compiled statement - both in moor files and in a @UseMoor or @UseDao annotation. A new builtin linter will even warn you when you forget to provide a value for a non-nullable column - right at compile time!

    And finally, we now generate better query code when queries only return a single column. Instead of generating a whole new class for that, we simply return the value directly.

    Experimental ffi support

    We released an experimental version of moor built on top of dart:ffi. It works cross-platform and is much, much faster than moor_flutter. It you want to try it out, read the docs here.

    Minor changes

    • a Constant<String> can now be written to SQL, it used to throw before. This is useful if you need default values for strings columns. This also works for BLOBS (Constant<Uint8List>).
    • new LazyDatabase for when you want to construct a database asynchronously (for instance, if you first need to find a file before you can open a database).

    Breaking changes

    • THIS LIKELY AFFECTS YOUR APP: Removed the transaction parameter for callbacks in transactions and beforeOpen callbacks. So, instead of writing

      transaction((t) async {
        await t.update(table)...;
      });
      

      simply write

      transaction(() async {
        await update(table)...;
      });
      

      Similarly, instead of using onOpen: (db, details) async {...}, use onOpen: (details) async {...}. You don't have to worry about calling methods on your database instead of a transaction objects. They will be delegated automatically.

      On a similar note, we also removed the operateOn parameter from compiled queries.

    • Compiled queries that return only a single column (e.g. SELECT COUNT(*) FROM users) will just return their value (in this case, an int) now. Moor no longer generates a new class in that case.

    • Removed MigrationStrategy.onFinished. Use beforeOpen instead.

    • Compiled sql queries starting with an underscore will now generate private match queries. Previously, the query _allUsers would generate a watchAllUsers method, that has been adopted to _watchAllUsers. The generate_private_watch_methods builder option, which backported this fix to older versions, has thus been removed.

    • Removed InsertStatement.insertOrReplace. Use insert(data, orReplace: true) instead.

    • Removed the diff util and MoorAnimatedList. Use a third party library for that.

    Source code(tar.gz)
    Source code(zip)
  • v1.7(Aug 24, 2019)

    • Support custom columns via type converters. See the docs for details on how to use this feature.
    • Transactions now roll back when not completed successfully, they also rethrow the exception to make debugging easier.
    • New backends api, making it easier to write database drivers that work with moor. Apart from moor_flutter, new experimental backends can be checked out from git:
      1. encrypted_moor: An encrypted moor database: https://github.com/simolus3/moor/tree/develop/extras/encryption
      2. moor_mysql: Work in progress mysql backend for moor. https://github.com/simolus3/moor/tree/develop/extras/mysql
    • The compiled sql feature is no longer experimental and will stay stable until a major version bump
    • New, experimental support for .moor files! Instead of declaring your tables in Dart, you can choose to declare them with sql by writing the CREATE TABLE statement in a .moor file. You can then use these tables in the database and with daos by using the include parameter on @UseMoor and @UseDao. Again, please notice that this is an experimental api and there might be some hiccups. Please report any issues you run into.

    Also see the full changelog for the relases from 1.2 to 1.6.

    Source code(tar.gz)
    Source code(zip)
  • v1.1(Mar 10, 2019)

his package provides a Clock class which encapsulates the notion of the "current time" and provides easy access to points relative to the current time.

This package provides a Clock class which encapsulates the notion of the "current time" and provides easy access to points relative to the current tim

Dart 34 Dec 15, 2022
:fire:GeoFlutterFire:fire: is an open-source library that allows you to store and query firestore documents based on their geographic location.

GeoFlutterFire ?? GeoFlutterFire is an open-source library that allows you to store and query a set of keys based on their geographic location. At its

Darshan N 282 Dec 11, 2022
Stream-based strongly typed GraphQL client for Dart

A simple, powerful GraphQL Client for Flutter and Dart Documentation ?? Features ✅ Fully Typed: work faster and safer with compile time checks and IDE

GQL Dart 484 Jan 9, 2023
Dart package for accessing databases.

Introduction This is database.dart, a vendor-agnostic database access API for Flutter and other Dart projects. This version is just an early preview.

Dint 63 Jan 2, 2023
Generate dart type definitions from PostgreSQL database schema

schema-dart Generate dart type definitions from PostgreSQL database schema (WIP) Installation: Until the package is published to pub.dev, it can be in

null 8 Oct 31, 2022
Persist data with Flutter's Sqflite Database locally on your Android or iOS device by using Raw SQL statements.

Flutter Tutorial - Database Storage Using Sqlite & Sqflite Persist data with Flutter's Sqflite Database locally on your Android or iOS device by using

Johannes Milke 170 Dec 30, 2022
Create a DataTable with Flutter to display data in columns, rows, and cells and also learn how to sort the data within the table.

Flutter Tutorial - Sortable DataTable Create a DataTable with Flutter to display data in columns, rows, and cells and also learn how to sort the data

Johannes Milke 22 Oct 9, 2022
AllSQL is an open-source compact browser based SQL Compiler, built using Flutter.

AllSQL - An open-source compact browser based SQL Compiler AllSQL is an open-source compact browser based SQL Compiler, built using Flutter. Please cr

Adit Luhadia 22 Nov 20, 2022
A Cool Datepicker Built With Flutter

Cool datepicker Features It's the best datepicker ui ever. (at least for me ?? ) It's possible to set all colors of datepicker Support selected date l

null 6 Nov 6, 2022
A typesafe sqlite persistence library for flutter

Warning: This library has been deprecated. Please use moor instead. It requires less work to set up, needs less boilerplate code and has more features

Simon Binder 59 Jan 18, 2021
The typesafe, reactive, and lightweight SQLite abstraction for your Flutter applications

See the project's website for the full documentation. Floor provides a neat SQLite abstraction for your Flutter applications inspired by the Room pers

Vitus 786 Dec 28, 2022
An example project to demonstrate how moor can be used on multiple platforms

moor_shared An example project to demonstrate how moor can be used on multiple p

null 0 Dec 28, 2021
State Persistence - Persist state across app launches. By default this library store state as a local JSON file called `data.json` in the applications data directory. Maintainer: @slightfoot

State Persistence Persist state across app launches. By default this library store state as a local JSON file called data.json in the applications dat

Flutter Community 70 Sep 28, 2022
Nexus is a state management library that makes it easy to create and consume your application's reactive data to the user interface.

Nexus ?? Nexus is a state management library that makes it easy to create and consume your application's reactive data to the user interface. With nex

Gor Mkhitaryan 3 Sep 7, 2022
Build an End-to-End Typesafe APIs (Experimental)

mid ⚠️ warning: the project is still experimental! so things may change often until a stable version is released. mid is a tool to build an end-to-end

osama 15 Oct 19, 2022
A demonstration of using Riverpod for dynamic locale switching in-app, with persistence.

Riverpod Localization A demonstration of using Riverpod for dynamic locale switching in-app, with persistence. How It Works Fallback Locale: Declared

Dominique Rwema Bagirishya 30 Oct 6, 2022
🌈 Repository for a compass project, basically an App for displaying bank transfers, with API requests, Flag persistence, Infinite Scroll, Error Handling, Unit Tests, Extract Sharing working with SOLID, BLoC and Designer Patterns.

?? Green Bank Aplicação desenvolvida em Flutter com intuito de trabalhar conexão com API, Gerenciamento de estado usando BLoC, Refatoração, Arquitetur

André Guerra Santos 28 Oct 7, 2022
A Flutter widget to use Apache ECharts (incubating) in a reactive way.

中文 [![pub](https://img.shields.io/pub/v/flutter_echarts.svg)](https://pub.dev/packages/flutter_echarts) A Flutter widget to use Apache ECharts in a re

LIN Chen 629 Dec 29, 2022
Reactive Programming - BLoC - Practical Use Cases and Patterns

Reactive Programming - BLoC - Practical Use Cases and Patterns Source code of the article available on didierboelens.com This article introduces some

Didier Boelens 211 Dec 29, 2022