Giter Club home page Giter Club logo

sqlcool's Introduction

Sqlcool

pub package Build Status Coverage Status

A database helper library for Sqflite. Forget about implementation details and focus on the business logic.

  • Simple: easy api for crud operations
  • Reactive: stream of changes, select bloc
  • Adaptative: plug custom models into the database

Check the documentation or the api doc for usage instructions

Simple crud

Define the database schema

import 'package:sqlcool/sqlcool.dart';

Db db = Db();
// define the database schema
DbTable category = DbTable("category")..varchar("name", unique: true);
DbTable product = DbTable("product")
   ..varchar("name", unique: true)
   ..integer("price")
   ..text("descripton", nullable: true)
   ..foreignKey("category", onDelete: OnDelete.cascade)
   ..index("name");
List<DbTable> schema = [category, product];

Initialize the database

String dbpath = "db.sqlite"; // relative to the documents directory
try {
  await db.init(path: dbpath, schema: schema);
} catch(e) {
  rethrow;
}

Insert

final Map<String, String> row = {name: "My item"};
try {
  int id = await db.insert(table: "category", row: row)
} catch(e) {
  rethrow;
}

Select

try {
  List<Map<String, dynamic>> rows = await db.select(
    table: "product",
    limit: 20,
    columns: "id,name",
    where: "name LIKE '%something%'",
    orderBy: "name ASC",
  );
} catch (e) {
  rethrow;
}

Update

try {
  int numRowsUpdated = await db.update(table: "category", 
   row: row, where: "id=1");
} catch(e) {
  rethrow;
}

Delete

try {
  await db.delete(table: "category", where: "id=3");
} catch(e) {
  rethrow;
}

Join queries

try {
  final data = await db.join(
   table: "product",
   columns: "product.name,price,category.name as category_name",
   joinTable: "category",
   joinOn: "product.category=category.id");
} catch(e) {
  rethrow;
}

Join on multiple tables

try {
  final data = db.mJoin(table: "product", joinsTables: <String>[
   "category",
   "manufacturer"
 ], joinsOn: <String>[
   "product.category=category.id",
   "product.manufacturer=manufacturer.id"
 ]);
} catch(e) {
  rethrow;
}

Reactivity

Changefeed

A stream of database change events is available. Inspired by Rethinkdb

import 'dart:async';
import 'package:sqlcool/sqlcool.dart';

StreamSubscription changefeed;

changefeed = db.changefeed.listen((change) {
   print("Change in the database:");
   print("Query: ${change.query}");
   if (change.type == DatabaseChange.update) {
     print("${change.value} items updated");
   }
 });
// Dispose the changefeed when finished using it
changefeed.cancel();

Reactive select bloc

The bloc will rebuild itself on any database change because of the reactive parameter set to true:

import 'package:flutter/material.dart';
import 'package:sqlcool/sqlcool.dart';

class _PageSelectBlocState extends State<PageSelectBloc> {
  SelectBloc bloc;

  @override
  void initState() {
    super.initState();
    this.bloc = SelectBloc(
        table: "items", orderBy: "name", reactive: true);
  }

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("My app")),
      body: StreamBuilder<List<Map>>(
          stream: bloc.items,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              // the select query has not found anything
              if (snapshot.data.length == 0) {
                return Center(child: const Text("No data"));
              }
              // the select query has results
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    var item = snapshot.data[index];
                    return ListTile(
                      title: GestureDetector(
                        child: Text(item["name"]),
                        onTap: () => someFunction()),
                    );
                  });
            } else {
              // the select query is still running
              return CircularProgressIndicator();
            }
          }),
    );
  }
}

class PageSelectBloc extends StatefulWidget {
  @override
  _PageSelectBlocState createState() => _PageSelectBlocState();
}

Database models

New in 4.0.0: define models that have database methods. The main advantage of this is to use only typed model data and avoid the type conversions from maps for every query. It directly plugs custom models into the database. Example:

In schema.dart:

final carTable = DbTable("car")
  ..varchar("name")
  ..integer("max_speed")
  ..real("price")
  ..integer("year")
  ..boolean("is_4wd", defaultValue: false)
  ..foreignKey("manufacturer", onDelete: OnDelete.cascade);

final manufacturerTable = DbTable("manufacturer")..varchar("name");

In car_model.dart:

import 'package:sqlcool/sqlcool.dart';
// the database schema
import 'schema.dart';
// another model
import 'manufacturer_model.dart';

class Car with DbModel {
  Car(
      {this.id,
      this.name,
      this.maxSpeed,
      this.price,
      this.year,
      this.is4wd,
      this.manufacturer});

  /// define some class properties

  final String name;
  final int maxSpeed;
  final double price;
  final DateTime year;
  final bool is4wd;
  // this is a foreign key to another model
  Manufacturer manufacturer;

  /// [DbModel] required overrides

  @override
  int id;

  /// the [Db] used
  /// pass it your main db
  @override
  Db get db => db;

  /// the table schema representation
  /// check example/pages/dbmodels/schema.dart
  @override
  DbTable get table => carTable;

  /// serialize a row to the database
  @override
  Map<String, dynamic> toDb() {
    // we want the foreign key to be recorded
    assert(manufacturer?.id != null);
    final row = <String, dynamic>{
      "name": name,
      "max_speed": maxSpeed,
      "price": price,
      "year": year.millisecondsSinceEpoch,
      "is_4wd": is4wd,
      "manufacturer": manufacturer.id
    };
    return row;
  }

  /// deserialize a row from database
  @override
  Car fromDb(Map<String, dynamic> map) {
    final car = Car(
      id: map["id"] as int,
      name: map["name"].toString(),
      maxSpeed: map["max_speed"] as int,
      price: map["price"] as double,
      year: DateTime.fromMillisecondsSinceEpoch(map["year"] as int),
      is4wd: (map["is_4wd"].toString() == "true"),
    );
    // the key will be present only with join queries
    // in a simple select this data is not present
    if (map.containsKey("manufacturer")) {
      car.manufacturer =
          Manufacturer().fromDb(map["manufacturer"] as Map<String, dynamic>);
    }
    return car;
  }

  /// Create a static join method for convenience

  static Future<List<Car>> selectRelated({String where, int limit}) async {
    final cars = List<Car>.from(
        await Car().sqlJoin(where: where, limit: limit, verbose: true));
    return cars;
  }
}

Then use the models:

/// car is an instance of [Car]
await car.sqlInsert();
await car.sqlUpdate();
await car.sqlUpsert();
await car.sqlDelete();
final cars = Car.selectRelated(where: "speed>200");
// foreign keys are retrieved as model instances
print(cars[0].manufacturer.name);

Using this

  • Sqlview: admin view and infinite list view
  • Kvsql: a type safe key/value store
  • Geopoint sql: sql operations for geospatial data

sqlcool's People

Contributors

adam-ashored avatar bandonovski avatar codedraughtsman avatar fusion44 avatar synw 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

sqlcool's Issues

Add or modify fields

Hello, I am very happy to use the plugin you developed, it is really great. But I encountered a small problem. How do I add or modify fields after the data table is initialized to make the old data table be overwritten?
Thank you

Unable to get data from SelectBloc

Following your example for SelectBloc, I'm unable to get data from it.
It's just infinitely stuck on the CircularProgressIndicator()

Changefeed doesn't seem to notice changes, and there is data present in the table before and after SelectBloc is initialized, but despite that fact I cannot get it to build my Listview.

