Giter Site home page Giter Site logo

hoc081098 / sqlbrite Goto Github PK

View Code? Open in Web Editor NEW
27.0 2.0 5.0 378 KB

🌼 RxDart Reactive stream sqflite(sqlite) for Flutter - Sqlbrite for flutter - A lightweight wrapper around sqflite which introduces reactive stream semantics to SQL operations. https://pub.dev/packages/sqlbrite

Home Page: https://pub.dev/packages/sqlbrite

License: MIT License

Dart 70.47% Kotlin 0.09% Swift 0.90% Objective-C 0.02% HTML 0.12% Ruby 1.77% CMake 11.93% C++ 13.75% C 0.94%
flutter flutter-reactive-storage flutter-sqflite flutter-sqlite rxdart rxdart-bloc rxdart-epic rxdart-ext rxdart-extensions rxdart-flutter

sqlbrite's Introduction

SQL Brite alt text

Tests Build example Pub Pub Build Status codecov License: MIT Style Hits

  • Reactive stream wrapper around sqflite for Flutter inspired by sqlbrite
  • Streaming sqflite
  • RxDart reactive stream sqflite for Flutter
  • A lightweight wrapper around sqflite which introduces reactive stream semantics to SQL operations.

Getting Started

  1. Depend on it: In your flutter project, add the dependency to your pubspec.yaml
dependencies:
  ...
  sqlbrite: <latest_version>
  1. Install it: You can install packages from the command line with Flutter:
$ flutter packages get
  1. Import it: Now in your Dart code, you can use:
import 'package:sqlbrite/sqlbrite.dart';

Usage

1. Wrap your database in a BriteDatabase:

final Database db = await openDb();
final briteDb = BriteDatabase(db);
final briteDb = BriteDatabase(db, logger: null); // disable logging.

2. Using

  • The BriteDatabase.createQuery method is similar to Database.query. Listen to the returned Stream<Query> which will immediately notify with a Query to run.
  • These queries will run once to get the current data, then again whenever the given table is modified though the BriteDatabase.

Create entity model

class Entity {
  factory Entity.fromJson(Map<String, dynamic> map) { ... }
  
  factory Entity.empty() { ... }

  Map<String, dynamic> toJson() { ... }
}

Use mapToOne extension method on Stream<Query>

// Emits a single row, emit error if the row doesn't exist or more than 1 row in result set.
final Stream<Entity> singleQuery$ = briteDb.createQuery(
  'table',
  where: 'id = ?',
  whereArgs: [id],
  limit: 1,
).mapToOne((row) => Entity.fromJson(row));

Use mapToOneOrDefault extension method on Stream<Query>

// Emits a single row, or the given default value if the row doesn't exist, or emit error if more than 1 row in result set
final Stream<Entity> singleOrDefaultQuery$ = briteDb.createQuery(
  'table',
  where: 'id = ?',
  whereArgs: [id],
  limit: 1,
).mapToOneOrDefault(
  (row) => Entity.fromJson(row),
  defaultValue: Entity.empty()
);

Use mapToList extension method on Stream<Query>

// Emits a list of rows.
final Stream<List<Entity>> listQuery$ = briteDb.createQuery(
  'table',
  where: 'name LIKE ?',
  whereArgs: [queryName],
).mapToList((row) => Entity.fromJson(row));

Same API like Database

// will trigger query stream again
briteDb.insert(
  'table',
  Entity(...).toJson()
);

// will trigger query stream again
briteDb.update(
  'table',
  Entity(...).toJson(),
  where: 'id = ?',
  whereArgs: [id],
);

// will trigger query stream again
briteDb.update(
  'table',
  where: 'id = ?',
  whereArgs: [id],
);

Full power of RxDart operators

  • You can use RxDart operators to control the frequency of notifications to subscribers.
  • The full power of RxDart's operators are available for combining, filtering, and triggering any number of queries and data changes.
briteDb
    .createQuery(
      'table',
      where: 'name LIKE ?',
      whereArgs: [queryName],
    )
    .debounceTime(const Duration(milliseconds: 500))
    .where(filterQuery) // query is lazy, this lets you not even execute it if you don't need to
    .mapToList((row) => Entity.fromJson(row))
    .listen(updateUI);

Philosophy

SQL Brite's only responsibility is to be a mechanism for coordinating and composing the notification of updates to tables such that you can update queries as soon as data changes.

This library is not an ORM. It is not a type-safe query mechanism. It's not going to perform database migrations for you.

License

MIT License
Copyright (c) 2019 - 2022 Petrus Nguyễn Thái Học

sqlbrite's People

Contributors

hoc081098 avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

sqlbrite's Issues

Error: error: ../../../../.pub-cache/hosted/pub.dev/sqlbrite-2.6.0/lib/src/brite_database.dart:17:7: Error: The non-abstract class 'BriteDatabase' is missing implementations for these members:

