Giter VIP home page Giter VIP logo

sqflite's Introduction

sqflite

pub package

SQLite plugin for Flutter. Supports iOS, Android and MacOS.

  • Support transactions and batches
  • Automatic version management during open
  • Helpers for insert/query/update/delete queries
  • DB operation executed in a background thread on iOS and Android
  • Linux/Windows/DartVM support using sqflite_common_ffi

Documentation

sqflite's People

Contributors

0biwankenobi avatar alextekartik avatar andyzhshg avatar arthurmonteiroalvesmelo avatar augustozanellato avatar bartekpacia avatar blondie63 avatar davidmartos96 avatar dependabot[bot] avatar gaaclarke avatar jiahaog avatar joshpetit avatar kelburke avatar kevmoo avatar mit-mit avatar muhleder avatar philparisot avatar sethladd avatar simolus3 avatar simpleliujl avatar srawlins avatar stereotype441 avatar superfell avatar time1ess avatar tnorbury avatar ttencate avatar veronikalaskova avatar vitusortner avatar wills avatar zhenpingcui 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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  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

sqflite's Issues

support string as primary key

Can I use string id instead of integer? I am new to the dart language. I expect the rawInsert should return Future<T> instead of Future<int>. So the type system can infer the id type with the return var type.

int id = txt.rawInsert(...)
// or
String id = txt.rawInsert(...)

Is a Room like API possible?

Hi,

Room provides a really nice API to use SQLite on Android. Since iOS also supports SQLite, is there a way to bring an API similar to Room in this library for Flutter?

MissingPluginException when testing with sqflite

Hi, I'm wondering if there is a way to workaround this problem when running flutter test with sqflite. I know that there is also a similar problem with path_provider when testing because getting a directory for use with tests is different (https://flutter.io/cookbook/persistence/reading-writing-files/).

After following the testing steps on that page I was able to get past the first problem with path_provider, but then get the following:

MissingPluginException(No implementation found for method openDatabase on channel com.tekartik.sqflite)
package:flutter/src/services/platform_channel.dart 153:7   MethodChannel.invokeMethod
  ===== asynchronous gap ===========================
  dart:async                                                 _Completer.completeError
  package:flutter/src/services/platform_channel.dart         MethodChannel.invokeMethod
  ===== asynchronous gap ===========================
  dart:async                                                 _asyncThenWrapperHelper
  package:flutter/src/services/platform_channel.dart 146:74  MethodChannel.invokeMethod
  package:sqflite/src/sqflite_impl.dart 17:28                invokeMethod
  ===== asynchronous gap ===========================
  dart:async                                                 new Future.microtask
  package:sqflite/src/sqflite_impl.dart 16:69                invokeMethod
  package:sqflite/src/database.dart 197:7                    SqfliteDatabase.invokeMethod
  package:sqflite/src/database.dart 459:14                   SqfliteDatabase._openDatabase.<fn>
  package:sqflite/src/exception.dart 78:28                   wrapDatabaseException
  ===== asynchronous gap ===========================
  dart:async                                                 new Future.microtask
  package:sqflite/src/exception.dart 76:62                   wrapDatabaseException
  package:sqflite/src/database.dart 458:12                   SqfliteDatabase._openDatabase
  package:sqflite/src/database.dart 506:28                   SqfliteDatabase.open
  ===== asynchronous gap ===========================
  dart:async                                                 new Future.microtask
  package:sqflite/src/database.dart 487:39                   SqfliteDatabase.open
  package:sqflite/src/database.dart 610:19                   openDatabase
  package:sqflite/sqflite.dart 280:5                         openDatabase
  package:flutter_app/services/data.service.dart 28:28       DataService.initDb

This is what I have tried and it doesn't seem to have worked, the tests run forever:

final Directory directory = await Directory.systemTemp.createTemp();
final String path = join(directory.path, "main.db");

const MethodChannel('com.tekartik.sqflite')
        .setMockMethodCallHandler((MethodCall methodCall) async {
      if (methodCall.method == 'openDatabase') {
        SqfliteDatabase db = new SqfliteDatabase(path);
        return db.open(version: 1, onCreate: _onCreate);
      }
      return null;
});

Escaping Strings

I'm getting a SQL syntax error when trying to insert a text which contains ' " '. Is this something I should manually escape or could the library do that work?

License stated "Copyright 2017 Your Company"

Hi,

we are using your plugin in our app and would like to properly credit you on the credits / licenses page but your license file only states the placeholder "Copyright 2017 Your Company"

Do you want to fix this or let us know how to properly attribute you?

Thanks a lot either way.

Considering a new project title

Hi!

Thanks very much for writing this plugin!

May I ask you to consider a new title for the project? The ".dart" can imply it works wherever Dart works, but this plugin only works with Flutter.

Some ideas, but feel free to use your own title :)

sqflite.flutter
sqflite_flutter

Cheers!

Error running simple execute query

When I try to create a database on android, with the following on create:

onCreate: (Database db, int version) async {
    await db.execute("create table config (name varchar(32), value varchar(32));");
}

The app crashes with this error:

E/AndroidRuntime(11343): FATAL EXCEPTION: Sqflite
E/AndroidRuntime(11343): Process: com.example.protectionpro, PID: 11343
E/AndroidRuntime(11343): java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range.  The statement has 0 parameters.
E/AndroidRuntime(11343): 	at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
E/AndroidRuntime(11343): 	at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)
E/AndroidRuntime(11343): 	at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
E/AndroidRuntime(11343): 	at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:49)
E/AndroidRuntime(11343): 	at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1392)
E/AndroidRuntime(11343): 	at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1331)
E/AndroidRuntime(11343): 	at com.tekartik.sqflite.SqflitePlugin.query(SqflitePlugin.java:511)
E/AndroidRuntime(11343): 	at com.tekartik.sqflite.SqflitePlugin.access$200(SqflitePlugin.java:52)
E/AndroidRuntime(11343): 	at com.tekartik.sqflite.SqflitePlugin$1.run(SqflitePlugin.java:357)
E/AndroidRuntime(11343): 	at android.os.Handler.handleCallback(Handler.java:790)
E/AndroidRuntime(11343): 	at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(11343): 	at android.os.Looper.loop(Looper.java:164)
E/AndroidRuntime(11343): 	at android.os.HandlerThread.run(HandlerThread.java:65)
I/Process (11343): Sending signal. PID: 11343 SIG: 9
Lost connection to device.

Bulk inserts

Currently it's not possible to bulk insert records using a simple API.

I managed to achieve this result by manually creating this kind of query and binding the parameters to it. The gain in speed is remarkable (10x at least):

INSERT INTO table (col1, col2) VALUES (?, ?), (?, ?), (?, ?), ...

It shouldn't be that hard to implement a bulk insert method that follows this pattern. The only thing to pay attention to is that SQLite limits the max bound arguments to 500 per query, so if the records/columns are a lot, queries need to be splitted and batched (maybe in a transaction)

FATAL Exception: Sqflite

FATAL EXCEPTION: Sqflite
Process: com.vendetta.flutterapp, PID: 4816
java.lang.IllegalArgumentException: the bind value at index 1 is null
            at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:164)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
 	at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:49)
android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1401)
android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1340)
at com.tekartik.sqflite.SqflitePlugin.query(SqflitePlugin.java:511)
at com.tekartik.sqflite.SqflitePlugin.access$200(SqflitePlugin.java:52)
at com.tekartik.sqflite.SqflitePlugin$1.run(SqflitePlugin.java:357)
at android.os.Handler.handleCallback(Handler.java:819)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.os.HandlerThread.run(HandlerThread.java:65)

I've got this error when i tried to store some data inside the database. This is the function were the error was thrown:

Future datenSpeicher() async{
      Datenbank db = new Datenbank();
      await db.oeffnen();

      Rezept rezept = new Rezept();
      rezept.name = name_gespeichert;
      rezept.personen = anzahl_gespeichert;

      print(rezept.name+" "+rezept.personen.toString());

      rezept = await db.einfuegenRezept(rezept); //on this line was the error
    }

To add some data inside the database I use this function:

Future<Rezept> einfuegenRezept(Rezept rezept) async{
    var count = Sqflite.firstIntValue(await _db.rawQuery("SELECT COUNT(*) FROM rezept WHERE _ID = ?", [rezept.id]));
    if(count == 0){
      rezept.id = await _db.insert(tableRezept, rezept.toMap());
    } else{
      //await _db.update(tableRezept, rezept.toMap(), where: "id = ?", whereArgs: [rezept.id]);
    }

    return rezept;
  }

I hope that somebody has a solution to my problem! :-D

Failed to find Build Tools revision 26.0.3

here is the log while compiling in android device:


FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':sqflite'.

Failed to find Build Tools revision 26.0.3

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

  • Get more help at https://help.gradle.org

BUILD FAILED in 1s


then I remove "buildToolsVersion '26.0.3' " in build.gradle , fixed.

Concurrency support

I'd like to help with enabling concurrency support for Sqflite because I know it would benefit a lot from it but I'm having trouble disabling the locks that prevent it from occurring. So far, I've only commented out the return synchronized from rawQuery as a test but for some reason I'm still getting the queries executed sequentially on my Android device even when the queries are surrounded by

List<Future> futures = new List.generate(
      10,
      (int i) => db.query('test$i'),
    );

    await Future.wait(futures, eagerError: true);

as detailed by the logs

12-19 13:02:11.724 23632-23666/com.terkartik.sqflite_example D/Sqflite: [Thread[Sqflite,5,main]] SELECT * FROM test8
12-19 13:02:11.731 23632-23666/com.terkartik.sqflite_example D/Sqflite: {name=item 0, id=1}
12-19 13:02:11.731 23632-23666/com.terkartik.sqflite_example D/Sqflite: {name=item 1, id=2}
12-19 13:02:11.978 23632-23666/com.terkartik.sqflite_example D/Sqflite: {name=item 4999, id=5000}
12-19 13:02:11.978 23632-23666/com.terkartik.sqflite_example D/Sqflite: [Thread[Sqflite,5,main]] SELECT * FROM test9
12-19 13:02:11.986 23632-23666/com.terkartik.sqflite_example D/Sqflite: {name=item 0, id=1}
12-19 13:02:11.986 23632-23666/com.terkartik.sqflite_example D/Sqflite: {name=item 1, id=2}
12-19 13:02:12.173 23632-23666/com.terkartik.sqflite_example D/Sqflite: {name=item 4999, id=5000}

