database_manager 0.0.4

  • Readme
  • Changelog
  • Example
  • Installing
  • 55

database_manager (Developer Preview) #

pub package Donate

Simple way to manage database. Version control and application's database schema. Simplify CRUD operations.

Installing #

Add this to your package's pubspec.yaml file:

dependencies:
  database_manager: "^0.0.4"

Sqlite, Path and Path Provider dependencies must be installed.

Available features #

  • [x] Migration - version control and application's database schema
  • [x] ORM - simplify CRUD operations

Simple usage #

Migration #

import 'package:database_manager/database_manager.dart';

class Table implements Migration {
  @override
  void up() {
    Schema.create('table', (Blueprint table) {
      table.integer('id').autoIncrement();
      table.string('name').nullable();
      table.string('email').unique();
      table.unsignedInteger('active').defaultValue(1);
    });    
  }
  @override
  void down() {
    Schema.dropIfExists('table');
  }
}

Model #

import 'package:database_manager/database_manager.dart';
import 'database/migration/table.dart';

class TableModel extends ORMModel {
  @override
  final String databaseName = 'test';
  @override
  final int databaseVersion = 1;

  @override
  List<Migration> migration() {
    return [Table1()];
  }
}

Usage #

import 'model/table_model.dart';

TableModel table = TableModel();

final List<Map<String, dynamic>> lst = [];
for (int i = 0; i < 1000; i++) lst.add({'name': 'marios', 'email': 'email$i@email.com'});

List ids = await table   
  .insert(lst, noResult: true, continueOnError: false)
  .catchError((e) => print(e));
   
print(ids);

table.get(['name','email']).then((r) => print(r) );

Migration parameters #

PropNameDescriptiondefault value
attributedescriptionvalue

It takes time to carry on this project. If you found it useful or learned something from the source code please consider the idea of donating 5, 20, 50 € or whatever you can to support the project.

  • Donate

Issues #

If you encounter problems, open an issue. Pull request are also welcome.

[0.0.4] - 2020-06-02. #

  • [Added] - whereRow function.
  • [Updated] - readme.

[0.0.3+2] - 2020-05-23. #

  • General improvement of the code.
  • added exists operator.

[0.0.3+1] - 2020-05-15. #

  • General improvement of the code.
  • added the ability to create nested queries.

[0.0.3] - 2020-05-2. #

  • Created the following model methods:
  • select, count, min, avg, max
  • where, orWhere, whereIn, orWhereIn, whereNotIn, orWhereNotIn
  • insert, update, get
  • distinct, groupBy, orderBy, orderByDesc, orderByAsc
  • having, orHaving

[0.0.2] - 2020-04-18. #

  • Created Connection Class. Possibility to manage the connection with SQflite.

[0.0.1] - 2020-04-9. #

  • Created Database Manager.
  • Created SQLCommand.
  • Created Schema Class.

example/lib/main.dart

import 'package:flutter/material.dart';

import 'package:database_manager/database_manager.dart';
import 'package:example/database/migration/table1.dart';
import 'package:example/database/migration/table2.dart';
import 'package:sqflite/sqflite.dart';

