Skip to content

Commit cea3ae1

Browse files
committed
wip
1 parent 6faba1f commit cea3ae1

File tree

4 files changed

+113
-66
lines changed

4 files changed

+113
-66
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import 'package:powersync/sqlite3.dart' as sqlite;
2+
import 'package:wger/models/schema.dart';
3+
4+
import '../../powersync.dart';
5+
6+
/// TodoItem represents a result row of a query on "todos".
7+
///
8+
/// This class is immutable - methods on this class do not modify the instance
9+
/// directly. Instead, watch or re-query the data to get the updated item.
10+
/// confirm how the watch works. this seems like a weird pattern
11+
class TodoItem {
12+
final String id;
13+
final String description;
14+
final String? photoId;
15+
final bool completed;
16+
17+
TodoItem(
18+
{required this.id,
19+
required this.description,
20+
required this.completed,
21+
required this.photoId});
22+
23+
factory TodoItem.fromRow(sqlite.Row row) {
24+
return TodoItem(
25+
id: row['id'],
26+
description: row['description'],
27+
photoId: row['photo_id'],
28+
completed: row['completed'] == 1);
29+
}
30+
31+
Future<void> toggle() async {
32+
if (completed) {
33+
await db.execute(
34+
'UPDATE $logItemsTable SET completed = FALSE, completed_by = NULL, completed_at = NULL WHERE id = ?',
35+
[id]);
36+
} else {
37+
await db.execute(
38+
'UPDATE $logItemsTable SET completed = TRUE, completed_by = ?, completed_at = datetime() WHERE id = ?',
39+
[await getUserId(), id]);
40+
}
41+
}
42+
43+
Future<void> delete() async {
44+
await db.execute('DELETE FROM $logItemsTable WHERE id = ?', [id]);
45+
}
46+
47+
static Future<void> addPhoto(String photoId, String id) async {
48+
await db.execute('UPDATE $logItemsTable SET photo_id = ? WHERE id = ?', [photoId, id]);
49+
}
50+
}
51+
/*
52+
static Stream<List<TodoList>> watchLists() {
53+
// This query is automatically re-run when data in "lists" or "todos" is modified.
54+
return db.watch('SELECT * FROM lists ORDER BY created_at, id').map((results) {
55+
return results.map(TodoList.fromRow).toList(growable: false);
56+
});
57+
}
58+
59+
static Future<TodoList> create(String name) async {
60+
final results = await db.execute('''
61+
INSERT INTO
62+
lists(id, created_at, name, owner_id)
63+
VALUES(uuid(), datetime(), ?, ?)
64+
RETURNING *
65+
''', [name, await getUserId()]);
66+
return TodoList.fromRow(results.first);
67+
}
68+
*/

lib/models/schema.dart

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,41 @@ import 'package:powersync/powersync.dart';
22

33
const todosTable = 'todos';
44
const musclesTable = 'muscles';
5+
const logItemsTable = 'nutrition_logitem';
56

6-
// these are the same ones as in postgres, except for 'id'
7+
/*
8+
Postgres:
9+
wger@localhost:wger> \d nutrition_logitem;
10+
+----------------+--------------------------+--------------------------------------------+
11+
| Column | Type | Modifiers |
12+
|----------------+--------------------------+--------------------------------------------|
13+
| id | integer | not null generated by default as identity |
14+
| datetime | timestamp with time zone | not null |
15+
| comment | text | |
16+
| amount | numeric(6,2) | not null |
17+
| ingredient_id | integer | not null |
18+
| plan_id | integer | not null |
19+
| weight_unit_id | integer | |
20+
| meal_id | integer | |
21+
+----------------+--------------------------+--------------------------------------------+
22+
*/
23+
// these are the same ones as in postgres, except for 'id', because that is implied
724
Schema schema = const Schema([
25+
Table(
26+
logItemsTable,
27+
[
28+
Column.text('datetime'),
29+
Column.text('comment'),
30+
Column.integer('amount'),
31+
Column.integer('ingredient_id'),
32+
Column.integer('plan_id'),
33+
Column.integer('weight_unit_id'),
34+
Column.integer('meal_id'),
35+
],
36+
indexes: [
37+
// Index('plan', [IndexedColumn('plan_id')])
38+
],
39+
),
840
Table(
941
todosTable,
1042
[
@@ -31,11 +63,7 @@ Schema schema = const Schema([
3163
),
3264
Table(
3365
'muscles',
34-
[
35-
Column.text('name'),
36-
Column.text('name_en'),
37-
Column.text('is_front'),
38-
],
66+
[Column.text('name'), Column.text('name_en'), Column.text('is_front')],
3967
),
4068
]);
4169

lib/models/todo_item.dart

Lines changed: 0 additions & 51 deletions
This file was deleted.

lib/powersync.dart

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ class DjangoConnector extends PowerSyncBackendConnector {
5252
}
5353

5454
try {
55-
for (var op in transaction.crud) {
55+
for (final op in transaction.crud) {
5656
final record = {
5757
'table': op.table,
5858
'data': {'id': op.id, ...?op.opData},
@@ -86,9 +86,14 @@ late final PowerSyncDatabase db;
8686
// Hacky flag to ensure the database is only initialized once, better to do this with listeners
8787
bool _dbInitialized = false;
8888

89+
/// id of the user currently logged in
90+
Future<String?> getUserId() async {
91+
final prefs = await SharedPreferences.getInstance();
92+
return prefs.getString('id');
93+
}
94+
8995
Future<bool> isLoggedIn() async {
90-
final prefs = await SharedPreferences.getInstance(); // Initialize SharedPreferences
91-
final userId = prefs.getString('id');
96+
final userId = await getUserId();
9297
return userId != null;
9398
}
9499

@@ -113,16 +118,13 @@ Future<void> openDatabase() async {
113118
// Otherwise, connect once logged in.
114119
currentConnector = DjangoConnector(db);
115120
db.connect(connector: currentConnector);
121+
122+
// TODO: should we respond to login state changing? like here:
123+
// https://www.powersync.com/blog/flutter-tutorial-building-an-offline-first-chat-app-with-supabase-and-powersync#implement-auth-methods
116124
}
117125
}
118126

119127
/// Explicit sign out - clear database and log out.
120128
Future<void> logout() async {
121129
await db.disconnectAndClear();
122130
}
123-
124-
/// id of the user currently logged in
125-
Future<String?> getUserId() async {
126-
final prefs = await SharedPreferences.getInstance();
127-
return prefs.getString('id');
128-
}

0 commit comments

Comments
 (0)