0949fc98712c870fae9dd7d13d549ec8b0eae3cb
1 var db
= require("../utils/database");
4 * Structure table Games:
6 * vid: integer (variant id)
7 * fenStart: varchar (initial position)
8 * fen: varchar (current position)
10 * score: varchar (result)
12 * Structure table Players:
17 * Structure table Moves:
19 * squares: varchar (description)
27 create: function(vid
, fen
, timeControl
, players
, cb
)
29 db
.serialize(function() {
31 "INSERT INTO Games (vid, fenStart, fen, score, timeControl) VALUES " +
32 "(" + vid
+ ",'" + fen
+ "','" + fen
+ "','*','" + timeControl
+ "')";
33 db
.run(query
, function(err
) {
36 players
.forEach((p
,idx
) => {
37 const color
= (idx
==0 ? "w" : "b");
39 "INSERT INTO Players VALUES " +
40 "(" + this.lastID
+ "," + p
.id
+ ",'" + color
+ "')";
43 cb(null, {gid: this.lastID
});
48 // TODO: queries here could be async, and wait for all to complete
49 getOne: function(id
, cb
)
51 db
.serialize(function() {
52 // TODO: optimize queries?
54 "SELECT g.id, g.vid, g.fen, g.fenStart, g.timeControl, g.score, " +
60 db
.get(query
, (err
,gameInfo
) => {
64 "SELECT p.uid, p.color, u.name " +
68 "WHERE p.gid = " + id
;
69 db
.all(query
, (err2
,players
) => {
73 "SELECT squares, message, played, idx " +
76 db
.all(query
, (err3
,moves
) => {
79 const game
= Object
.assign({},
86 return cb(null, game
);
93 getByUser: function(uid
, excluded
, cb
)
95 db
.serialize(function() {
96 // Next query is fine because a player appear at most once in a game
100 "WHERE uid " + (excluded
? "<>" : "=") + " " + uid
;
101 db
.all(query
, (err
,gameIds
) => {
104 gameIds
= gameIds
|| []; //might be empty
106 for (let i
=0; i
<gameIds
.length
; i
++)
108 GameModel
.getOne(gameIds
[i
]["gid"], (err2
,game
) => {
111 gameArray
.push(game
);
112 // Call callback function only when gameArray is complete:
113 if (i
== gameIds
.length
- 1)
114 return cb(null, gameArray
);
121 getPlayers: function(id
, cb
)
123 db
.serialize(function() {
128 db
.all(query
, (err
,players
) => {
129 return cb(err
, players
);
134 // obj can have fields move, fen and/or score
135 update: function(id
, obj
)
137 db
.parallelize(function() {
142 query
+= "fen = '" + obj
.fen
+ "',";
144 query
+= "score = '" + obj
.score
+ "',";
145 query
= query
.slice(0,-1); //remove last comma
146 query
+= " WHERE id = " + id
;
152 "INSERT INTO Moves (gid, squares, message, played, idx) VALUES " +
153 "(" + id
+ ",'" + JSON
.stringify(m
.squares
) + "','" + m
.message
+
154 "'," + m
.played
+ "," + m
.idx
+ ")";
162 db
.parallelize(function() {
164 "DELETE FROM Games " +
168 "DELETE FROM Players " +
172 "DELETE FROM Moves " +
179 module
.exports
= GameModel
;