import 'model/table1_model.dart';
import 'model/table2_model.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Migration'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 25),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            RaisedButton(
              child: Text("migrate"),
              onPressed: _migrate,
            ),
            RaisedButton(
              child: Text("drop database"),
              onPressed: () {
                Connection con = Connection();
                con.init(dbName: 'prova');
                con.dropDatabase();
              },
            ),
            /*Text(
              '${_migrate()}',
              //style: Theme.of(context).textTheme.display1,
            ),*/
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _dbTest() async {
    Connection con = Connection();
    await con.init(
        dbName: 'db',
        onCreate: (db, v) {
          db.execute("CREATE TABLE IF NOT EXISTS `table` ("
              "`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"
              "`name` VARCHAR(255) NOT NULL,"
              "`email` VARCHAR(255) NOT NULL,"
              "`cell` VARCHAR(255) DEFAULT NULL,"
              "UNIQUE (`email`)"
              ");");
        });
    Database db = con.database;
    await db.delete('table');
    await db.transaction((db) async {
      Batch btc = db.batch();
      for (int i = 0; i < 10000; i++) {
        //btc.execute("INSERT INTO 'table'(name,email) VALUES(?,?)",['mario','email$i@email.com']);
        btc.insert("table", {'name': 'mario', 'email': 'email$i@email.com'});
      }
      return await btc.commit(noResult: true);
    });

    db.query('table',
        where: 'exists (select * from "table" tb where tb.id = id and name =?)',
        whereArgs: ['mario']).then((res) => print(res));
  }

  Future<void> _migrate() async {
    //_dbTest();return;

    Table1Model table1 = Table1Model();
    Table2Model table2 = Table2Model();

    //table2.delete();
    //table2.insert([{'nome':'mario','cognome':'rossi'}]);

    table1.delete();

    List<Map<String, dynamic>> lst = [];
    for (int i = 0; i < 1000; i++)
      lst.add({'name': 'marios', 'email': 'marios$i@email.com'});

    List ids = await table1
        .insert(lst, noResult: true, continueOnError: false)
        .catchError((e) => print(e));
    //print(ids);
    int cnt = await table1
        .where(
            nested: (query) => query
                .where(
                    nested: (query) => query.where(
                        nested: (query) => query
                            .where(
                                column: 'email',
                                operator: 'like',
                                value: 'marios11%')
                            .whereExists((query) => query
                                .from('users')
                                .where(column: 'id', value: '1'))))
                .whereRaw("name='marios'")
            //.limit(1)
            )
        /*.whereIn(column:'user_id', values: ['2','1'], nested: (query) => query
          */ /*.from('users as s')
          .select(['id'])
          .where(column: 'id', value: '2')*/ /*
        )*/
        .where(column: 'name', operator: 'like', value: 'marios')
        .count();
    print(cnt);

    //table1.whereIn('email', values: ['marios2@email.com','marios3@email.com','marios20000@email.com']);
    //table1.limit(2);
    //table1.get();
    //table1.insert([{'name': 'marios', 'email': 'marios20000@email.com'}]);
    //int cnt2 = await table1.count();
    //table1.get(['name','email']).then((r) => print(r) );

    /*int cnt = await table1.where(column: 'name', value: 'marios').whereIn(
        column: 'id',
        values: [
          '1',
          '2',
          '3',
          '4',
          '5',
          '6',
          '7',
          '8'
        ]).update({'name': 'carlitos'});
    print(cnt);*/

    /*table1
        //.orWhere(column: 'name', operator: 'like', value: 'm%')
        //.whereNotIn(column: 'id', values: ['2', '3', '4'])
        //.select(['min(id) min','avg(id) avg','max(id) max'])
        //.having(column: 'cnt', value: 2)
        .having(column: 'name', value: 'carlitos')
        .groupBy(['name','email'])
        //.limit(5).offset(1)
        //.distinct()
        //.get()
        //.where(column: 'id',value: 1)
        .get(['id','name','email'])
        .then((val) {
          val.forEach((a) => print(a));
        })
        .catchError((e) => print(e));*/
    //table1.delete();
    //table1.whereIn(column: 'id', values: ['1','2']).update({'name' :'mario'});
    //int cnt = await table1.count();
    //print(cnt);
    /*table1.where(column: 'name', value: 'mario').get(['id','name']).then((res){
      res.forEach((v) => print(v) );
    });*/
    /*table1
        .where(column: 'name', value: 'carlitos')
        .get(['id', 'name']).then((list) => list.forEach((val) => print(val)));
    print('');
    table1
        .select(['id', 'name'])
        .where(column: 'name', value: 'carlitos')
        .min('id', alias: 'min')
        .then((val) => print(val));
    table1
        .select(['id', 'name'])
        .where(column: 'name', value: 'carlitos')
        .avg('id', alias: 'avg')
        .then((val) => print(val));
    table1
        .select(['id', 'name'])
        .where(column: 'name', value: 'carlitos')
        .max('id', alias: 'max')
        .then((val) => print(val));*/
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  database_manager: ^0.0.4

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:database_manager/database_manager.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
38
Health:
Code health derived from static analysis. [more]
74
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
70
Overall:
Weighted score of the above. [more]
55
Learn more about scoring.

We analyzed this package on Jul 2, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Health issues and suggestions

Fix lib/src/orm/relations/relation.dart. (-25 points)

Analysis of lib/src/orm/relations/relation.dart failed with 1 error:

line 1 col 8: Target of URI doesn't exist: 'file:///D:/Android/Flutter/Package/database_manager/lib/src/orm/builder/orm_builder.dart'.

Fix lib/src/orm/query/query_builder.dart. (-1.49 points)

Analysis of lib/src/orm/query/query_builder.dart reported 3 hints:

line 5 col 21: The value of the field '_bindings' isn't used.

line 15 col 8: The value of the field '_operators' isn't used.

line 51 col 14: The value of the field '_joins' isn't used.

Fix lib/src/orm/query/raw_query_builder.dart. (-0.50 points)

Analysis of lib/src/orm/query/raw_query_builder.dart reported 1 hint:

line 37 col 14: Name non-constant identifiers using lowerCamelCase.

Maintenance issues and suggestions

No valid SDK. (-20 points)

The analysis could not detect a valid SDK that can use this package.

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
path ^1.6.4 1.7.0
path_provider ^1.6.8 1.6.11
sqflite ^1.3.0 1.3.1
Transitive dependencies
collection 1.14.12 1.14.13
file 5.2.1
intl 0.16.1
meta 1.1.8
path_provider_linux 0.0.1+2
path_provider_macos 0.0.4+3
path_provider_platform_interface 1.0.2
platform 2.2.1
plugin_platform_interface 1.0.2
process 3.0.13
sky_engine 0.0.99
sqflite_common 1.0.2+1
synchronized 2.2.0+1
typed_data 1.1.6 1.2.0
vector_math 2.0.8
xdg_directories 0.1.0
Dev dependencies
flutter_test