Timing everything out, it actually looks like my database is initialized after SelectBloc queries against it.
I'm not sure if that effects how it works.

  @override
  void initState() {
    print("Step 1, Init DB");
    String dbpath = "convos.sqlite";
    db.init(path: dbpath, verbose: true).catchError((e) {
      print("Error initializing the database: $e");
    });
    print("Step 2, SelectBloc");
    this.bloc = SelectBloc(table: "convos", orderBy: "time DESC", verbose: true, reactive: true);
    print("Step 3, initState super");
    super.initState();

    List all_data = db.select(table: 'convos');
    print(all_data);
I/flutter (25748): Step 1, Init DB
I/flutter (25748): Step 2, SelectBloc
I/flutter (25748): SELECT * FROM convos ORDER BY time DESC
I/flutter (25748): Step 3, initState super
I/flutter (25748): INITIALIZING DATABASE at /data/user/0/io.dah.sippy2/app_flutter/convos.sqlite
I/flutter (25748): OPENING DATABASE
I/flutter (25748): [{number: XXXXYYY, time: 15503805177.67, message: Hello from SQLITE, to_num: XXXXXXX}, {number: YYYYXXX, time: 15503805177.73, message: Hello from HELL!?, to_num: XXXXXXX}]

Doubt about Primary Key

Imagine the following table:

final calendario = DbTable ("Calendario")
   ..integer ("CalID", unique: true, nullable: false)
   ..varchar ("CalTipo", unique: true, nullable: false)
   ..integer ("CalEntDia", nullable: false)
   ..integer ("CalEntMes", nullable: false)
   ..integer ("CalEntAno", nullable: false)
   ..varchar ("CalDescricao", nullable: false)
   ..integer ("CalVencDia", nullable: false)
   ..integer ("CalVencMes", nullable: false)
   ..integer ("CalVencAno", nullable: false)
   ..varchar ("CalURL", nullable: false)
   ..integer ("CalOecID", nullable: false);

Question when defining the column CalID and CalTipo as unique = true does he understand that it is a composite primary key? If not, how do I define this situation?

Backup database

I want to offer database backup functionality, in which user can either download DB file or send it via email.

What I have tried is,

Db db = Db();
var bytes = await db.file.readAsBytes();
print(bytes.length); // it prints: 4096

WcFlutterShare.share(
        sharePopupTitle: 'Take Backup',
        fileName: 'db.bkup',
        mimeType: 'application/x-sqlite3',
        bytesOfFile: bytes);

Here I am using third party library for sharing. Here, I can successfully send db.bkup file to email. But, when I open this file in SqliteBrowser, I can't see any table & it's just empty database.

5.0.0 preview : type safe api

A new type safe api has landed in master and will be introduced in version 5.0.0. Instead of dealing with maps it provides DbRow and typed DbRecord objects.

Note: the original api will still work, backward compatibility is guarantied. The example has been updated to use this api. Feel free to post what you think about this

Type safe api

Create a schema:

DbTable category = DbTable("category")..varchar("name", unique: true);
DbTable product = DbTable("product")
   ..varchar("name", unique: true)
   ..integer("price")
   ..text("descripton", nullable: true)
   ..foreignKey("category", onDelete: OnDelete.cascade)
   ..index("name");
List<DbTable> schema = [category, product];

Initialize a database:

final SqlDb db = SqlDb();
String dbpath = "db.sqlite"; // relative to the documents directory
try {
  await db.init(path: dbpath, schema: schema);
} catch(e) {
  rethrow;
}

Insert

try {
  final lastInsertedId = await db.insert(
      table: "product",
      row: DbRow(<DbRecord>[
        DbRecord<String>("name", "Product 2"),
        DbRecord<int>("price", 50),
        DbRecord<int>("category", 1),
      ]));
} catch (e) {
  rethrow;
}

Select

try {
  final List<DbRow> rows = await db.select(
      table: "product",
      limit: 20,
      columns: "id,name",
      where: "name LIKE '%something%'",
      orderBy: "name ASC");
  rows.forEach((row) {
    final int id = row.record<int>("id");
    final String name = row.record<String>("name");
    print("Product : $id $name");
  });
} catch (e) {
  rethrow;
}

Problem with db.query and reactive update

I was observing a problem in updating the data using reactive, when you for example execute the command db.query () and for example execute an update I realized that the stream process is not updated, however if I use db.update the update occurs I do not know if it would be a bug or if this is really the behavior.

Roadmap for 4.0.0

New features

  • Add informative getters to the schema
  • Join on multiple foreign keys
  • Database models: use a mixin to give any model methods to interact with the database
  • Foreign key support for database models

Tests, doc and examples

  • Test the new features
  • Examples for the new features
  • Document the new features
  • Refresh the documentation and add missing doc
  • Write more tests and increase the coverage
  • Better presentation for the example app homepage

Database models

This release will introduce the database models feature: any model can use a DbModel mixin to get database crud methods: select, delete, insert, upsert. Some serializers must be written in the model: fromDb and toDb:

class Car with DbModel {
  Car({this.id,
       this.name,
       this.price,
       this.year});

  final String name;
  final double price;
  final DateTime year;

 @override
  int id;

@override
  Db get db => conf.db;

  @override
  DbTable get table => carTable;

  @override
  Map<String, dynamic> toDb() => <String, dynamic>{
        "name": name,
        "price": price,
        "year": year.millisecondsSinceEpoch
      };

  @override
  Car fromDb(Map<String, dynamic> map) => Car(
        id: map["id"] as int,
        name: map["name"].toString(),
        price: map["price"] as double,
        year: DateTime.fromMillisecondsSinceEpoch(map["year"] as int));
}

/// In schemas.dart declare the schema as usual

final carTable = DbTable("car")
          ..varchar("name")
          ..real("price")
          ..integer("year"));
  }

