-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
428 lines (373 loc) · 11.7 KB
/
database.js
File metadata and controls
428 lines (373 loc) · 11.7 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
const { Database } = require('arangojs');
require('dotenv').config();
class ArangoDBManager {
constructor() {
this.db = new Database({
url: process.env.ARANGO_URL || 'http://localhost:8529',
databaseName: process.env.ARANGO_DATABASE || 'multimodal_demo',
auth: {
username: process.env.ARANGO_USERNAME || 'root',
password: process.env.ARANGO_PASSWORD || ''
}
});
}
async initializeDatabase() {
try {
// First, connect to the _system database to manage databases
const systemDb = new Database({
url: process.env.ARANGO_URL || 'http://localhost:8529',
databaseName: '_system',
auth: {
username: process.env.ARANGO_USERNAME || 'root',
password: process.env.ARANGO_PASSWORD || ''
}
});
// Check if database exists, create if not
const databases = await systemDb.listDatabases();
const dbName = process.env.ARANGO_DATABASE || 'multimodal_demo';
if (!databases.includes(dbName)) {
console.log(`Creating database: ${dbName}`);
await systemDb.createDatabase(dbName);
}
// Now switch to our target database
this.db = new Database({
url: process.env.ARANGO_URL || 'http://localhost:8529',
databaseName: dbName,
auth: {
username: process.env.ARANGO_USERNAME || 'root',
password: process.env.ARANGO_PASSWORD || ''
}
});
// Initialize collections
await this.initializeCollections();
console.log('Database initialized successfully');
} catch (error) {
console.error('Error initializing database:', error);
throw error;
}
}
async initializeCollections() {
// Document Collection: Users
const usersCollection = this.db.collection('users');
if (!await usersCollection.exists()) {
await usersCollection.create();
console.log('Created users collection');
}
// Document Collection: Posts
const postsCollection = this.db.collection('posts');
if (!await postsCollection.exists()) {
await postsCollection.create();
console.log('Created posts collection');
}
// Edge Collection: Follows (for graph relationships)
const followsCollection = this.db.collection('follows');
if (!await followsCollection.exists()) {
await followsCollection.create({ type: 'edge' });
console.log('Created follows edge collection');
}
// Edge Collection: Likes (for graph relationships)
const likesCollection = this.db.collection('likes');
if (!await likesCollection.exists()) {
await likesCollection.create({ type: 'edge' });
console.log('Created likes edge collection');
}
// Create graph if it doesn't exist
const graphName = 'social_network';
const graphs = await this.db.listGraphs();
if (!graphs.some(g => g._key === graphName)) {
await this.db.createGraph(graphName, [
{
collection: 'follows',
from: ['users'],
to: ['users']
},
{
collection: 'likes',
from: ['users'],
to: ['posts']
}
]);
console.log('Created social_network graph');
}
}
// Document operations
async createUser(userData) {
const users = this.db.collection('users');
return await users.save({
...userData,
createdAt: new Date(),
followerCount: 0,
followingCount: 0
});
}
async createPost(postData) {
const posts = this.db.collection('posts');
return await posts.save({
...postData,
createdAt: new Date(),
likeCount: 0
});
}
// Graph operations
async followUser(followerId, followeeId) {
const follows = this.db.collection('follows');
const users = this.db.collection('users');
try {
// Check if follow relationship already exists
const existingFollow = await this.db.query(`
FOR follow IN follows
FILTER follow._from == @from AND follow._to == @to
RETURN follow
`, {
from: `users/${followerId}`,
to: `users/${followeeId}`
});
const existingFollows = await existingFollow.all();
if (existingFollows.length > 0) {
throw new Error('Follow relationship already exists');
}
// Create follow relationship
const result = await follows.save({
_from: `users/${followerId}`,
_to: `users/${followeeId}`,
createdAt: new Date()
});
// Update follower counts using AQL
await this.db.query(`
FOR user IN users
FILTER user._key == @followerId
UPDATE user WITH { followingCount: (user.followingCount || 0) + 1 } IN users
`, { followerId });
await this.db.query(`
FOR user IN users
FILTER user._key == @followeeId
UPDATE user WITH { followerCount: (user.followerCount || 0) + 1 } IN users
`, { followeeId });
return result;
} catch (error) {
console.error('Error in followUser:', error);
throw error;
}
}
async likePost(userId, postId) {
const likes = this.db.collection('likes');
const posts = this.db.collection('posts');
try {
// Check if like already exists
const existingLike = await this.db.query(`
FOR l IN likes
FILTER l._from == @from AND l._to == @to
RETURN l
`, {
from: `users/${userId}`,
to: `posts/${postId}`
});
const existingLikes = await existingLike.all();
if (existingLikes.length > 0) {
throw new Error('User has already liked this post');
}
// Create like relationship
const result = await likes.save({
_from: `users/${userId}`,
_to: `posts/${postId}`,
createdAt: new Date()
});
// Update like count using AQL
await this.db.query(`
FOR post IN posts
FILTER post._key == @postId
UPDATE post WITH { likeCount: (post.likeCount || 0) + 1 } IN posts
`, { postId });
return result;
} catch (error) {
console.error('Error in likePost:', error);
throw error;
}
}
// Key-Value operations (using document collection as key-value store)
async setUserSetting(userId, key, value) {
const settingsCollection = this.db.collection('user_settings');
// Create collection if it doesn't exist
if (!await settingsCollection.exists()) {
await settingsCollection.create();
}
return await settingsCollection.save({
_key: `${userId}_${key}`,
userId,
key,
value,
updatedAt: new Date()
}, { overwrite: true });
}
async getUserSetting(userId, key) {
const settingsCollection = this.db.collection('user_settings');
try {
return await settingsCollection.document(`${userId}_${key}`);
} catch (error) {
return null;
}
}
// Complex queries demonstrating multimodal capabilities
async getUserFeed(userId, limit = 10) {
try {
const query = `
FOR follow IN follows
FILTER follow._from == @userDoc
LET followedUserId = PARSE_IDENTIFIER(follow._to).key
FOR post IN posts
FILTER post.authorId == followedUserId
SORT post.createdAt DESC
LIMIT @limit
LET author = DOCUMENT(follow._to)
RETURN {
post: post,
author: {
_key: author._key,
username: author.username,
displayName: author.displayName
}
}
`;
const cursor = await this.db.query(query, {
userDoc: `users/${userId}`,
limit
});
return await cursor.all();
} catch (error) {
console.error('Error in getUserFeed:', error);
// Return empty array if no follows exist
return [];
}
}
async getPopularUsers(limit = 5) {
try {
const query = `
FOR user IN users
LET followerCount = LENGTH(
FOR follow IN follows
FILTER follow._to == CONCAT('users/', user._key)
RETURN 1
)
SORT followerCount DESC, user.createdAt DESC
LIMIT @limit
RETURN MERGE(user, { followerCount: followerCount })
`;
const cursor = await this.db.query(query, { limit });
return await cursor.all();
} catch (error) {
console.error('Error in getPopularUsers:', error);
return [];
}
}
async getMutualFollows(userId1, userId2) {
try {
const query = `
LET user1_follows = (
FOR follow IN follows
FILTER follow._from == @user1Doc
RETURN PARSE_IDENTIFIER(follow._to).key
)
LET user2_follows = (
FOR follow IN follows
FILTER follow._from == @user2Doc
RETURN PARSE_IDENTIFIER(follow._to).key
)
LET mutual = INTERSECTION(user1_follows, user2_follows)
FOR userId IN mutual
LET user = DOCUMENT(CONCAT('users/', userId))
RETURN user
`;
const cursor = await this.db.query(query, {
user1Doc: `users/${userId1}`,
user2Doc: `users/${userId2}`
});
return await cursor.all();
} catch (error) {
console.error('Error in getMutualFollows:', error);
return [];
}
}
async getAllUsers() {
const users = this.db.collection('users');
return await users.all().then(cursor => cursor.all());
}
async getAllPosts() {
const posts = this.db.collection('posts');
return await posts.all().then(cursor => cursor.all());
}
async getUser(userId) {
const users = this.db.collection('users');
return await users.document(userId);
}
// Helper methods for debugging and validation
async getFollowRelationships(userId = null) {
try {
let query = `FOR follow IN follows RETURN follow`;
let params = {};
if (userId) {
query = `FOR follow IN follows FILTER follow._from == @userDoc OR follow._to == @userDoc RETURN follow`;
params = { userDoc: `users/${userId}` };
}
const cursor = await this.db.query(query, params);
return await cursor.all();
} catch (error) {
console.error('Error getting follow relationships:', error);
return [];
}
}
async getLikeRelationships(userId = null) {
try {
let query = `FOR l IN likes RETURN l`;
let params = {};
if (userId) {
query = `FOR l IN likes FILTER l._from == @userDoc RETURN l`;
params = { userDoc: `users/${userId}` };
}
const cursor = await this.db.query(query, params);
return await cursor.all();
} catch (error) {
console.error('Error getting like relationships:', error);
return [];
}
}
async getUserStats(userId) {
try {
const query = `
LET user = DOCUMENT('users', @userId)
LET followingCount = LENGTH(
FOR follow IN follows
FILTER follow._from == @userDoc
RETURN 1
)
LET followerCount = LENGTH(
FOR follow IN follows
FILTER follow._to == @userDoc
RETURN 1
)
LET likeCount = LENGTH(
FOR l IN likes
FILTER l._from == @userDoc
RETURN 1
)
RETURN {
user: user,
stats: {
followingCount: followingCount,
followerCount: followerCount,
likeCount: likeCount
}
}
`;
const cursor = await this.db.query(query, {
userId: userId,
userDoc: `users/${userId}`
});
const results = await cursor.all();
return results[0] || null;
} catch (error) {
console.error('Error getting user stats:', error);
return null;
}
}
}
module.exports = ArangoDBManager;