-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathdbInitialization.js
More file actions
1330 lines (1231 loc) · 39.2 KB
/
dbInitialization.js
File metadata and controls
1330 lines (1231 loc) · 39.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
52
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import SQLite from 'react-native-sqlite-storage';
console.log('in dbInitialization.js');
// Open or create the SQLite database
const db = SQLite.openDatabase(
{name: 'mydatabase.db', location: 'default'},
() => {
console.log('Database opened successfully');
},
error => {
console.error('Error opening database', error);
},
);
const initializeDatabase = async () => {
console.log('in initializeDatabase');
console.log('creating tables');
// Drop the existing users table before updating it. might be better to have a migrations file
db.transaction(tx => {
// Drop the existing users table
tx.executeSql(
`DROP TABLE IF EXISTS users`,
[],
() => {
console.log('Old users table dropped successfully.');
},
(_, error) => {
console.error('Error dropping table', error);
},
);
});
// Drop the existing curriculum table before updating it. might be better to have a migrations file
db.transaction(tx => {
// Drop the existing curriculum table
tx.executeSql(
`DROP TABLE IF EXISTS curriculum`,
[],
() => {
console.log('Old curriculum table dropped successfully.');
},
(_, error) => {
console.error('Error dropping table', error);
},
);
});
// tx.executeSql(
// `CREATE TABLE IF NOT EXISTS UserSettingsv3 (
// id INTEGER PRIMARY KEY AUTOINCREMENT,
// userId INTEGER,
// featureA INTEGER DEFAULT 1 CHECK(featureA BETWEEN 0 AND 1),
// featureB INTEGER DEFAULT 1 CHECK(featureB BETWEEN 0 AND 1),
// featureC INTEGER DEFAULT 1 CHECK(featureC BETWEEN 0 AND 1),
// featureD INTEGER DEFAULT 1 CHECK(featureD BETWEEN 0 AND 1),
// featureE INTEGER DEFAULT 1 CHECK(featureE BETWEEN 0 AND 1),
// featureF INTEGER DEFAULT 1 CHECK(featureF BETWEEN 0 AND 1),
// featureG INTEGER DEFAULT 1 CHECK(featureG BETWEEN 0 AND 1),
// featureH INTEGER DEFAULT 1 CHECK(featureH BETWEEN 0 AND 1),
// FOREIGN KEY (userId) REFERENCES Users(id)
// )`,
// [],
// () => {
// console.log('usersettingsv3 Table created successfully - in dbInitialization.');
// },
// (_, error) => {
// console.error('Error creating UserSettingsv3 table or exists or or or or or', error);
// },
// );
// tx.executeSql(`
// CREATE TRIGGER IF NOT EXISTS create_default_settings
// AFTER INSERT ON Users
// BEGIN
// INSERT INTO UserSettingsv3 (userId)
// VALUES (NEW.id);
// END;
// `,
// [],
// () => {
// console.log('users trigger created successfuly - in dbInitialization.');
// },
// (_, error) => {
// console.error('Error creating trigger', error);
// },
// );
// });
// Drop the existing achievements table before updating it. might be better to have a migrations file
db.transaction(tx => {
// Drop the existing achievements table
tx.executeSql(
`DROP TABLE IF EXISTS achievements`,
[],
() => {
console.log('Old achievements table dropped successfully.');
},
(_, error) => {
console.error('Error dropping table', error);
}
);
});
// function to create tables
const createTable = (query, tableName) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
query,
[],
() => {
console.log(`${tableName} table created successfully.`);
resolve();
},
(tx, error) => {
console.error(`Error creating ${tableName} table`, error);
reject(error);
},
);
});
});
};
const addColumnIfTableExists = (tableName, columnName, columnDefinition) => {
return new Promise((resolve, reject) => {
console.log(
`Checking if column '${columnName}' exists in '${tableName}' table...`,
);
db.transaction(tx => {
// Query the table schema to check if the column exists
tx.executeSql(
`PRAGMA table_info(${tableName});`, // This returns info about the columns in the table
[],
(_, result) => {
// Check if the column exists
const columnExists = Array.from({length: result.rows.length}).some(
(_, i) => result.rows.item(i).name === columnName,
);
if (columnExists) {
console.log(
`Column '${columnName}' already exists in '${tableName}' table. No changes needed.`,
);
resolve(); // Resolve as no need to add the column
} else {
console.log(
`Column '${columnName}' does not exist in '${tableName}' table. Adding column...`,
);
// Add the column if it doesn't exist
tx.executeSql(
`ALTER TABLE ${tableName} ADD COLUMN ${columnDefinition};`,
[],
() => {
console.log(
`Column '${columnName}' added to '${tableName}' table successfully.`,
);
resolve(); // Resolve after successfully adding the column
},
(tx, error) => {
// Handle any errors that occur while adding the column
console.error(
`Error adding column '${columnName}' to '${tableName}' table:`,
error?.message || 'Unknown error',
);
reject(error);
},
);
}
},
(tx, error) => {
// Handle any errors that occur while querying the table schema
console.error(
`Error querying table info for '${tableName}':`,
error?.message || 'Unknown error',
);
reject(error);
},
);
});
});
};
// Create the tables if they don't exist
const imgdpTableQuery = `
CREATE TABLE IF NOT EXISTS imgdp (
id INTEGER PRIMARY KEY AUTOINCREMENT,
b64str TEXT,
input INTEGER,
output INTEGER
)`;
const curriculumTableQuery = `
CREATE TABLE IF NOT EXISTS curriculum (
id INTEGER PRIMARY KEY AUTOINCREMENT,
input_output INTEGER,
sequence INTEGER,
content TEXT,
completed INTEGER DEFAULT 0,
score INTEGER DEFAULT 0,
correct_answer TEXT,
difficulty TEXT DEFAULT 'medium',
choices TEXT
)`;
const curriculumImagesTableQuery = `
CREATE TABLE IF NOT EXISTS curriculumImages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
base64 TEXT NOT NULL
)`;
const usersTableQuery = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
picture TEXT,
estimatedAttentionSpan INTEGER,
settingsChoices TEXT,
progressInCurriculum INTEGER,
averageAccuracy INTEGER,
description TEXT,
necessaryBreakTime INTEGER
)`;
const achievementsTableQuery = `
CREATE TABLE IF NOT EXISTS achievements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
description TEXT,
picture TEXT,
points INTEGER,
user_id INTEGER,
FOREIGN KEY (user_id) REFERENCES users(id)
)`;
const userSettingsTableQuery = `
CREATE TABLE IF NOT EXISTS UserSettingsv3 (
id INTEGER PRIMARY KEY AUTOINCREMENT,
userId INTEGER,
featureA INTEGER DEFAULT 1 CHECK(featureA BETWEEN 0 AND 1),
featureB INTEGER DEFAULT 1 CHECK(featureB BETWEEN 0 AND 1),
featureC INTEGER DEFAULT 1 CHECK(featureC BETWEEN 0 AND 1),
featureD INTEGER DEFAULT 1 CHECK(featureD BETWEEN 0 AND 1),
featureE INTEGER DEFAULT 1 CHECK(featureE BETWEEN 0 AND 1),
featureF INTEGER DEFAULT 1 CHECK(featureF BETWEEN 0 AND 1),
featureG INTEGER DEFAULT 1 CHECK(featureG BETWEEN 0 AND 1),
featureH INTEGER DEFAULT 1 CHECK(featureH BETWEEN 0 AND 1),
FOREIGN KEY (userId) REFERENCES users(id)
)`;
// note: the emotionalStateDuringResponse is a string representation of an object with the emotional state of the user during the response as the key and the confidence level (response accuracy) as the value.
const responseTableQuery = `
CREATE TABLE IF NOT EXISTS response (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
curriculum_id INTEGER,
responseTime DATETIME,
emotionalStateDuringResponse TEXT,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (curriculum_id) REFERENCES curriculum(id)
)`;
// Create the tables using the queries above and the createTable function
return Promise.all([
createTable(imgdpTableQuery, 'imgdp'),
createTable(curriculumTableQuery, 'curriculum'),
createTable(curriculumImagesTableQuery, 'curriculumImages'),
createTable(usersTableQuery, 'users'),
createTable(achievementsTableQuery, 'achievements'),
createTable(userSettingsTableQuery, 'UserSettingsv3'),
createTable(responseTableQuery, 'response'),
])
.then(() => {
console.log('All tables created successfully.');
return addColumnIfTableExists(
'curriculum',
'completed',
'completed INTEGER DEFAULT 0',
);
// return addColumnIfTableExists('curriculum', 'score', 'score INTEGER DEFAULT 0');
})
.catch(error => {
console.error('Error initializing database', error);
throw error;
});
};
function dropTrigger(triggerName) {
db.transaction(tx => {
tx.executeSql(
`DROP TRIGGER IF EXISTS ${triggerName};`,
[],
() => {
console.log(`Trigger '${triggerName}' dropped successfully.`);
},
error => {
console.error(`Error dropping trigger '${triggerName}':`, error);
}
);
});
}
// CRUD operations for the imgdp table
// Insert a new row into the imgdp table
const insertImageData = async (b64str, input, output) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO imgdp (b64str, input, output) VALUES (?, ?, ?)',
[b64str, input, output],
(_, result) => {
console.log(`A row has been inserted with rowid ${result.insertId}`);
resolve(result);
},
(tx, error) => {
console.error('Error inserting data', error);
reject(error);
},
);
});
});
};
// Retrieve all rows from the imgdp table
const getImageData = () => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM imgdp',
[],
(_, result) => {
resolve(result.rows.raw());
},
(tx, error) => {
reject(error);
},
);
});
});
};
// Update a row in the imgdp table
const updateImageData = (b64str, id) => {
db.transaction(tx => {
tx.executeSql(
'UPDATE imgdp SET b64str = ? WHERE id = ?',
[b64str, id],
(_, result) => {
console.log(`Row(s) updated: ${result.rowsAffected}`);
},
(tx, error) => {
console.error('Error updating data', error);
},
);
});
};
// Delete a row from the imgdp table
const deleteImageData = id => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'DELETE FROM imgdp WHERE id = ?',
[id],
(_, result) => {
console.log(`Row(s) deleted: ${result.rowsAffected}`);
resolve(result);
},
(tx, error) => {
console.error('Error deleting data', error);
reject(error);
},
);
});
});
};
// Function to print the first row of the imgdp table
const printFirstRow = () => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM imgdp LIMIT 1',
[],
(_, {rows}) => {
if (rows.length > 0) {
console.log('First row data:', rows.item(0));
resolve(rows.item(0));
} else {
console.log('No data found.');
resolve(null);
}
},
(tx, error) => {
console.error('Error querying data', error);
reject(error);
},
);
});
});
};
//Insert a new row into the curriculum table
const insertCurriculumData = (input_output, sequence, content) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO curriculum (input_output, sequence, content) VALUES (?, ?, ?)',
[input_output, sequence, content],
(_, result) => {
console.log(`A row has been inserted with rowid ${result.insertId}`);
resolve(result);
},
(tx, error) => {
console.error('Error inserting data', error);
reject(error);
},
);
});
});
};
//Insert a new row into answers table
const insertAnswerData = (user_id, prompt, writing_response) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO answers (user_id, prompt, writing_response) VALUES(?, ?, ?)',
[user_id, prompt, writing_response],
(_, result) => {
console.log(`A row has been inserted with rowid ${result.insertId}`);
resolve(result);
},
(tx, error) => {
console.error('Error inserting data', error);
reject(error);
},
);
});
});
};
const insertCurriculumDataWithImage = async (input_output, sequence, content) => {
try {
let uriContent = content;
// Ensure content is an object and check for base64 image
if (typeof content === 'object' && content.image && content.image.startsWith('data:image/')) {
const base64Image = content.image; // Extract the base64 image string
const imageId = await createCurriculumImage(base64Image); // Store image and get its ID
uriContent = { ...content, image: `image://${imageId}` }; // Create URI and update content object
console.log("uriContent", uriContent);
}
// Serialize the content object to a JSON string
const serializedContent = JSON.stringify(uriContent);
const result = await insertCurriculumData(input_output, sequence, serializedContent);
console.log(`Inserted curriculum with row ID ${result.insertId}`);
return result;
} catch (error) {
console.error('Error inserting curriculum data with image', error);
throw error;
}
};
// Retrieve all rows from the curriculum table for testing
const getAllCurriculumData = () => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM curriculum',
[],
(_, result) => {
resolve(result.rows.raw());
},
(tx, error) => {
console.error('Error fetching all curriculum data:', error);
reject(error);
},
);
});
});
};
const printCurriculumFirstRow = () => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM curriculum LIMIT 1',
[],
(_, { rows }) => {
if (rows.length > 0) {
console.log('First row data:', rows.item(0));
resolve(rows.item(0));
} else {
console.log('No data found.');
resolve(null);
}
},
(tx, error) => { console.error('Error querying data', error);
reject(error);
}
);
});
});
};
// CRUD operations for the curriculumImages table
// Create function to store base64 data in curriculumImages
function createCurriculumImage(base64String) {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO curriculumImages (base64) VALUES (?);',
[base64String],
(_, { insertId }) => resolve(insertId), // Return the new image's ID
(_, error) => reject(error)
);
});
});
}
// Read function to retrieve base64 data by ID
const getCurriculumImageById = (id) =>{
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'SELECT base64 FROM curriculumImages WHERE id = ?;',
[id],
(_, { rows }) => {
if (rows.length > 0) {
const base64 = rows.item(0).base64;
console.log(`Base64 string for ID ${id}: ${base64}`);
resolve(base64);
} else {
console.log(`No image found for ID ${id}`);
resolve(null);
}
},
(_, error) => {
console.error(`Error retrieving image for ID ${id}`, error);
reject(error);
}
);
});
});
}
// Function to retrieve a curriculum image by ID
const retrieveCurriculumImageFromUri = (uri) => {
console.log('URI:', uri);
const imageId = uri.split('://')[1];
console.log('Image ID:', imageId);
return getCurriculumImageById(imageId);
}
// CRUD operations for the users table
// Insert a new row into the users table
const insertUser = (
name,
picture,
estimatedAttentionSpan,
settingsChoices,
progressInCurriculum,
averageAccuracy,
description,
necessaryBreakTime,
) => {
return new Promise((resolve, reject) => {
db.transaction(
tx => {
tx.executeSql(
'INSERT INTO users (name, picture, estimatedAttentionSpan, settingsChoices, progressInCurriculum, averageAccuracy, description, necessaryBreakTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[
name,
picture,
estimatedAttentionSpan,
settingsChoices,
progressInCurriculum,
averageAccuracy,
description,
necessaryBreakTime,
],
(_, result) => {
console.log(
`A row has been inserted in the user table with rowid ${result.insertId} and name ${name}`,
);
resolve(result);
},
(_, error) => {
console.error('Error inserting user data', error.message);
reject(error);
},
);
},
);
},
error => {
console.error('Transaction error:', error.message); //
},
() => {
console.log('Transaction completed successfully');
},
);
};
// Retrieve all rows from the users table
const getUsers = () => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
`SELECT * FROM Users`,
[],
(_, result) => {
const users = result.rows.raw();
resolve(users);
},
(_, error) => { reject(error); }
);
});
});
};
//Create Settings Tablee in db
// const createSettingsTable = () => {
// db.transaction(tx => {
// tx.executeSql(
// `CREATE TABLE IF NOT EXISTS UserSettings (
// id INTEGER PRIMARY KEY AUTOINCREMENT,
// featureA NUMBER DEFAULT 1,
// featureB NUMBER DEFUALT 1,
// featureC NUMBER DEFUALT 1,
// featureD NUMBER DEFAULT 1,
// featureE NUMBER DEFAULT 1,
// featureF NUMBER DEFAULT 1,
// featureG NUMBER DEFAULT 1,
// featureH NUMBER DEFAULT 1,
// )`,
// [],
// () => {
// console.log('Settings Table created successfully - in dbInitialization.');
// },
// (_, error) => {
// console.error('Error creating table or exists', error);
// },
// );
// });
// };
// Function to update user settings
const dropTable = (tableName) => {
db.transaction(tx => {
tx.executeSql(
`DROP TABLE IF EXISTS ${tableName}`,
[],
(tx, results) => {
console.log(`Table ${tableName} dropped successfully.`);
},
(tx, error) => {
console.error(`Error dropping table ${tableName}:`, error);
}
);
});
};
// Call the function with the table name you want to drop
// dropTable('UserSettings');
// is this chaning the true and false into 1 and zero
const updateUserSettings = (userId, settings) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
`UPDATE UserSettingsv3 SET
featureA = ?,
featureB = ?,
featureC = ?,
featureD = ?,
featureE = ?,
featureF = ?,
featureG = ?,
featureH = ?
WHERE userId = ?`,
[
settings.featureA ? 1 : 0,
settings.featureB ? 1 : 0,
settings.featureC ? 1 : 0,
settings.featureD ? 1 : 0,
settings.featureE ? 1 : 0,
settings.featureF ? 1 : 0,
settings.featureG ? 1 : 0,
settings.featureH ? 1 : 0,
userId
],
(_, result) => {
resolve(result);
},
(_, error) => {
reject(error);
}
);
});
});
};
const updateUserSettings2 = (userId, settings) => {
const booleanToInteger = value => (value === true ? 1 : 0);
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(`
INSERT INTO UserSettingsv3 (userId, featureA, featureB, featureC, featureD, featureE, featureF, featureG, featureH)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(userId) DO UPDATE SET
featureA=excluded.featureA,
featureB=excluded.featureB,
featureC=excluded.featureC,
featureD=excluded.featureD,
featureE=excluded.featureE,
featureF=excluded.featureF,
featureG=excluded.featureG,
featureH=excluded.featureH
`, [
userId,
booleanToInteger(settings.featureA),
booleanToInteger(settings.featureB),
booleanToInteger(settings.featureC),
booleanToInteger(settings.featureD),
booleanToInteger(settings.featureE),
booleanToInteger(settings.featureF),
booleanToInteger(settings.featureG),
booleanToInteger(settings.featureH)
], (tx, results) => {
resolve(results);
}, (tx, error) => {
reject(error);
});
});
});
};
// Function to retrieve user settings
const getUserSettings=(userId)=> {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
`SELECT * FROM UserSettingsv3 WHERE userId = ?;`,
[userId],
(tx, results) => {
const rows = results.rows;
let userSettings = [];
for (let i = 0; i < rows.length; i++) {
userSettings.push(rows.item(i));
}
resolve(userSettings); // Resolve the promise with the user settings
},
error => {
reject(error); // Reject the promise with an error
}
);
});
});
}
const getAllUserSettings = () => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
`SELECT * FROM UserSettingsv3`,
[],
(_, result) => { resolve(result.rows.raw()); },
(_, error) => { reject(error); }
);
});
});
};
const getOneUser = (id) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM users WHERE id = ?',
[id],
(_, result) => {
const user = result.rows.raw();
console.log('User:', user);
resolve(user);
},
(_, error) => { reject(error); }
);
});
});
};
// Update a row in the users table
const updateUser = (id, updates) => {
const fields = [];
const values = [];
if (updates.name !== undefined) {
fields.push('name = ?');
values.push(updates.name);
}
if (updates.picture !== undefined) {
fields.push('picture = ?');
values.push(updates.picture);
}
if (updates.estimatedAttentionSpan !== undefined) {
fields.push('estimatedAttentionSpan = ?');
values.push(updates.estimatedAttentionSpan);
}
if (updates.settingsChoices !== undefined) {
fields.push('settingsChoices = ?');
values.push(updates.settingsChoices);
}
if (updates.progressInCurriculum !== undefined) {
fields.push('progressInCurriculum = ?');
values.push(updates.progressInCurriculum);
}
if (updates.averageAccuracy !== undefined) {
fields.push('averageAccuracy = ?');
values.push(updates.averageAccuracy);
}
if (updates.description !== undefined) {
fields.push('description = ?');
values.push(updates.description);
}
if (updates.necessaryBreakTime !== undefined) {
fields.push('necessaryBreakTime = ?');
values.push(updates.necessaryBreakTime);
}
if (fields.length === 0) {
console.log('No fields to update');
return;
}
values.push(id);
const query = `UPDATE users SET ${fields.join(', ')} WHERE id = ?`;
db.transaction(tx => {
tx.executeSql(
query,
values,
(_, result) => { console.log(`Row(s) updated: ${result.rowsAffected}`); },
(_, error) => { console.error('Error updating data', error); }
);
});
};
// delete a row from the users table
const deleteUser = (id) => {
db.transaction(tx => {
tx.executeSql(
'DELETE FROM users WHERE id = ?',
[id],
(_, result) => { console.log(`Row(s) deleted: ${result.rowsAffected}`); },
(_, error) => { console.error('Error deleting data', error); }
);
});
};
// RL tables
export const setupRLTables = async (db) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
// DROP OLD UCB TABLE IF EXISTS
tx.executeSql(
`DROP TABLE IF EXISTS Combos`,
[],
() => console.log("Dropped old Combos table"),
(_, err) => {
console.error("Failed to drop Combos table:", err);
return true;
}
);
// CREATE RL COMBOS TABLE
tx.executeSql(
`CREATE TABLE IF NOT EXISTS Combos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id INTEGER NOT NULL,
state TEXT NOT NULL,
action TEXT NOT NULL,
q_value REAL DEFAULT 0,
last_updated DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(student_id, state, action)
)`,
[],
() => console.log("✅ RL Combos table created"),
(_, err) => {
console.error("Combos table create error:", err);
return true;
}
);
// CREATE INTERACTION LOGS TABLE
tx.executeSql(
`CREATE TABLE IF NOT EXISTS InteractionLogs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
student_id INTEGER NOT NULL,
state TEXT NOT NULL,
action TEXT NOT NULL,
reward INTEGER NOT NULL,
is_correct BOOLEAN,
time_taken REAL,
emotion TEXT,
hints_used INTEGER,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
[],
() => console.log("✅ InteractionLogs table created"),
(_, err) => {
console.error("Logs table create error:", err);
return true;
}
);
}, reject, resolve);
});
};
// CRUD operations for the achievements table
// Insert a new row into the achievements table
const insertAchievement = (name, description, points, user_id) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO achievements (name, description, points, user_id) VALUES (?, ?, ?, ?)',
[name, description, points, user_id],
(_, result) => {
console.log(`A row has been inserted with rowid ${result.insertId}`);
resolve(result);
},
(_, error) => {
console.error('Error inserting data', error);
reject(error);
},
);
});
});
};
// update a row in the achievements table
const updateAchievement = (name, description, points, user_id) => {
db.transaction(tx => {
tx.executeSql(
'UPDATE achievements SET name = ?, description = ?, points = ? WHERE user_id = ?',
[name, description, points, user_id],
(_, result) => {
console.log(`Row(s) updated: ${result.rowsAffected}`);
},
(_, error) => {
console.error('Error updating data', error);
},
);
});
};
// Retrieve all rows from the achievements table
const allUserAchievements = (id) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM achievements WHERE user_id = ?',
[id],
(_, result) => {
resolve(result.rows.raw());
},
(_, error) => {
reject(error);
},
);
});
});
};
// delete a row from the achievements table
const deleteAchievement = (id) => {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql(
'DELETE FROM achievements WHERE id = ?',
[id],
(_, result) => {
console.log(`Row(s) deleted: ${result.rowsAffected}`);
resolve(result);
},
(_, error) => {
console.error('Error deleting data', error);
reject(error);
},