• This repository has been archived on 07/May/2023
  • Stars
    star
    162
  • Rank 227,886 (Top 5 %)
  • Language
    Dart
  • License
    MIT License
  • Created over 5 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easy and reactive Sqlite for Flutter

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

More Repositories

1

django-instant

Websockets for Django with Centrifugo
Python
120
star
2

map_controller

Stateful map controller for Flutter Map
Dart
57
star
3

django-vitevue

Manage Vitejs frontends for Django
Python
50
star
4

livemap

A map widget with live position updates for Flutter
Dart
46
star
5

geojson

Utilities to work with geojson data in Dart
Dart
37
star
6

django-mqueue

Events queue for Django
Python
29
star
7

django-chartflo

Charts for the lazy ones in Django
CSS
29
star
8

airlink

A mobile file explorer with peer to peer file transfer and remote file server connection
Dart
26
star
9

dataview

View application data for Flutter
Dart
26
star
10

iso

An isolates runner with bidirectionnal communication
Dart
25
star
11

panaview

A desktop application to visualize Dart packages analysis
Dart
23
star
12

django-userprofiles2

User profiles that work with Django Allauth
Python
22
star
13

df

A dataframe for Dart
Dart
19
star
14

isohttpd

A lightweight http server that runs in an isolate
Dart
19
star
15

geopoint

Geospatial data structures for Dart
Dart
16
star
16

nodecommander

Network nodes communication in Dart
Dart
16
star
17

filex

Configurable file explorer widget for Flutter
Dart
16
star
18

geodraw

Draw markers, lines and polygons on a map
Dart
15
star
19

django-watchtower

Collect metrics and events from Django
Python
14
star
20

tailwindcss-semantic-colors

A Tailwind css plugin to generate semantic color utilities
JavaScript
13
star
21

fluxmap

A reactive map that handle real time location updates for multiple devices for Flutter
Dart
12
star
22

folder_picker

A directory picker for Flutter
Dart
11
star
23

django-spaninja

Django api server with single page app template
Vue
11
star
24

agent-smith

Local first human friendly agents toolkit for the browser and Nodejs
TypeScript
10
star
25

django-dirtyedit

Django application to edit files from the admin interface
Python
10
star
26

django-mqueue-livefeed

Real time events feed demo for Django Mqueue
Python
10
star
27

traccar_client

Dart client for the Traccar geolocation server
Dart
9
star
28

dataswim

Diving equipment for data lake
Python
9
star
29

django-autoreloader

Autoreload files in browser for Django development
Python
8
star
30

centcli

Terminal client for Centrifugo
Go
7
star
31

django-graphql-utils

Utilities for working with Graphql in Django
JavaScript
7
star
32

usepython

Run Python scripts in a Pyodide service worker
TypeScript
7
star
33

django-rechat

A chat application for Django
Python
7
star
34

django-introspection

Introspection tools for Django
Python
7
star
35

django-presence

Realtime user presence widget for Django
Python
7
star
36

rethinkdb-editor

Manage Rethinkdb databases and edit content
JavaScript
7
star
37

snowind

A Vuejs 3 Tailwindcss design system
Vue
6
star
38

pad

Quick padding for Flutter
Dart
6
star
39

desktopia

Flutter widgets and components for desktop
Dart
6
star
40

infergui

Graphical user inferface for local language models
Vue
6
star
41

geopoint_sql

Sql operations for geospatial data
Dart
6
star
42

django-mptt-graph

Graphical representation of mptt models
Python
6
star
43

sqlview

Widgets for Sqlcool: admin view and infinite list view
Dart
6
star
44

django-instant-example

Example for django-instant with backend and frontend
Python
6
star
45

fwr

Development server for Flutter web with multi-devices autoreload
Go
5
star
46

geodf

Geospatial timeseries analysis for Dart
Dart
5
star
47

django-mogo

Starter kit for Django projects
Python
5
star
48

device

Data structure representing a device for Dart
Dart
5
star
49

influxdb

