SqliteHandler.dart 3.46 KB
Newer Older
Jay Naik's avatar
Jay Naik committed
1 2 3 4 5 6 7 8 9 10 11
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqlite_api.dart';
import 'dart:async';
import 'Note.dart';

class NotesDBHandler {

  final databaseName = "notes.db";
  final tableName = "notes";

12

Jay Naik's avatar
Jay Naik committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
  final fieldMap = {
    "id": "INTEGER PRIMARY KEY AUTOINCREMENT",
    "title": "BLOB",
    "content": "BLOB",
    "date_created": "INTEGER",
    "date_last_edited": "INTEGER",
    "note_color": "INTEGER",
    "is_archived": "INTEGER"
  };


  static Database _database;


  Future<Database> get database async {
    if (_database != null)
      return _database;

    _database = await initDB();
    return _database;
  }


  initDB() async {
    var path = await getDatabasesPath();
    var dbPath = join(path, 'notes.db');
    // ignore: argument_type_not_assignable
    Database dbConnection = await openDatabase(
        dbPath, version: 1, onCreate: (Database db, int version) async {
      print("executing create query from onCreate callback");
      await db.execute(_buildCreateQuery());
    });

    await dbConnection.execute(_buildCreateQuery());
    _buildCreateQuery();
    return dbConnection;
  }


52
// build the create query dynamically using the column:field dictionary.
Jay Naik's avatar
Jay Naik committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  String _buildCreateQuery() {
    String query = "CREATE TABLE IF NOT EXISTS ";
    query += tableName;
    query += "(";
    fieldMap.forEach((column, field){
      print("$column : $field");
      query += "$column $field,";
    });


    query = query.substring(0, query.length-1);
    query += " )";

   return query;

  }

  static Future<String> dbPath() async {
    String path = await getDatabasesPath();
    return path;
  }

  Future<int> insertNote(Note note, bool isNew) async {
    // Get a reference to the database
    final Database db = await database;
    print("insert called");

    // Insert the Notes into the correct table.
    await db.insert('notes',
82
      isNew ? note.toMap(false) : note.toMap(true),
Jay Naik's avatar
Jay Naik committed
83 84 85 86
      conflictAlgorithm: ConflictAlgorithm.replace,
    );

    if (isNew) {
87
      // get latest note which isn't archived, limit by 1
Jay Naik's avatar
Jay Naik committed
88 89 90 91 92 93 94 95 96 97 98
      var one = await db.query("notes", orderBy: "date_last_edited desc",
          where: "is_archived = ?",
          whereArgs: [0],
          limit: 1);
      int latestId = one.first["id"] as int;
      return latestId;
    }
    return note.id;
  }


99
  Future<bool> copyNote(Note note) async {
Jay Naik's avatar
Jay Naik committed
100
    final Database db = await database;
101
    try {
102
      await db.insert("notes",note.toMap(false), conflictAlgorithm: ConflictAlgorithm.replace);
103 104 105 106 107
    } catch(Error) {
      print(Error);
      return false;
    }
    return true;
Jay Naik's avatar
Jay Naik committed
108 109 110 111 112 113 114 115 116
  }


  Future<bool> archiveNote(Note note) async {
    if (note.id != -1) {
      final Database db = await database;

      int idToUpdate = note.id;

117
      db.update("notes", note.toMap(true), where: "id = ?",
Jay Naik's avatar
Jay Naik committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
          whereArgs: [idToUpdate]);
    }
  }

  Future<bool> deleteNote(Note note) async {
    if(note.id != -1) {
      final Database db = await database;
      try {
        await db.delete("notes",where: "id = ?",whereArgs: [note.id]);
        return true;
      } catch (Error){
        print("Error deleting ${note.id}: ${Error.toString()}");
        return false;
      }
    }
  }


136
  Future<List<Map<String,dynamic>>> selectAllNotes() async {
Jay Naik's avatar
Jay Naik committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150
    final Database db = await database;
    // query all the notes sorted by last edited
    var data = await db.query("notes", orderBy: "date_last_edited desc",
        where: "is_archived = ?",
        whereArgs: [0]);

    return data;

  }



}