/// initialize the database with model schemas

final db = Db();
db.init(path: "mydb.sqlite", schema = <DbTable>[carTable]);

Use the model's crud methods to query the database:

/// car is an instance of Car
await car.sqlInsert();
await car.sqlUpdate();
await car.sqlUpsert();
await car.sqlDelete();
// select
final cars = List<Car>.from(await Car().sqlSelect(where: "price<25000"));

Check the example for foreign key support

This way no need to deal with maps decoding and encoding when doing database operations: all the data is of the model type

Getting query error in logcat after DB init called , using v5.1.1

D/Sqflite (22844): [1,Sqflite(1100)] CREATE TABLE IF NOT EXISTS tunes (
D/Sqflite (22844): id INTEGER PRIMARY KEY,
D/Sqflite (22844): tuneId VARCHAR NOT NULL,
D/Sqflite (22844): artist TEXT NOT NULL,
D/Sqflite (22844): track TEXT NOT NULL,
D/Sqflite (22844): bpm VARCHAR,
D/Sqflite (22844): key VARCHAR,
D/Sqflite (22844): deleted BOOLEAN DEFAULT false,
D/Sqflite (22844): verified BOOLEAN DEFAULT false,
D/Sqflite (22844): verified_id TEXT NOT NULL DEFAULT ,
D/Sqflite (22844): source INTEGER NOT NULL,
D/Sqflite (22844): createdAt INTEGER NOT NULL,
D/Sqflite (22844): updatedAt INTEGER,
D/Sqflite (22844): album TEXT,
D/Sqflite (22844): comment TEXT,
D/Sqflite (22844): genre TEXT,
D/Sqflite (22844): time TEXT,
D/Sqflite (22844): rating TEXT,
D/Sqflite (22844): dateAdded TEXT
D/Sqflite (22844): )
E/SQLiteLog(22844): (1) near ",": syntax error
D/Sqflite (22844): [1,Sqflite(1100)] ROLLBACK
I/flutter (22844): error DatabaseException(near ",": syntax error (code 1 SQLITE_ERROR): , while compiling: CREATE TABLE IF NOT EXISTS tunes (
I/flutter (22844): id INTEGER PRIMARY KEY,
I/flutter (22844): tuneId VARCHAR NOT NULL,
I/flutter (22844): artist TEXT NOT NULL,
I/flutter (22844): track TEXT NOT NULL,
I/flutter (22844): bpm VARCHAR,
I/flutter (22844): key VARCHAR,
I/flutter (22844): deleted BOOLEAN DEFAULT false,
I/flutter (22844): verified BOOLEAN DEFAULT false,
I/flutter (22844): verified_id TEXT NOT NULL DEFAULT ,
I/flutter (22844): source INTEGER NOT NULL,
I/flutter (22844): createdAt INTEGER NOT NULL,
I/flutter (22844): updatedAt INTEGER,
I/flutter (22844): album TEXT,
I/flutter (22844): comment TEXT,
I/flutter (22844): genre TEXT,
I/flutter (22844): time TEXT,
I/flutter (22844): rating TEXT,
I/flutter (22844): dateAdded TEXT
I/flutter (22844): )) sql 'CREATE TABLE IF NOT EXISTS tunes (
I/flutter (22844): id INTEGER PRIMARY KEY,
I/flutter (22844): tuneId VARCHAR NOT NULL,
I/flutter (22844): artist TEXT NOT NULL,
I/flutter (22844): track TEXT NOT NULL,
I/flutter (22844): bpm VARCHAR,
I/flutter (22844): key VARCHAR,
I/flutter (22844): deleted BOOLEAN DEFAULT false,
I/flutter (22844): verified BOOLEAN DEFAULT false,
I/flutter (22844): verified_id TEXT NOT NULL DEFAULT ,
I/flutter (22844): source INTEGER NOT NULL,
I/flutter (22844): createdAt INTEGER NOT NULL,
I/flutter (22844): updatedAt INTEGER,
I/flutter (22844): album TEXT,
I/flutter (22844): comment TEXT,
I/flutter (22844): genre TEXT,
I/flutter (22844): time TEXT,
I/flutter (22844): rating TEXT,
I/flutter (22844): dateAdded TEXT
I/flutter (22844): )' args []} during open, closing...
D/Sqflite (22844): [1,main(2)] closing 1 /data/user/0/com.myapp/app_flutter/myapp.sqlite
D/Sqflite (22844): [1,Sqflite(1100)] closing database Thread[Sqflite,5,main]
D/Sqflite (22844): [1,Sqflite(1100)] stopping threadThread[Sqflite,5,main]
I/flutter (22844): Closure: () => String from Function 'toString':.
V/FA (22844): Inactivity, disconnecting from the service