which show that there's a 200ms delay for when the 1st and 2nd query start which shouldn't happen if the queries run concurrently (unless there's something I don't understand about Future.wait.

A package may not list itself as a dependency

When i try to get the package i get this

Running "flutter packages get" in sqflite...
Error on line 11, column 3 of pubspec.yaml: A package may not list itself as a dependency.
  sqflite: "^0.8.6"
  ^^^^^^^
pub get failed (65)

Data deleted

I've been using sqflite for a bit and have noticed that the data can disappear when I restart the app or the app crashes.

Version 0.7.1 crashes on database init with following stack:

E/flutter ( 5025): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 5025): NoSuchMethodError: Class 'List' has no instance method 'cast'.
E/flutter ( 5025): Receiver: _List len:1
E/flutter ( 5025): Tried calling: cast()
E/flutter ( 5025): #0      Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)
E/flutter ( 5025): #1      new QueryResultSet (package:sqflite/src/sqflite_impl.dart:69)
E/flutter ( 5025): #2      queryResultSetFromMap (package:sqflite/src/sqflite_impl.dart:41)
E/flutter ( 5025): #3      queryResultToList (package:sqflite/src/sqflite_impl.dart:52)
E/flutter ( 5025): #4      Database.rawQuery.<anonymous closure>.<anonymous closure> (package:sqflite/sqflite.dart:269)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #5      wrapDatabaseException (package:sqflite/src/exception.dart:48)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #6      Database.rawQuery.<anonymous closure> (package:sqflite/sqflite.dart:264)
E/flutter ( 5025): #7      SynchronizedLock.synchronized (package:synchronized/src/synchronized_impl.dart:125)
E/flutter ( 5025): #8      Database.synchronized (package:sqflite/sqflite.dart:308)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #9      Database.rawQuery (package:sqflite/sqflite.dart:263)
E/flutter ( 5025): #10     Database.getVersion (package:sqflite/sqflite.dart:351)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #11     openDatabase.<anonymous closure> (package:sqflite/sqflite.dart:496)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #12     Database.inTransaction.<anonymous closure> (package:sqflite/sqflite.dart:335)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #13     SynchronizedLock._run.<anonymous closure>.<anonymous closure> (package:synchronized/src/synchronized_impl.dart:87)
E/flutter ( 5025): #14     _rootRun (dart:async/zone.dart:1126)
E/flutter ( 5025): #15     _CustomZone.run (dart:async/zone.dart:1023)
E/flutter ( 5025): #16     runZoned (dart:async/zone.dart:1501)
E/flutter ( 5025): #17     SynchronizedLock._run.<anonymous closure> (package:synchronized/src/synchronized_impl.dart:85)
E/flutter ( 5025): #18     new Future.sync (dart:async/future.dart:222)
E/flutter ( 5025): #19     SynchronizedLock._run (package:synchronized/src/synchronized_impl.dart:84)
E/flutter ( 5025): #20     SynchronizedLock.synchronized.run (package:synchronized/src/synchronized_impl.dart:150)
E/flutter ( 5025): #21     SynchronizedLock.synchronized (package:synchronized/src/synchronized_impl.dart:160)
E/flutter ( 5025): #22     Database.writeSynchronized (package:sqflite/sqflite.dart:319)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #23     Database.inTransaction (package:sqflite/sqflite.dart:327)
E/flutter ( 5025): #24     openDatabase (package:sqflite/sqflite.dart:495)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #25     BookDatabase.init (package:test_app/database.dart:27)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #26     Repository.init (package:test_app/data/repository.dart:26)
E/flutter ( 5025): <asynchronous suspension>
E/flutter ( 5025): #27     _SearchBookState.initState (package:test_app/pages/search_book_page.dart:84)
E/flutter ( 5025): #28     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3711)
E/flutter ( 5025): #29     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3577)
E/flutter ( 5025): #30     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2875)
E/flutter ( 5025): #31     Element.updateChild (package:flutter/src/widgets/framework.dart:2678)
E/flutter ( 5025): #32     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3613)
E/flutter ( 5025): #33     Element.rebuild (package:flutter/src/widgets/framework.dart:3463)
E/flutter ( 5025): #34     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3582)
E/flutter ( 5025): #35     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3577)
E/flutter ( 5025): #36     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2875)
E/flutter ( 5025): #37     Element.updateChild (package:flutter/src/widgets/framework.dart:2678)
E/flutter ( 5025): #38     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3613)
E/flutter ( 5025): #39     Element.rebuild (package:flutter/src/widgets/framework.dart:3463)
E/flutter ( 5025): #40     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3582)
E/flutter ( 5025): #41     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3577)
E/flutter ( 5025): #42     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2875)
E/flutter ( 5025): #43     Element.updateChild (package:flutter/src/widgets/framework.dart:2678)
E/flutter ( 5025): #44     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4588)
E/flutter ( 5025): #45     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2875)
E/flutter ( 5025): #46     Element.updateChild (package:flutter/src/widgets/f

Only 1 value returned

If there are 2 columns with the same name from 2 different tables, the value for that column that is entered last will be returned.

