49 lines
1.2 KiB
Dart
49 lines
1.2 KiB
Dart
import 'person.dart';
|
|
import 'package:sqlite3/sqlite3.dart';
|
|
|
|
import 'person_data_access_map.dart';
|
|
|
|
class PersonDataAccessSqlite implements PersonDataAccessMap {
|
|
final String fileName;
|
|
final Database db;
|
|
|
|
PersonDataAccessSqlite(this.fileName) : db = sqlite3.open(fileName) {
|
|
try {
|
|
// when select fails due to missing table ...
|
|
db.execute('SELECT count(*) from persons');
|
|
} catch (e) {
|
|
// ... create it
|
|
db.execute('''CREATE TABLE persons (
|
|
id INTEGER NOT NULL PRIMARY KEY,
|
|
name TEXT NOT NULL);''');
|
|
}
|
|
}
|
|
|
|
@override
|
|
void store(Person p) {
|
|
final stmt = db.prepare('INSERT INTO persons (id, name) VALUES (?, ?)');
|
|
stmt.execute([p.id, p.name]);
|
|
stmt.dispose();
|
|
}
|
|
|
|
@override
|
|
Person? retrieve(int id) {
|
|
final ResultSet resultSet =
|
|
db.select('SELECT * FROM persons WHERE id = ?', [id]);
|
|
return resultSet.isEmpty
|
|
? null
|
|
: Person(resultSet.first['id'], resultSet.first['name']);
|
|
}
|
|
|
|
@override
|
|
List<Person> retrieveAll() {
|
|
final ResultSet resultSet = db.select('SELECT * FROM persons');
|
|
return resultSet.map((row) => Person(row['id'], row['name'])).toList();
|
|
}
|
|
|
|
@override
|
|
void close() {
|
|
db.dispose();
|
|
}
|
|
}
|