Error serialize object complex

Hi @synw .
I'm having trouble bringing in a serialized model with a relationship from another model class,below I attach my case..

MY CLASS MODEL IS:

class ProductoItem with DbModel {

// Propiedades

String unidadMedida;
double cantidad;
double precioUnitario;
double descuento;
ProductoModel producto;
Pedido pedido;

ProductoItem(
{this.id,
this.unidadMedida,
this.cantidad,
this.precioUnitario,
this.descuento,
this.producto,
this.pedido});

/// [DbModel] required overrides
///
@OverRide
int id;

@OverRide
Db get db => conf.db;

@override

DbTable get table => productoPedidoTable;

/// serialize a row to the database
@OverRide
Map<String, dynamic> toDb() {
// we want the foreign key to be recorded
assert(pedido?.id != null);
assert(producto?.id!=null);
final row = <String, dynamic>{
'unidadMedida': unidadMedida,
'cantidad': cantidad,
'precioUnitario': precioUnitario,
'descuento': descuento,
'producto': producto.id,
"pedido": pedido.id
};
return row;
}

/// deserialize a row from database
@OverRide
ProductoItem fromDb(Map<String, dynamic> map) {
final producto = ProductoItem(
id: map["id"] as int,
unidadMedida: map["unidadMedida"].toString(),
cantidad: map["cantidad"] as double,
precioUnitario: map["precioUnitario"] as double,
descuento: map["descuento"] as double,
);
// the key will be present only with join queries
// in a simple select this data is not present
if (map.containsKey("pedido")) {
producto.pedido =
Pedido().fromDb(map["pedido"] as Map<String, dynamic>);
}

  if (map.containsKey("producto")) {
      producto.producto =
          ProductoModel().fromDb(map["producto"] as Map<String, dynamic>);
  }
return producto;

}

/// Create a static join method for convenience

static Future<List> selectRelated({String where, int limit}) async {
final cars = List.from(
await ProductoItem().sqlJoin(where: where, limit: limit));
return cars;
}

}