Influxdb 2 client for Dart
Dart
5
star
50

django-dex

Database export tools for Django
Python
5
star
51

goinfer

Lightweight inference server for local language models
Go
5
star
52

food_scan

A mobile application to get info about food products by scanning barcodes
Dart
5
star
53

kvsql

A type safe key/value store backed by Sqlite for Flutter
Dart
5
star
54

dataspace

Data wrangling and visualization
Python
5
star
55

webx

Routing and layout management for Flutter web
Dart
5
star
56

err

Error data structures for fine-grained control over errors
Dart
5
star
57

map_markers

Markers builders for Flutter Map
Dart
5
star
58

smsexpress

Send sms messages from a terminal
Dart
5
star
59

sqlite-speed

Test Sqlite write speed with various sql abstraction tools in Go and Python
Python
4
star
60

bg_download

Download files in the background in an isolate for Dart
Dart
4
star
61

pycheck

An opinionated code quality checker for Python
TypeScript
4
star
62

emodebug

Emoji-based semantic debuging for Dart
Dart
4
star
63

django-vitevue-example

Example usage of django-vitevue
Python
4
star
64

django-jssor

Jssor slideshows for Django
JavaScript
4
star
65

djangoinstant

Client for the django-instant websockets backend
TypeScript
4
star
66

terr

Trace errors across the call stack
Go
4
star
67

persistent_state

Persist state across restarts and returns from hibernation in Flutter
Dart
4
star
68

geopoint_location

Handle real time location data for Geopoint
Dart
4
star
69

django-qcf

Django quick contact form
Python
3
star
70

django-changefeed

Rethinkdb realtime changefeed manager for Django
Python
3
star
71

django-chartmodels

Chart Django models
Python
3
star
72

dbswitch

Switch between Sqlite databases and import/export them to storage for Sqlcool
Dart
3
star
73

statik

A configurable watch-autoreload development server
Go
3
star
74

django-vvpages

Pages management with Vue.js for Django
Python
3
star
75

rxclass

A set of stateful data classes with reactive properties
TypeScript
3
star
76

django-R

Rethinkdb toolkit for Django
JavaScript
3
star
77

sqldebug

A Node Commander plugin to run sql queries on device from a terminal
Dart
3
star
78

django-term

In browser terminal for Django
JavaScript
3
star
79

chartlibs_eval

An evaluation of different Flutter charting libraries
Dart
3
star
80

django-alapage

Pages management app for Django
Python
3
star
81

django-vvinstant

Vue.js frontend for Django Instant - MERGED into https://github.com/synw/django-instant
HTML
3
star
82

airlib

Peer to peer file transfer library for Dart
Dart
2
star
83

vite-vue

Vue.js mixin for http operations and state management
JavaScript
2
star
84

quidpy

A requests library for the Quid json web tokens server
Python
2
star
85

quid_examples

Frontend and backend examples usage of the Quid json web tokens server
Vue
2
star
86

django-spages

Lightweight single page app engine for Django
Python
2
star
87

quidart

A requests library for the Quid json web tokens server
Dart
2
star
88

django-mgof

Modern good old forums for Django
Python
2
star
89

modprompt

Prompt templates for language models
TypeScript
2
star
90

err_router

A logs router for Flutter that can pop messages to the device screen
Dart
2
star
91

snowind-stories

A storybook presenting the Snowind components
Vue
2
star
92

ghobserver

Monitor your Github data
Python
2
star
93

django-tabular

Display tabular data in Django
Python
2
star
94

chartjspy

Generate Chartjs charts from python
Python
2
star
95

locallm

An api to query local language models using different backends
TypeScript
2
star
96

centcom

A Go API for Centrifugo
Go
2
star
97

leaflet-controller

A stateful map controller for Leaflet
TypeScript
2
star
98

chartflo

Charts for the lazy ones with Flutter
Dart
2
star
99

dialmenu

Flexible dialer menu for Flutter
Dart
2
star
100

usepwastate

A composable to manage a progressive web app's install state
TypeScript
2
star