Hello,

This used to be an issue couple months ago when building locally but it was fixed. Now I am getting similar error when using Github Action. I am puzzled of what it might be.

image

I can't expand to see what those members are.

I have even specified exact versions to use in pubspec.yaml

sqlbrite: 2.6.0
sqflite: 2.2.4

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

cocoapods
example/ios/Podfile
example/macos/Podfile
github-actions
.github/workflows/build-example.yml
  • actions/checkout v4
  • actions/setup-java v4
  • subosito/flutter-action v2.16.0
  • actions/upload-artifact v4
.github/workflows/flutter.yml
  • actions/checkout v4
  • subosito/flutter-action v2.16.0
  • codecov/codecov-action v4.5.0
.github/workflows/publish.yml
  • actions/checkout v4
  • subosito/flutter-action v2.16.0
  • dart-lang/setup-dart a57a6c04cf7d4840e88432aad6281d1e125f0d46
.github/workflows/remove-old-artifacts.yml
  • c-hive/gha-remove-artifacts v1
gradle
example/android/gradle.properties
example/android/settings.gradle
example/android/build.gradle
  • com.android.tools.build:gradle 7.1.2
  • org.jetbrains.kotlin:kotlin-gradle-plugin 1.6.10
  • org.jetbrains.kotlin:kotlin-stdlib-jdk7 1.6.10
example/android/app/build.gradle
gradle-wrapper
example/android/gradle/wrapper/gradle-wrapper.properties
  • gradle 7.4
pub
example/pubspec.yaml
  • flutter
  • cupertino_icons ^1.0.6
  • path_provider ^2.1.2
  • path ^1.8.3
  • intl ^0.19.0
  • flutter_lints ^3.0.1
  • rxdart_ext ^0.2.9
  • collection ^1.17.2
  • platform ^3.1.4
  • dart >=3.0.0 <4.0.0
  • flutter >=3.10.0
pubspec.yaml
  • flutter
  • rxdart_ext ^0.2.5
  • sqflite_common ^2.5.3
  • sqflite ^2.3.2
  • sqflite_common_ffi ^2.1.1+1
  • mockito ^5.3.0
  • flutter_lints ^1.0.4
  • build_runner ^2.2.0
  • analyzer ^6.0.0
  • code_builder ^4.2.0
  • path ^1.8.2
  • dart >=3.0.0 <4.0.0
  • flutter >=3.10.0

  • Check this box to trigger a request for Renovate to run again on this repository

Stream is not working in Getx