when using this query to see the attributes of the product, I get an exception

final c = await ProductoItem.selectRelated();
print("Found ${c[0].producto.nombre} cars: $c");

Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The getter 'name' was called on null.
Receiver: null
Tried calling: name)

I don't know why throws that exception but in the repository on github I could not perform either, but in theory it should work according to the doc ( https://pub.dev/packages/sqlcool)

Problem with StreamBuilder

Good Morning

Guys I am in need of help, first I would like to thank you for creating a fantastic plugin that sqlcool helped me a lot, however I am setting up a chat screen using sqlcool + dashchat where I create my block using sqlcool I pass to my streambuilder and consequently for dashchat, the first time the data is displayed on the screen perfectly.

However I use Firebase Messanging for push I intercept the onmessage event in Firebase Messaging and insert it into my database using sqlcool, this works perfectly but the stream created does not update. I already tried to put a break point in some places and unfortunately the screen is not updated anyone would know how to tell me how to proceed to resolve this.

Just in advance I got sqlcool using the same feature for a simpler notification screen and it worked normally but I can't update it

Nested StreamBuilder not working

When I am using two streambuilder of SelectBloc one inside another. The inner stream builder is not working.
The inner stream builder is always returning text widget.

StreamBuilder<List<Map>>(
                stream: filterBloc.items,
                builder: (BuildContext context, AsyncSnapshot filterSnapshot) {
                  if(filterSnapshot.hasData) {
                    if(filterSnapshot.data.length==0) {
                      return Center(
                        child: Text('Downloading Data'),
                      );
                    }
                    Map<String, int> filterMap = Map<String, int>();
                    for(int i=0; i<filterSnapshot.data.length; i++)
                      filterMap[filterSnapshot.data[i]['name']] = filterSnapshot.data[i]['enabled'];
                    return StreamBuilder<List<Map>>(
                      stream: modelBloc.items,
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        if(snapshot.hasData) {
                          if(snapshot.data.length==0) {
                            return Center(
                              child: Text('Downloading Data'),
                            );
                          }
                          return ListView.builder(
                            shrinkWrap: true,
                            itemCount: snapshot.data.length,
                            itemBuilder: (context, index) {
                              Model item = Model().fromDb(snapshot.data[index]);
                              return ContestCard(size: size, item: item);
                            },
                          );
                        }
                        return Text('Loading');
                      },
                    );
                  }
                  return Container();
                },
              ),

Question about Map<String, String> for row

Hi there,

Why is it that a DB row has to be a Map<String, String>. I'm having quite a bit of a problem serialising to and from the actual value and knowing which values were int's before I put them into the DB.

I'm reverting back to using the database on it's own but I was wondering if you had a particular reason?

Also how do you currently know to convert to and form an integer if the value that goes in it a null value. I'm using freezed and json serialize to generate my models I'm not writing them by hand.

Updates to null don't work when using the model approach

I'm implementing an undo operation where I'm setting previous non-nullable fields to null. I'm using the model approach.

