-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueries.js
341 lines (305 loc) · 10.7 KB
/
queries.js
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
const databaseManager = require('./databaseManager');
const userTables = require('./creatingTables/userTables');
async function createTables(tableName, columns) {
try {
// Verificar si la tabla existe
const res = await databaseManager.query('select exists (select * from information_schema.tables where table_name = $1)', [tableName]);
const verifyTable = res.rows[0].exists;
// Si no existe, cree la tabla en supabase
if (!verifyTable) {
let foreignKeyQueries = [];
let columnsQuery = columns.map(column => {
let columnDef = `${column.name} ${column.type}`;
if (column.primaryKey) {
// eslint-disable-next-line no-undef
primaryKeyColumn = column.name;
}
if (column.unique) {
columnDef += ' UNIQUE';
}
if (column.notNull) {
columnDef += ' NOT NULL';
}
if (column.default !== undefined) {
if (!column.identity) {
columnDef += ` DEFAULT ${column.default}`;
}
}
if (column.reference) {
foreignKeyQueries.push(`ALTER TABLE ${tableName} ADD CONSTRAINT ${tableName}_${column.name}_fkey FOREIGN KEY (${column.name}) REFERENCES ${column.reference}`);
}
return columnDef;
}).join(', ');
let createTableQuery = `CREATE TABLE ${tableName} (${columnsQuery})`;
try {
const resCreateTable = await databaseManager.query(createTableQuery);
if (resCreateTable.error) {
console.log("❌ Error to create the table "+ tableName+": ",resCreateTable.error);
} else {
console.log("✅ Table "+tableName+" created successfully");
}
// Habilitar la seguridad a nivel de fila en la tabla supabase
const enableRLSQuery = `ALTER TABLE ${tableName} ENABLE ROW LEVEL SECURITY`;
const resEnableRLS = await databaseManager.query(enableRLSQuery);
if (resEnableRLS.error) {
console.log("❌📜 Error to create the Row level security: ",resEnableRLS.error);
} else {
console.log('📜 Row level security enabled');
}
// Add primary key to id
const addPrimaryKeyQuery = `ALTER TABLE ${tableName} ADD CONSTRAINT ${tableName}_pkey PRIMARY KEY (id)`;
const resPK = await databaseManager.query(addPrimaryKeyQuery);
if (resPK.error) {
console.log("❌🔑 Error to create the Row level security: ",resPK.error);
} else {
console.log('🔑 Primary key added');
}
// Agregar las claves foraneas a las tablas que tengan la referencia
for (const foreignKeyQuery of foreignKeyQueries) {
const resFK = await databaseManager.query(foreignKeyQuery);
if (resFK.error) {
console.log("❌🗝️ Error to add foreign key: ", resFK.error);
} else {
console.log('🗝️ Foreign key added');
}
}
} catch (error) {
console.log("⛔ Error to create the table: ",error);
}
} else {
console.log("✅ Table " +tableName+ " already exists");
}
} catch (e) {
console.log("📵 Error to entablish comunication to supabase:",e);
}
}
// Verificar la existencia de la tabla
async function verifyTable(tableName) {
try {
const result = await databaseManager.query(`
SELECT exists (select * from information_schema.tables where table_name = $1)
`, [tableName]);
return result.rows;
} catch (e) {
console.log(e);
}
}
// Funcion que consulta la bd y obtiene los usuarios de la tabla
async function getUsers() {
try {
const result = await databaseManager.query(`
SELECT id, username, role
FROM ${userTables.users.tableName}
`);
return result.rows;
} catch (e) {
console.log(e);
}
}
// Funcion que consulta la bd y obtiene los puntajes de la tabla
async function getScores() {
try {
const result = await databaseManager.query(`
SELECT *
FROM ${userTables.scores.tableName}
`);
return result.rows;
} catch (e) {
console.log(e);
}
}
// Funcion que consulta la bd y obtiene las preguntas de la tabla
async function getQuestions() {
try {
const result = await databaseManager.query(`
SELECT *
FROM ${userTables.quotes.tableName}
`);
return result.rows;
} catch (e) {
console.log(e);
}
}
// Funcion que crea un usuario en la bd
async function createUser(username, email, supabase_user_id, role, created_at) {
try {
const result = await databaseManager.query(`
INSERT INTO ${userTables.users.tableName} (username, email, supabase_user_id, role, created_at)
VALUES ($1, $2, $3, $4, $5)
RETURNING *
`, [username, email,supabase_user_id, role, created_at]);
return result;
} catch (e) {
console.log(e);
throw e;
}
}
// Valida si existe el usuario en la bd
async function userExists(email) {
try {
const result = await databaseManager.query(`
SELECT *
FROM ${userTables.users.tableName}
WHERE email = $1
`, [email]);
return result;
} catch (e) {
console.log(e);
throw e;
}
}
// Funcion que obtiene una pregunta aleatoria
async function getRandomQuestion() {
try {
const result = await databaseManager.query(`
SELECT q.id, q.quote, c.name as correct_character,
(SELECT array_agg(c2.name)
FROM ${userTables.character.tableName} c2
WHERE c2.id != q.character_id
ORDER BY RANDOM()
LIMIT 10) as incorrect_options
FROM ${userTables.quotes.tableName} q
JOIN ${userTables.character.tableName} c ON q.character_id = c.id
ORDER BY RANDOM()
LIMIT 1
`);
// Verificar si se obtuvo un resultado
if (result.rows.length === 0) {
console.error("No questions found in the database.");
return undefined;
}
const incorrectOptions = result.rows[0].incorrect_options;
// Asegurarse de que incorrectOptions tenga al menos 3 elementos
if (!incorrectOptions || incorrectOptions.length < 3) {
console.error("Not enough incorrect options available.");
return undefined;
}
const shuffledOptions = incorrectOptions.sort(() => Math.random() - 0.5).slice(0, 3);
return {
...result.rows[0],
incorrect_options: shuffledOptions
};
} catch (e) {
console.log(e);
throw e;
}
}
// Función que obtiene las frases de un personaje específico
async function getQuotesByCharacter(characterId) {
try {
const characterResult = await databaseManager.query(`
SELECT id, name
FROM ${userTables.character.tableName}
WHERE id = $1
`, [characterId]);
// Si no se encuentra el personaje, se retorna null
if (characterResult.rows.length === 0) {
return null;
}
// Se obtiene el nombre del personaje
const character = characterResult.rows[0];
// Se obtiene las frases del personaje
const quotesResult = await databaseManager.query(`
SELECT id, quote
FROM ${userTables.quotes_users.tableName}
WHERE character_id = $1
`, [characterId]);
// Se obtiene el total de frases
const totalQuotes = quotesResult.rows.length;
return {
character: character,
totalQuotes: totalQuotes,
quotes: quotesResult.rows
};
} catch (e) {
console.log("Error al obtener frases por personaje:", e);
throw e;
}
}
// Funcion que obtiene los personajes de la bd
async function getCharacters() {
try {
const result = await databaseManager.query(`
SELECT id, name
FROM ${userTables.character.tableName}
`);
return result.rows;
} catch (e) {
console.log(e);
}
}
// Función para obtener un usuario por ID
async function getUserById(id) {
try {
const result = await databaseManager.query(`
SELECT id, username, email, role
FROM ${userTables.users.tableName}
WHERE id = $1
`, [id]);
return result.rows[0] || null;
} catch (e) {
console.error("Error getting user by ID:", e);
throw e;
}
}
async function changeUserRole(userId, newRole) {
try {
const result = await databaseManager.query(
`UPDATE ${userTables.users.tableName} SET role = $1 WHERE id = $2 RETURNING *`,
[newRole, userId]);
if (result.rows.length === 0) {
throw new Error('User not found');
}
return result.rows[0];
} catch (error) {
console.error('Error changing user role:', error);
throw error;
}
}
async function getUserRole(userId) {
try {
const result = await databaseManager.query(`
SELECT role
FROM ${userTables.users.tableName}
WHERE id = $1`, [userId]);
if (result.rows.length === 0) {
throw new Error('Role not found');
}
return result.rows[0];
} catch (error) {
console.error('Error obtain user role:', error);
throw error;
}
}
// Función para obtener TODOS los datos de un usuario por ID de Supabase
async function getUserDataSupabaseAuth(userId) {
try {
const result = await databaseManager.query(`
SELECT *
FROM ${userTables.users.tableName}
WHERE supabase_user_id = $1`, [userId]);
if (result.rows.length === 0) {
throw new Error('Role not found');
}
return result.rows[0];
} catch (error) {
console.error('Error obtain user role:', error);
throw error;
}
}
module.exports = {
createTables,
verifyTable,
getUsers,
getScores,
getQuestions,
createUser,
userExists,
getRandomQuestion,
getQuotesByCharacter,
getCharacters,
getUserById,
changeUserRole,
getUserRole,
getUserDataSupabaseAuth,
}