I have my code like this

  @override
  void onInit() {

    rxLhdChartUi.bindStream(DBProvider.db.watchAll());
  
    super.onInit();

My db is

  // Reactive DB listener
  Stream<List<TestResult>> watchAll() async*{
    final db = await streamDatabase;
    yield* db
        .createQuery("test_result")
        .mapToList((row) => TestResult.fromDB(row));
  }

This stream get data at the start of app, other than that it won't update continually

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (github>whitesource/merge-confidence:beta)

Support null safety

This is a request to add support for null safety to package:sqlbrite.
We depend on your awesome package, so would be great to have null safety enabled.

The Dart/Flutter team already encourages publishing the migrated packages: See this blog post.

See the migration guide for details about enabling null safety.

'BriteBatch' is missing implementation for Batch.apply

Hey there,

with an update to Flutter 3.3.2, my app's build suddenly start to fail with the following message:

Error: The non-abstract class 'BriteBatch' is missing implementations for these members:
../…/src/brite_batch.dart:8
     - Batch.apply

class BriteBatch implements IBriteBatch {
          ^^^^^^^^^^
: Context: 'Batch.apply' is defined here.
../…/lib/sqlite_api.dart:479
      Future<List<Object?>> apply({bool? noResult, bool? continueOnError});
                            ^^^^^

The sqlbrite version I'm using is 2.3.0.

After checking the sqlbrite-2.3.0/lib/src/brite_batch.dart I found out that the implementation of Future<List<Object?>> apply({bool? noResult, bool? continueOnError}) is indeed missing and this causes the issue.

Any chance this can be addressed?

Thanks in advance!

Error: The non-abstract class 'BriteDatabase' is missing implementations for these members

Launching lib/main.dart on moto g22 in debug mode...
: Error: The non-abstract class 'BriteTransaction' is missing implementations for these members:

  • DatabaseExecutor.queryCursor

  • DatabaseExecutor.rawQueryCursor
    Try to either

  • provide an implementation,

  • inherit an implementation from a superclass or mixin,

  • mark the class as abstract, or

  • provide a 'noSuchMethod' implementation.

class BriteTransaction extends AbstractBriteDatabaseExecutor
^^^^^^^^^^^^^^^^
: Context: 'DatabaseExecutor.queryCursor' is defined here.
Future queryCursor(String table,
^^^^^^^^^^^
: Context: 'DatabaseExecutor.rawQueryCursor' is defined here.
Future rawQueryCursor(String sql, List<Object?>? arguments,
^^^^^^^^^^^^^^
: Error: The non-abstract class 'BriteDatabase' is missing implementations for these members:

  • DatabaseExecutor.queryCursor

  • DatabaseExecutor.rawQueryCursor
    Try to either

  • provide an implementation,

  • inherit an implementation from a superclass or mixin,

  • mark the class as abstract, or

  • provide a 'noSuchMethod' implementation.

class BriteDatabase extends AbstractBriteDatabaseExecutor
^^^^^^^^^^^^^
: Context: 'DatabaseExecutor.queryCursor' is defined here.
Future queryCursor(String table,
^^^^^^^^^^^
: Context: 'DatabaseExecutor.rawQueryCursor' is defined here.
Future rawQueryCursor(String sql, List<Object?>? arguments,

                  ^^^^^^^^^^^^^^

FAILURE: Build failed with an exception.

  • Where:
    Script '/Users/darek/Desktop/Dev/Flutter/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 1159

  • What went wrong:
    Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command '/Users/darek/Desktop/Dev/Flutter/flutter/bin/flutter'' finished with non-zero exit value 1

  • Try:

Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.

BUILD FAILED in 8s
Exception: Gradle task assembleDebug failed with exit code 1
Exited

Flutter SqlBrite not rebuilding automatically in streambuilder list

I am trying to build a chat storage system with firebase, sqlite and sqlBrite. The aim of this is to stream the newmessages without having to rebuild the page. The stream from sqlBrite is only rebuilding on setstate eg.when the keyboard is drawn back.

How can i get the stream to automatically update on save.

The db document


///INSERT INTO DB
    Future<int> insertNewMessage(String id, int result, BriteDatabase briteDb,
          Map<String, dynamic> row) async {
        messageList.add(id);
    
        await ifexists(id, messageId, briteDb)
            ? print('message already In')
            : result = await briteDb.insert(messageTable, row);
        return result;
      }

////STREAM MESSAGES
    Stream<List<Map<String, dynamic>>> getMessageMapListbyId(
          {String sendId, String receiveId, database}) async* {
        try {
          BriteDatabase briteDb = await database;
        yield* briteDb.createQuery(messageTable,
                  distinct: false,
                  where:
                      ' $senderId=? $receiverId = ? ',
                  whereArgs: [
                      sendId,
                      receiverId,
                    ])});

provider document

///ADD MESSAGES
    addMessageTodb(message) async {
        await ldbH
            .msg_insertMessage(
                message.id, modelFuncs.messageMaping(message, msgFuncs))
            .then((value) async {
         
          await getMessageYieldBase(message.senderId, message.receiverId);
        });}

    ///STREAM NEW DATA
getMessageYieldBase(senderId, receiverId) async* {
        yield* ldbH.msg_getAllMessagesbyId(senderId, receiverId);}

The ui side

StreamBuilder(
            stream: messageStream.getMessageYieldBase(
                widget._currentUserId, widget.receiver.uid),
            builder: (context, AsyncSnapshot<dynamic> snapshot) {
              var d = snapshot.data;
              var newList = snapshot.hasData ? d.reversed.toList() : [];
              return ListView.builder(
                      reverse: true,
                      padding: EdgeInsets.all(10),
                      controller: widget._listScrollController,
                      itemCount: newList.length,
                      itemBuilder: (BuildContext context, int index) {  return DisplayMessage(
                          currentUserId: widget._currentUserId,
                          receiver: widget.receiver,
                          message: newList[index],
                        );
                      });
            })

So the new texts keep coming only when the page rebuilds in any sort of way. Any help rendered is appreciated.

feat: `queryCursorAsStream`

ReactiveX/rxdart#696

Stream<JSON> queryCursorAsStream(
    String table, {
    bool? distinct,
    List<String>? columns,
    String? where,
    List<Object?>? whereArgs,
    String? groupBy,
    String? having,
    String? orderBy,
    int? limit,
    int? offset,
    int? bufferSize,
  }) =>
      Rx.using<JSON, sqlite_api.QueryCursor>(
        () => queryCursor(
          table,
          distinct: distinct,
          columns: columns,
          where: where,
          whereArgs: whereArgs,
          groupBy: groupBy,
          having: having,
          orderBy: orderBy,
          limit: limit,
          offset: offset,
          bufferSize: bufferSize,
        ),
        (cursor) async* {
          while (await cursor.moveNext()) {
            yield cursor.current;
          }
        },
        (cursor) => cursor.close(),
      );

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.