It looks something like this:

  Future<GearEvent> recoverGear({
    @required Position pos,
    @required String deviceId,
    @required Position posEnd,
  }) async {
    await (this
          ..recover = pos
          ..recoverEnd = posEnd
          ..recoverDeviceId = deviceId)
        .sqlUpdate(verbose: true);
    return this;
  }

  Future<GearEvent> undoRecover() async {
    await (this
          ..recover = null
          ..recoverEnd = null
          ..recoverDeviceId = null)
        .sqlUpdate(verbose: true);
    return this;
  }

When I run recover I see this come from the verbose log:

flutter: UPDATE gearEvents SET event_id= ?, deploy_time= ?, deploy_lat= ?, deploy_lng= ?, recover_time= ?, recover_lat= ?, recover_lng= ?, deploy_atlas_device_id= ?, recover_atlas_device_id= ? WHERE id=36 {event_id: 0f552795-9bff-44e3-b938-b5cf38c40fb0, deploy_time: 1609119872543, deploy_lat: 37.32824275, deploy_lng: -122.02685504, recover_time: 1609119874681, recover_lat: 37.32830924, recover_lng: -122.02685755, deploy_atlas_device_id: 395976bf-8d05-52d8-b13b-7e00c6986c7b, recover_atlas_device_id: 395976bf-8d05-52d8-b13b-7e00c6986c7b} in 4 ms

When I call undoRecover on the model, I see this:

flutter: UPDATE gearEvents SET event_id= ?, deploy_time= ?, deploy_lat= ?, deploy_lng= ?, deploy_atlas_device_id= ? WHERE id=36 {event_id: 0f552795-9bff-44e3-b938-b5cf38c40fb0, deploy_time: 1609119872543, deploy_lat: 37.32824275, deploy_lng: -122.02685504, deploy_atlas_device_id: 395976bf-8d05-52d8-b13b-7e00c6986c7b} in 2 ms

EDIT:

So it's because of this line

I'm thinking it should probably be changed for updates, unless there is a very specific reason why it was implemented this way

question about database version

How to insert a new column to exist table?
We can update the database version within sqflite, but how to do within sqlcool?

this._db = await openDatabase(dbpath, version: 1,
onCreate: (Database _sqfliteDb, int version) async {
await _initQueries(schema, queries, _sqfliteDb, verbose);
}, onOpen: (Database _sqfliteDb) async {
// run create queries for file copied from an asset
if (fromAsset != null && checkCreateQueries) {
if (schema != null || queries.isNotEmpty) {
await _initQueries(schema, queries, _sqfliteDb, verbose);
}
}
});

Support change feed across isolates

A quick skim on the source code shows the .changefeed property works well on a single instance of the plugin (within the same isolate).

Can this be made to work with background processing, so that a worker process (e.g. started on Android in a service / work manager / separate engine) could signal database changes?

Handle conflicts on inserts

This question was asked by @bmelton at synw/sqlview#1 , moving it to here

BatchInsert allows for use of ConflictAlgorithm.replace / ignore / whatever, but I don't see any implementation for this on the regular db.insert method, and can't figure out how to handle those errors. Should I just try and catch them, or is there something obvious that I'm missing?

How to Relation many to one in sqlcool?

Hi. I want to make a one-to-many relationship using sqlcool. I have a class model of orders and products. But I don't know how to generate those relationships in order. Then, when I insert from the order, the products are automatically saved and generated

Built-in parsing system

Currently we are engaging with Map<String, String> for both insert and select (even that it returns a Map<String, dynamic>) queries. It's better to create some kind of built-in system to parse data to String and back from String based on column type.

SelectBloc Reactive doesn't trigger when not current screen

If I have SelectBloc set to be reactive, and use a StreamBuilder to build my home page,
Then update the table it is watching while on a different page, it fails to update the original home page.

I tried also calling setState() via listening to the _changefeed, however that doesn't work either.

Is this a limitation of sqlcool/SelectBloc/StreamBuilder and something I should solve myself?

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.