For example, let's say there are 2 tables, A and B, with the same column name where A.name = "A" and B.name = "B".
If the query is

SELECT A.name, B.name, A.id FROM A JOIN B ON B.id = A.id WHERE A.name = 'A';

the plugin returns {'name': 'B', 'id': 1}.

However, if it is

SELECT B.name, A.name, B.id FROM A JOIN B ON B.id = A.id WHERE A.name = 'A';

the plugin returns {'name': 'A', 'id': 1}.

What I'm expecting from both of these queries is {'A.name': 'A', 'B.name': 'B', 'id': 1} or {'A.name': 'A', 'B.name': 'B', 'A.id': 1} (using the 1st query as an example)

Change activity to context when accessing application context

When plugin is been registered activity is used:

    public static void registerWith(Registrar registrar) {
        final MethodChannel channel = new MethodChannel(registrar.messenger(), "com.tekartik.sqflite");
        channel.setMethodCallHandler(new SqflitePlugin(registrar.activity().getApplicationContext()));
    }

would be great to use registrar's context instead:

    public static void registerWith(Registrar registrar) {
        final MethodChannel channel = new MethodChannel(registrar.messenger(), "com.tekartik.sqflite");
        channel.setMethodCallHandler(new SqflitePlugin(registrar.context().getApplicationContext()));
    }

This is needed to support "headless" mode, when activity not necessarily available.

Fails silently on iOS if logging is disabled

There's a bug around line 320 in SqflitePlugin.m that causes the execution queue to only be created if logging is enabled (NSOperationQueue is created inside the check for _log when it should have been outside) - this is the correct code:

** if (_databaseOpenCount++ == 0) {
if (_log) {
NSLog(@"Creating operation queue");
}
self.operationQueue = [NSOperationQueue new];
} **

Query results always empty when using not primary key

i'm trying to execute next query in my flutter application:
return await _db.query("npa", columns: ["id", "title" ,"identifier"], where: '"identifier" = ?', whereArgs: ["0008120150514"]);
but the results is always - empty QueryResultSet[].

If i'm trying to do the same with the id field and integer value like
return await _db.query("npa", columns: ["id", "title" ,"identifier"], where: '"id" = ?', whereArgs: ["215"]);

  • works fine.

I've got the npa.identifier = "0008120150514" (id : 215) in database, so the trouble not in data existense.

How to do a SELECT query using WHERE IN?

Does sqflite support using WHERE...IN? Because when I try

// Tried both IN (?) and IN ? with 1st argument of whereArgs as array and string
db.query('table', where: 'id IN (?)', whereArgs: [ids.join(', ')], orderBy: 'id ASC');

it returns 0 rows, which means it's most likely not forming the query properly (although I'm not sure how I can see the complete query being sent), and I'm sure it's not the DB missing the data or writing the query wrong because when I did a query on the DB myself, it returned the rows I was looking for.

Should ConflictAlgorithm be expose?

To avoid requiring import 'package:sqflite/src/sql_builder.dart' show ConflictAlgorithm; in which, dart analyzer complain about not to import from src folder.

Insert or update

Is there an easy and efficient way to insert multiple objects to a database if not existing, or update if already exist? Do you predicted this eventuality? Some SQL helper maybe, or do I need to manually check each object for existence in the database?

NoSuchMethodError

The method 'execute' and also the method ".query" is throwing an error:

  • NoSuchMethodError: The method 'execute' was called on null.
  • NoSuchMethodError: The method 'query' was called on null.
