6ef658558a
First slice of the tier 2 offline mode work tracked in Fable #147. Notes are the only domain wired so far; this PR establishes the shape and proves the round-trip end-to-end before extending to tasks / projects / events / etc. in phase 2. Local store - Adds drift ^2.20.0 + sqlite3_flutter_libs ^0.5.24 + path ^1.9.0 runtime deps and drift_dev / build_runner dev deps. - New lib/data/local/database.dart: FabledDatabase with CachedNotes (mirroring the Note model 1:1; tags stored as JSON-encoded text) and SyncMetadata (per-domain last_synced_at). Database file lives at $appDocs/fabled_cache.sqlite; opened lazily in a background isolate. - fabledDatabaseProvider on the existing api_client_provider; closes the DB when the ProviderScope disposes. Repository pattern - NotesRepository now takes (NotesApi, FabledDatabase). Reads attempt the network first; on success the response is written to the cache. On NetworkException reads fall back to the cache (rethrowing if it is empty so fresh-install offline still surfaces the network error). - Writes (create/update/delete) hit the server then sync the cache; offline write queueing is phase 3 and explicitly not wired here. - AuthStatus.offline stays owned by AuthNotifier.verify()'s heartbeat; this repo deliberately doesn't poke that state. OfflineBanner - Reads notesRepository.lastSyncedAt(); when present, swaps "Offline — showing cached data." for "Offline — last sync X min ago." A 30s timer refreshes the relative-time string while the banner is mounted. - Falls back to the generic message if no cache exists yet (fresh install offline). Verification - flutter analyze: No issues found Out of scope (later phases per the task body) - Tasks / projects / milestones / events / conversation list / journal day caching (phase 2 — same wrapper pattern, repeated) - Generic write queue with conflict resolution on updated_at (phase 3) - Read-only UI indicators on screens that depend on cached data (phase 4) - Full offline chat (out of scope; needs a local model) - RAG / search over cached content (out of scope) Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
153 lines
5.2 KiB
Dart
153 lines
5.2 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:drift/drift.dart';
|
|
import 'package:drift/native.dart';
|
|
import 'package:path/path.dart' as p;
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:sqlite3_flutter_libs/sqlite3_flutter_libs.dart';
|
|
|
|
import '../models/note.dart';
|
|
|
|
part 'database.g.dart';
|
|
|
|
/// Local cache of server-side Notes for offline reads.
|
|
///
|
|
/// Mirrors the shape of [Note] one-to-one. Tags are stored as a JSON-encoded
|
|
/// string because SQLite has no native list type and Drift's typed converters
|
|
/// add ceremony we don't need for a simple read cache. `cachedAt` tracks when
|
|
/// the row was last written from a successful API response.
|
|
class CachedNotes extends Table {
|
|
IntColumn get id => integer()();
|
|
TextColumn get title => text()();
|
|
TextColumn get body => text()();
|
|
TextColumn get tagsJson => text().withDefault(const Constant('[]'))();
|
|
TextColumn get noteType => text().withDefault(const Constant('note'))();
|
|
IntColumn get projectId => integer().nullable()();
|
|
IntColumn get milestoneId => integer().nullable()();
|
|
DateTimeColumn get createdAt => dateTime()();
|
|
DateTimeColumn get updatedAt => dateTime()();
|
|
DateTimeColumn get cachedAt =>
|
|
dateTime().clientDefault(() => DateTime.now())();
|
|
|
|
@override
|
|
Set<Column> get primaryKey => {id};
|
|
}
|
|
|
|
/// Per-domain sync timestamp. Keyed by a short domain string ('notes',
|
|
/// 'tasks', 'projects', 'events', etc.) so the OfflineBanner and any
|
|
/// stale-while-revalidate logic can ask "when did we last fetch this".
|
|
class SyncMetadata extends Table {
|
|
TextColumn get domain => text()();
|
|
DateTimeColumn get lastSyncedAt => dateTime()();
|
|
|
|
@override
|
|
Set<Column> get primaryKey => {domain};
|
|
}
|
|
|
|
const String kSyncDomainNotes = 'notes';
|
|
|
|
@DriftDatabase(tables: [CachedNotes, SyncMetadata])
|
|
class FabledDatabase extends _$FabledDatabase {
|
|
FabledDatabase() : super(_openConnection());
|
|
FabledDatabase.forTesting(super.executor);
|
|
|
|
@override
|
|
int get schemaVersion => 1;
|
|
|
|
// ── Notes ────────────────────────────────────────────────────────────────
|
|
|
|
Future<List<Note>> getAllNotes() async {
|
|
final rows = await (select(cachedNotes)
|
|
..orderBy([(t) => OrderingTerm.desc(t.updatedAt)]))
|
|
.get();
|
|
return rows.map(_noteFromRow).toList();
|
|
}
|
|
|
|
Future<Note?> getNote(int id) async {
|
|
final row = await (select(cachedNotes)..where((t) => t.id.equals(id)))
|
|
.getSingleOrNull();
|
|
return row == null ? null : _noteFromRow(row);
|
|
}
|
|
|
|
/// Replace the entire notes cache with the latest server snapshot.
|
|
/// Used after a successful `getAll()` so the cache reflects deletions
|
|
/// (a row that's gone from the server should be gone locally too).
|
|
Future<void> replaceAllNotes(List<Note> notes) async {
|
|
await transaction(() async {
|
|
await delete(cachedNotes).go();
|
|
if (notes.isNotEmpty) {
|
|
await batch((b) {
|
|
b.insertAll(
|
|
cachedNotes,
|
|
notes.map(_companionFromNote).toList(),
|
|
);
|
|
});
|
|
}
|
|
await _setLastSyncIn(kSyncDomainNotes, DateTime.now());
|
|
});
|
|
}
|
|
|
|
/// Upsert a single note (after a successful create / update / getOne).
|
|
Future<void> upsertNote(Note note) async {
|
|
await into(cachedNotes).insertOnConflictUpdate(_companionFromNote(note));
|
|
}
|
|
|
|
Future<void> deleteNote(int id) async {
|
|
await (delete(cachedNotes)..where((t) => t.id.equals(id))).go();
|
|
}
|
|
|
|
// ── Sync metadata ────────────────────────────────────────────────────────
|
|
|
|
Future<DateTime?> getLastSync(String domain) async {
|
|
final row = await (select(syncMetadata)
|
|
..where((t) => t.domain.equals(domain)))
|
|
.getSingleOrNull();
|
|
return row?.lastSyncedAt;
|
|
}
|
|
|
|
Future<void> _setLastSyncIn(String domain, DateTime timestamp) {
|
|
return into(syncMetadata).insertOnConflictUpdate(
|
|
SyncMetadataCompanion(
|
|
domain: Value(domain),
|
|
lastSyncedAt: Value(timestamp),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
CachedNotesCompanion _companionFromNote(Note note) => CachedNotesCompanion(
|
|
id: Value(note.id),
|
|
title: Value(note.title),
|
|
body: Value(note.body),
|
|
tagsJson: Value(jsonEncode(note.tags)),
|
|
noteType: Value(note.noteType),
|
|
projectId: Value(note.projectId),
|
|
milestoneId: Value(note.milestoneId),
|
|
createdAt: Value(note.createdAt),
|
|
updatedAt: Value(note.updatedAt),
|
|
);
|
|
|
|
Note _noteFromRow(CachedNote row) => Note(
|
|
id: row.id,
|
|
title: row.title,
|
|
body: row.body,
|
|
tags: (jsonDecode(row.tagsJson) as List<dynamic>).cast<String>(),
|
|
noteType: row.noteType,
|
|
projectId: row.projectId,
|
|
milestoneId: row.milestoneId,
|
|
createdAt: row.createdAt,
|
|
updatedAt: row.updatedAt,
|
|
);
|
|
|
|
LazyDatabase _openConnection() {
|
|
return LazyDatabase(() async {
|
|
if (Platform.isAndroid) {
|
|
await applyWorkaroundToOpenSqlite3OnOldAndroidVersions();
|
|
}
|
|
final dir = await getApplicationDocumentsDirectory();
|
|
final file = File(p.join(dir.path, 'fabled_cache.sqlite'));
|
|
return NativeDatabase.createInBackground(file);
|
|
});
|
|
}
|