import 'dart:async';
import 'dart:io';
import 'package:flutter_app/datenbank/Rezepte.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseClient{
  Database database;

  //Datenbank wird erstellt
  Future erstellen() async{
    Directory pfad = await getApplicationDocumentsDirectory();
    String datenbankPfad = join(pfad.path, "rezept_buch.db");

    database = await openDatabase(datenbankPfad, version: 1, onCreate: this.erstelleTabellen);
  }

  //Die Tabellen werden erstellt
  Future erstelleTabellen(Database db, int version) async{
    await database.execute("""  //The error is on this line
      create table rezept (
        id integer primary key,
        name text not null,
        personen_anzahl integer not null,
        beschreibung text default null,
        favorit integer default 0
      )
    """);
  }
  
  
  Future setRezept(Rezepte rezepte) async{
    var count = Sqflite.firstIntValue(await database.rawQuery("SELECT * FROM rezept WHERE name =?", [rezepte.name]));
    if(count == 0){
      rezepte.id = await database.insert("rezept", rezepte.toMap());
    } else {
      await database.update("rezept", rezepte.toMap(), where: "id = ?", whereArgs: [rezepte.id]);
    }

    return rezepte;
  }

  //Daten aus Tabellen holen
  Future getAllRezepte(int id) async{
    List ergebnisse = await database.query("rezept", columns: Rezepte.spalten, where: "id=?",whereArgs: [id]);   // error on this line
    Rezepte rezepte = Rezepte.fromMap(ergebnisse[0]);

    return rezepte;
  }
}`

'_InternalLinkedHashMap' is not a subtype of type 'Map<String, dynamic>'

2018-03-27 17:01:47.649310+0200 Runner[557:230228] [VERBOSE-2:dart_error.cc(16)] Unhandled exception:
type '_InternalLinkedHashMap' is not a subtype of type 'Map<String, dynamic>' where
  _InternalLinkedHashMap is from dart:collection
  Map is from dart:core
  String is from dart:core

I get this error message when I run my Flutter app with Flutter channel dev. When I use Flutter channel beta it works

$ flutter doctor -v
[✓] Flutter (Channel dev, v0.2.4, on Mac OS X 10.13.3 17D102, locale de-DE)
    • Flutter version 0.2.4 at /Users/ralphbergmann/Downloads/flutter
    • Framework revision 3352a3fb48 (7 days ago), 2018-03-20 19:30:06 +0100
    • Engine revision 6280adbfb1
    • Dart version 2.0.0-dev.39.0.flutter-06949dc985

flutter packages get busy wait

After adding
dependencies:
flutter:
sdk: flutter
sqflite: any
flutter packages get busy wait and need to stop by deleting .lockfile in the flutter/bin
how can use this package in my project

Support for ASC or DESC?

Does sqflite support ordering in ascending or descending order?

SELECT
 *
FROM
 table
ORDER BY
 column_1 ASC,
 column_2 DESC;

How would I rewrite the SQL query above in sqflite?

The API provided by the library is

  Future<List<Map<String, dynamic>>> query(String table,
      {bool distinct,
      List<String> columns,
      String where,
      List whereArgs,
      String groupBy,
      String having,
      String orderBy,
      int limit,
      int offset})

Help on how to get started

Please can you kindly with me basic use cases of the library.

I'm very new to Flutter and I don't really know how to begin.

I tried the code below

Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "demo.db");

but got Invalid Directory.

I have a user_data.dart file which contains the following code

// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Snapshot from http://www.nasdaq.com/screening/company-list.aspx
// Fetched 2/23/2014.
// "Symbol","Name","LastSale","MarketCap","IPOyear","Sector","industry","Summary Quote",
// Data in stock_data.json

import 'dart:convert';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
//import 'package:sqflite/sqflite.dart';
import 'user_store.dart';

class User {
  String UserId;
  String UserName;
  String UserSurname;
  String UserEmail;
  String UserForgotPwrdLongToken;
  String UserForgotPwrdShortToken;
  String UserPhoneNumber;
  String UserActive;

  User(this.UserId, this.UserName, this.UserSurname, this.UserEmail, this.UserForgotPwrdLongToken,
      this.UserForgotPwrdShortToken, this.UserPhoneNumber, this.UserActive);

  User.fromJson(Map fields) {
    UserId = fields['UserId'];
    UserName = fields['UserName'];
    UserSurname = fields['UserSurname'];
    UserEmail = fields['UserEmail'];
    UserForgotPwrdLongToken = fields['UserForgotPwrdLongToken'];
    UserForgotPwrdShortToken = fields['UserForgotPwrdShortToken'];
    UserPhoneNumber = fields['UserPhoneNumber'];
    UserActive = fields['UserActive'];
  }
}

class UserData extends ChangeNotifier{
  String email;
  String password;
  Future<int> response;
  bool status;
  String message;

  http.Client _httpClient;
  bool get loading => _httpClient != null;

  UserData(this.email, this.password){
    _httpClient = createHttpClient();
    this.response = authentication();
  }

  authentication() async {
    String url = "http://localhost/api/user/login";
    String body = "email="+this.email+"&password="+this.password;
    Map headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "application/json"};

    var response = await _httpClient.post(url, body: body, headers: headers);
    print('Response status: ${response.body}');
    Map data = JSON.decode(response.body);

    // set the response details here
    this.status = data["status"];
    this.message = data["message"];

    if(data["status"]){

        **// Create tables for user table and store information**


    }

    notifyListeners();

  void _end() {
    _httpClient?.close();
    _httpClient = null;
  }
}

and user_store.dart

import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

final String tableUser = "user";
final String columnId = "_id";
final String columnTitle = "title";
final String columnDone = "done";

class UserStore {
  int id;
  String title;
  bool done;

  Map toMap() {
    Map map = {columnTitle: title, columnDone: done == true ? 1 : 0};
    if (id != null) {
      map[columnId] = id;
    }
    return map;
  }

  UserStore();

  UserStore.fromMap(Map map) {
    id = map[columnId];
    title = map[columnTitle];
    done = map[columnDone] == 1;
  }
}

class UserStoreProvider {
  Database db;

  Future open(String path) async {
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute('''
create table $tableUser ( 
  $columnId integer primary key autoincrement, 
  $columnTitle text not null,
  $columnDone integer not null)
''');
        });
  }

  Future<UserStore> insert(UserStore user) async {
    user.id = await db.insert(tableUser, user.toMap());
    return user;
  }

  Future<UserStore> getTodo(int id) async {
    List<Map> maps = await db.query(tableUser,
        columns: [columnId, columnDone, columnTitle],
        where: "$columnId = ?",
        whereArgs: [id]);
    if (maps.length > 0) {
      return new UserStore.fromMap(maps.first);
    }
    return null;
  }

  Future<int> delete(int id) async {
    return await db.delete(tableUser, where: "$columnId = ?", whereArgs: [id]);
  }

  Future<int> update(UserStore user) async {
    return await db.update(tableUser, user.toMap(),
        where: "$columnId = ?", whereArgs: [user.id]);
  }

  Future close() async => db.close();
}

Support Dart 2.0

Looks like the strong typing in 2.0 stops the library from running:

E/flutter ( 5976): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 5976): type '_Future' is not a subtype of type 'Future<int>' where
E/flutter ( 5976):   _Future is from dart:async
E/flutter ( 5976):   Future is from dart:async
E/flutter ( 5976):   int is from dart:core
E/flutter ( 5976):
E/flutter ( 5976): #0      _openDatabase (package:sqflite/sqflite.dart:365:10)
E/flutter ( 5976): #1      openDatabase (package:sqflite/sqflite.dart:407:26)

Looks like the issue is that you have this method Future wrapDatabaseException(action()) async { which gets used in most calls like this:

Future<int> _openDatabase(String path) {
  return wrapDatabaseException(() {

so you're casting the Future<dynamic> to Future<int> which causes the new type checking to blow up. I tried a couple things to see if I could fix it and maybe give you a pull request, but I've been using dart for about 3 days now and have no idea how you can cast these (just ramming as Future<int> in there also blows up) in some way that won't require rewriting a bunch of it. The only thing that worked was basically changing all of these methods to return Future<dynamic> which sucks.

Great work on sqflite library! Made it super easy to screw around with sqlite in my project. Thanks and let me know if there's some way I can help

onConfigure

Need onConfigure support to enable foreign keys and execute other pragmas:

onConfigure
added in API level 16
void onConfigure (SQLiteDatabase db)
Called when the database connection is being configured, to enable features such as write-ahead logging or foreign key support.

This method is called before onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int), onDowngrade(SQLiteDatabase, int, int), or onOpen(SQLiteDatabase) are called. It should not modify the database except to configure the database connection as required.

This method should only call methods that configure the parameters of the database connection, such as enableWriteAheadLogging() setForeignKeyConstraintsEnabled(boolean), setLocale(Locale), setMaximumSize(long), or executing PRAGMA statements.

docs

database is locked

I suddenly came across this error.
It works only for the first time, then it gives error: database is locked.
below is what I see in the terminal:

E/SQLiteDatabase( 6785): Failed to open database '/data/user/0/com.arnold.knowbuddy/app_flutter/demo.db'.
E/SQLiteDatabase( 6785): android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5): , while compiling: PRAGMA journal_mode
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:634)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:320)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:294)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:215)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:808)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:793)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:696)
E/SQLiteDatabase( 6785): 	at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:711)
E/SQLiteDatabase( 6785): 	at com.tekartik.sqflite.SqflitePlugin$Database.open(SqflitePlugin.java:805)
E/SQLiteDatabase( 6785): 	at com.tekartik.sqflite.SqflitePlugin$Database.access$900(SqflitePlugin.java:796)
E/SQLiteDatabase( 6785): 	at com.tekartik.sqflite.SqflitePlugin.onOpenDatabaseCall(SqflitePlugin.java:682)
E/SQLiteDatabase( 6785): 	at com.tekartik.sqflite.SqflitePlugin.onMethodCall(SqflitePlugin.java:779)
E/SQLiteDatabase( 6785): 	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:191)
E/SQLiteDatabase( 6785): 	at io.flutter.view.FlutterNativeView.handlePlatformMessage(FlutterNativeView.java:136)
E/SQLiteDatabase( 6785): 	at android.os.MessageQueue.nativePollOnce(Native Method)
E/SQLiteDatabase( 6785): 	at android.os.MessageQueue.next(MessageQueue.java:325)
E/SQLiteDatabase( 6785): 	at android.os.Looper.loop(Looper.java:147)
E/SQLiteDatabase( 6785): 	at android.app.ActivityThread.main(ActivityThread.java:6637)
E/SQLiteDatabase( 6785): 	at java.lang.reflect.Method.invoke(Native Method)
E/SQLiteDatabase( 6785): 	at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
E/SQLiteDatabase( 6785): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
E/flutter ( 6785): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 6785): DatabaseException(database is locked (code 5): , while compiling: PRAGMA journal_mode)
E/flutter ( 6785): #0      wrapDatabaseException (package:sqflite/src/exception.dart:82:7)
E/flutter ( 6785): <asynchronous suspension>
E/flutter ( 6785): #1      SqfliteDatabase._openDatabase (package:sqflite/src/database.dart:458:12)
E/flutter ( 6785): #2      SqfliteDatabase.open (package:sqflite/src/database.dart:506:28)
E/flutter ( 6785): <asynchronous suspension>
E/flutter ( 6785): #3      openDatabase (package:sqflite/src/database.dart:610:19)
E/flutter ( 6785): #4      openDatabase (package:sqflite/sqflite.dart:280:10)
E/flutter ( 6785): #5      dbInit (package:knowbuddy/backend/database.dart:20:22)
E/flutter ( 6785): <asynchronous suspension>
E/flutter ( 6785): #6      _HomePageState.initState (package:knowbuddy/pages/home_page.dart:134:5)
E/flutter ( 6785): #7      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3734:58)
E/flutter ( 6785): #8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter ( 6785): #9      Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter ( 6785): #10     Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter ( 6785): #11     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3636:16)
E/flutter ( 6785): #12     Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5)
E/flutter ( 6785): #13     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5)
E/flutter ( 6785): #14     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter ( 6785): #15     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter ( 6785): #16     Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter ( 6785): #17     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4637:14)
E/flutter ( 6785): #18     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter ( 6785): #19     Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter ( 6785): #20     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4637:14)
E/flutter ( 6785): #21     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter ( 6785): #22     Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter ( 6785): #23     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4637:14)
E/flutter ( 6785): #24     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter ( 6785): #25     Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter ( 6785): #26     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4637:14)
E/flutter ( 6785): #27     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter ( 6785): #28     Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter ( 6785): #29     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3636:16)
E/flutter ( 6785): #30     Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5)
E/flutter ( 6785): #31     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5)
E/flutter ( 6785): #32     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3752:11)
E/flutter ( 6785): #33     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter ( 6785): #34     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter ( 6785): #35     Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter ( 6785): #36     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3636:16)
E/flutter ( 6785): #37     Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5)
E/flutter ( 6785): #38     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5)
E/flutter ( 6785): #39     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
E/flutter ( 6785): #40     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
E/flutter ( 6785): #41     Element.updateChild (package:flutter/src/widgets/framework.dart:2693:12)
E/flutter ( 6785): #42     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3636:16)
E/flutter ( 6785): #43     Element.rebuild (package:flutter/src/widgets/framework.dart:3478:5)
E/flutter ( 6785): #44     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3605:5)
E/flutter ( 6785): #45     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3752:

flutter doctor


[✓] Flutter (Channel beta, v0.2.8, on Linux, locale en_IN)
[!] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    ✗ Android license status unknown.
[✓] Android Studio (version 3.0)
[✓] IntelliJ IDEA Community Edition (version 2017.3)
[✓] VS Code (version 1.21.1)
[✓] Connected devices (1 available)

! Doctor found issues in 1 category.


Help on Catching DatabaseException

I've been unsuccessful at catching a sqflite SQL error that thows a DatabaseException.

For example, this code:

Future<String> getData() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, globals.databaseName);
Database db = await openDatabase(path);
List results = await db.rawQuery("mal formed sql on purpose");
}

throws the following error.. The console shows:

E/SQLiteLog( 7908): (1) near "mal": syntax error

What I want to do is be able to catch SQL errors and handle them.

I did try this:

try {
  List results = await db.rawQuery("mal formed sql on purpose");
} catch (e) {
  print(e);
}

but it results in the same error.

E/SQLiteLog( 3148): (1) near "mal": syntax error

And I've tried .then and .catchError - but not getting that to work either.

Thanks in advance for the help!

Issue with not using tic symbols for field names in a query

Hello

I get thrown some errors if I don't use ` in the query fields . For example:

this works:

db.execute("CREATE TABLE IF NOT EXISTS quiz (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `group` INTEGER, `name` TEXT)")

this doesn't work:

db.execute("CREATE TABLE IF NOT EXISTS quiz (id INTEGER PRIMARY KEY AUTOINCREMENT, group INTEGER, name TEXT)")

This wouldn't be a huge issue, because I could just wrap the field names in `. The issue comes if I do:

await _db.insert("quiz", quiz.toMap())

in this case I get:

DatabaseException(near "group": syntax error (Sqlite code 1): , while compiling: INSERT INTO quiz (group, name) VALUES (?, ?), (OS error - 2:No such file or directory))

If I write the raw query, then the insert works, but that defies using the sugar method, like _db.insert(...

await _db.rawInsert('INSERT INTO quiz (`group`, `name`) VALUES(?, ?)', [data['group'], data['name']]);

Basically the field names don't get wrapped in ` symbols.

Any ideas?

Here is the full error trace:

E/flutter (26309): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (26309): DatabaseException(near "group": syntax error (Sqlite code 1): , while compiling: INSERT INTO quiz (group, name) VALUES (?, ?), (OS error - 2:No such file or directory))
E/flutter (26309): #0      wrapDatabaseException (package:sqflite/src/exception.dart:52:7)
E/flutter (26309): <asynchronous suspension>
E/flutter (26309): #1      Database.rawInsert.<anonymous closure> (package:sqflite/sqflite.dart:106:14)
E/flutter (26309): #2      SynchronizedLock._run.<anonymous closure>.<anonymous closure> (package:synchronized/src/synchronized_impl.dart:86:29)
E/flutter (26309): #3      _rootRun (dart:async/zone.dart:1126)
E/flutter (26309): #4      _CustomZone.run (dart:async/zone.dart:1023)
E/flutter (26309): #5      runZoned (dart:async/zone.dart:1501)
E/flutter (26309): #6      SynchronizedLock._run.<anonymous closure> (package:synchronized/src/synchronized_impl.dart:84:14)
E/flutter (26309): #7      new Future.sync (dart:async/future.dart:222)
E/flutter (26309): #8      SynchronizedLock._run (package:synchronized/src/synchronized_impl.dart:83:16)
E/flutter (26309): #9      SynchronizedLock.synchronized.run (package:synchronized/src/synchronized_impl.dart:147:14)
E/flutter (26309): #10     SynchronizedLock.synchronized (package:synchronized/src/synchronized_impl.dart:157:17)
E/flutter (26309): #11     Database.writeSynchronized (package:sqflite/sqflite.dart:288:23)
E/flutter (26309): #12     Database.rawInsert (package:sqflite/sqflite.dart:105:12)
E/flutter (26309): #13     Database.insert (package:sqflite/sqflite.dart:124:12)
E/flutter (26309): #14     DatabaseClient.insertIntoQuiz (package:myapp/models/databaseClient.dart:27:25)

How to access an already made database?

I have a folder named assets which contains my database. How do i copy it to the app folder? When I declare that as an asset in pubspec.yaml I get the following exception. How do I access it?

Oops; flutter has exited unexpectedly.
Dart_NewStringFromUTF8 expects argument 'str' to be valid UTF-8.

FAILURE: Build failed with an exception.

  • Where:
    Script '/home/power/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 320

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

Process 'command '/home/power/flutter/bin/flutter'' finished with non-zero exit value 255

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
    Finished with error: Gradle build failed: 1

Transaction exceptions handling

I did not notice any "beginTransaction" methods in android java code. How are exceptions while in a transaction handled? What will happen if an app terminates in a middle of a transaction?

Unnamed columns causes problem with `print()`

If you do, for example, a GROUP BY query without aliasing aggregated columns, rawQuery returns null. For example,

await db.rawQuery('''
      select t.one, GROUP_CONCAT(t.another)
      from tbl t
      GROUP BY t.one''')

gives no way to access that unaliased column (?) - I initially thought it didn't return anything at all because print outputs nothing for it, but that doesn't seem to be the case now...

await db.rawQuery('''
      select t.one, GROUP_CONCAT(t.another) as anothers
      from tag t
      GROUP BY t.one''')

works as expected. Thinking through the API (even without looking at the code), this makes some sense but should probably be documented and either handled or thrown.

I should add that I've tested this on iOS but not Android yet - I've had issues with gradle versions on Android I haven't sorted through just yet.

Error when run sample on iOS with " s.dependency 'FMDB', '~> 2.7.2' "

This is console:

Resolving dependencies of Podfile
[!] CocoaPods could not find compatible versions for pod "FMDB":
In Podfile:
sqflite (from /Users/cytech/Downloads/sqflite-master/ios) was resolved to 0.0.1, which depends on
FMDB (~> 2.7.2)

None of your spec sources contain a spec satisfying the dependency: `FMDB (~> 2.7.2)`.

If remove '~> 2.7.2' in file sqflite.podspec then it work.
So what should i do?

Error compiling this repo

Hi,

Thanks for your work on this project.

I was trying to use your project, however I keep getting an error.
To try and troubleshoot I cloned your project, and found I get the same issue.

I am using a Mac, and the steps I took:

  1. Upgraded flutter-sdk
  2. Ran flutter doctor
  3. cloned your repo
  4. open project in Android Studio
  5. ran flutter packages get
  6. attempted a compile (using Android Emulator)

The console error message below:

Launching lib/main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
* Error running Gradle:
Exit code 1 from: /Users/Home/Flutter/sqflite/example/android/gradlew app:properties:
Parallel execution is an incubating feature.

BUILD FAILED

Total time: 1.298 secs


FAILURE: Build failed with an exception.

* Where:
Build file '/Users/Home/Flutter/sqflite/example/android/build.gradle' line: 3

* What went wrong:
A problem occurred evaluating root project 'android'.
> Could not find method google() for arguments [] on repository container.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Finished with error: Please review your Gradle project setup in the android/ folder.

Please support DateTime

For a Database DateTime is an essential type especially with sorting please support DateTime.
I know that SQLite doesn't support a special Datetype but the Dart interface should do it

Query returns empty results with not primary key condition

i'm trying to execute next query in my flutter application:
return await _db.query("npa", columns: ["id", "title" ,"identifier"], where: '"identifier" = ?', whereArgs: ["0008120150514"]);
but the results is always - empty QueryResultSet[].

If i'm trying to do the same with the id field and integer value like
return await _db.query("npa", columns: ["id", "title" ,"identifier"], where: '"id" = ?', whereArgs: [215]);

  • works fine.

I've got the npa.identifier = "0008120150514" (id : 215) in database, so the trouble not in data existense.

nullColumnHack required

If a table contains no columns except autoincremented id, so no data need to be provided when inserted a row "nullColumnHack required when inserting no data" error is thrown.

Exception Code to be part of DatabaseException

Hi,

I wanted to write an UPSERT using sqflite
My approach was to try to insert and if insert fails with "UNIQUE constraint failed" I will try to update
To catch the error i wrote something like:

try{
    await db.rawInsert('INSERT INTO MY_TABLE (col1 , col2) VALUES ( ?, ?)',['value1','value2']);
}
on DatabaseException catch (e){
    print(e);
}

Now, the insert fails as expected and i get the print as

DatabaseException(UNIQUE constraint failed:....
(Sqlite code 1555), (OS error - 2:No such file or directory)) sql.....
......

The exception object does not have a code as a member.
Comparing that with (in this case with 1555) would have helped me to take appropriate action, fire an update.
I would not like to compare message strings.

It would have been great if the sqlite error code could have been part of the derived class viz. DatabaseException

Regards
Dhaval

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.