-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdb.js
More file actions
1451 lines (1290 loc) · 54.2 KB
/
db.js
File metadata and controls
1451 lines (1290 loc) · 54.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 config from '#config'
import pg from 'pg'
const { Pool } = pg
let pool = null
export function getPool() {
return pool
}
export let db = {
collection: dummy_collection
}
export let collection = {
illust: dummy_collection(),
chat_setting: dummy_collection(),
novel: dummy_collection(),
ranking: dummy_collection(),
author: dummy_collection(),
telegraph: dummy_collection()
}
/**
* Initialize PostgreSQL connection
*/
export async function db_initial() {
if (process.env.DBLESS) {
console.warn('WARNING', 'No Database Mode(DBLESS) is not recommend for production environment.')
} else {
try {
pool = new Pool({
connectionString: config.postgres.uri,
max: 50, // Increase for 2.2M dataset
min: 5, // Keep warm connections
idleTimeoutMillis: 30000, // Close idle after 30s
connectionTimeoutMillis: 3000, // Timeout acquiring connection
statement_timeout: 30000 // Kill queries after 30s
})
// Test connection
await pool.query('SELECT 1')
console.log('PostgreSQL connected')
// Initialize collection wrappers
collection.illust = createIllustCollection()
collection.chat_setting = createChatSettingCollection()
collection.novel = createNovelCollection()
collection.ranking = createRankingCollection()
collection.author = createAuthorCollection()
collection.telegraph = createTelegraphCollection()
db = { collection: (name) => collection[name] }
}
catch (error) {
console.error('Connect Database Error', error)
process.exit()
}
}
}
/**
* Close PostgreSQL connection pool
*/
export async function db_close() {
if (pool) {
await pool.end()
console.log('PostgreSQL pool closed')
}
}
// ============================================
// New Direct SQL API (No Wrapper)
// ============================================
/**
* Get illust by ID
* Returns MongoDB-compatible format for backward compatibility
* @param {number} id - Illust ID
* @param {Pool} testPool - Optional pool for testing (uses global pool if not provided)
*/
export async function getIllust(id, testPool = null) {
const queryPool = testPool || pool
if (!queryPool) {
return null
}
const illustResult = await queryPool.query(
'SELECT i.*, a.author_name FROM illust i LEFT JOIN author a ON i.author_id = a.author_id WHERE i.id = $1',
[id]
)
if (!illustResult.rows[0]) {
return null
}
const illust = illustResult.rows[0]
// For ugoira (type=2), get ugoira_meta
if (illust.type === 2) {
const ugoiraResult = await queryPool.query(
'SELECT * FROM ugoira_meta WHERE illust_id = $1',
[id]
)
const ugoira = ugoiraResult.rows[0]
return rebuildIllustFromRow(illust, [], ugoira)
}
// For regular illusts, get images
const imagesResult = await queryPool.query(
'SELECT * FROM illust_image WHERE illust_id = $1 ORDER BY page_index',
[id]
)
return rebuildIllustFromRow(illust, imagesResult.rows, null)
}
/**
* Update or insert illust
* @param {number} id - Illust ID
* @param {object} data - Data to update (can include imgs_, author_name, etc.)
* @param {Pool} testPool - Optional pool for testing
* @param {object} options - Options like { upsert: true }
*/
export async function updateIllust(id, data, testPool = null, options = {}) {
const queryPool = testPool || pool
if (!queryPool) {
return { acknowledged: false }
}
const upsert = options.upsert || false
try {
await queryPool.query('BEGIN')
// Extract illust main fields
const illustFields = ['title', 'type', 'comment', 'description', 'author_id',
'tags', 'sl', 'restrict', 'x_restrict', 'ai_type', 'page_count', 'deleted', 'deleted_at']
const illustData = {}
for (const field of illustFields) {
if (data[field] !== undefined) {
illustData[field] = data[field]
}
}
// Handle author - insert or update author_name
if (data.author_id && data.author_name) {
await queryPool.query(`
INSERT INTO author (author_id, author_name)
VALUES ($1, $2)
ON CONFLICT (author_id) DO UPDATE SET author_name = $2, updated_at = NOW()
`, [data.author_id, data.author_name])
}
// Upsert illust main table
if (Object.keys(illustData).length > 0 || upsert) {
const columns = ['id', ...Object.keys(illustData)]
const values = [id, ...Object.values(illustData)]
const placeholders = values.map((_, i) => `$${i + 1}`).join(', ')
const updateClauses = Object.keys(illustData)
.map((col, i) => `${col} = $${i + 2}`)
.join(', ')
if (updateClauses) {
if (upsert) {
// INSERT with ON CONFLICT - create if not exists
await queryPool.query(`
INSERT INTO illust (${columns.join(', ')})
VALUES (${placeholders})
ON CONFLICT (id) DO UPDATE SET ${updateClauses}, updated_at = NOW()
`, values)
} else {
// UPDATE only - don't create new record
const result = await queryPool.query(`
UPDATE illust SET ${updateClauses}, updated_at = NOW()
WHERE id = $1
`, values)
if (result.rowCount === 0) {
throw new Error(`Record not exist: illust ${id}`)
}
}
} else if (upsert) {
await queryPool.query(`
INSERT INTO illust (id, title) VALUES ($1, $2)
ON CONFLICT (id) DO NOTHING
`, [id, data.title || ''])
}
}
// Handle imgs_ field - convert to illust_image or ugoira_meta rows
if (data.imgs_) {
const imgs = data.imgs_
const type = data.type ?? 0
if (type === 2 && imgs.cover_img_url) {
// Ugoira - update ugoira_meta
await queryPool.query(`
INSERT INTO ugoira_meta (illust_id, cover_img_url, width, height)
VALUES ($1, $2, $3, $4)
ON CONFLICT (illust_id) DO UPDATE SET
cover_img_url = $2, width = $3, height = $4, updated_at = NOW()
`, [
id,
imgs.cover_img_url,
imgs.size?.[0]?.width || null,
imgs.size?.[0]?.height || null
])
} else if (imgs.thumb_urls) {
// Regular illust - update illust_image
// Delete existing images first
await queryPool.query('DELETE FROM illust_image WHERE illust_id = $1', [id])
// Insert new images
for (let i = 0; i < imgs.thumb_urls.length; i++) {
await queryPool.query(`
INSERT INTO illust_image (illust_id, page_index, thumb_url, regular_url, original_url, width, height)
VALUES ($1, $2, $3, $4, $5, $6, $7)
`, [
id,
i,
imgs.thumb_urls[i] || null,
imgs.regular_urls?.[i] || null,
imgs.original_urls?.[i] || null,
imgs.size?.[i]?.width || null,
imgs.size?.[i]?.height || null
])
}
}
}
// Handle tg_file_id update
if (data.tg_file_id !== undefined) {
if (data.type === 2) {
// Ugoira - update ugoira_meta
await queryPool.query(`
UPDATE ugoira_meta SET tg_file_id = $1, updated_at = NOW()
WHERE illust_id = $2
`, [data.tg_file_id, id])
} else {
// Regular illust - update first image's tg_file_id
await queryPool.query(`
UPDATE illust_image
SET tg_file_id = $1, updated_at = NOW()
WHERE illust_id = $2 AND page_index = 0
`, [data.tg_file_id, id])
}
}
await queryPool.query('COMMIT')
return { acknowledged: true, matchedCount: 1, modifiedCount: 1 }
} catch (error) {
await queryPool.query('ROLLBACK')
console.error('updateIllust error:', error)
throw error
}
}
/**
* Delete an illust from the database
* @param {number} id - Illust ID
* @param {Pool} testPool - Optional test pool
* @returns {Promise<Object>} Result with deletedCount
*/
export async function deleteIllust(id, testPool = null) {
const queryPool = testPool || pool
if (!queryPool) return { acknowledged: true, deletedCount: 0 }
try {
await queryPool.query('BEGIN')
// Delete related data first (foreign keys cascade if set, but let's be explicit)
await queryPool.query('DELETE FROM illust_image WHERE illust_id = $1', [id])
await queryPool.query('DELETE FROM ugoira_meta WHERE illust_id = $1', [id])
// Delete the main illust record
const result = await queryPool.query('DELETE FROM illust WHERE id = $1', [id])
await queryPool.query('COMMIT')
return { acknowledged: true, deletedCount: result.rowCount }
} catch (error) {
await queryPool.query('ROLLBACK')
console.error('deleteIllust error:', error)
throw error
}
}
/**
* Find multiple illusts by IDs
* @param {number[]} ids - Array of illust IDs
* @param {Pool} testPool - Optional test pool
* @returns {Promise<Array>} Array of illust objects
*/
export async function findManyIllusts(ids, testPool = null) {
const queryPool = testPool || pool
if (!queryPool) return []
if (!Array.isArray(ids) || ids.length === 0) return []
// Simpler approach that works with pg-mem: fetch each illust separately
// In production PostgreSQL, we could use a more optimized query with json_agg
// But for compatibility with pg-mem (testing), we use this approach
const results = await Promise.all(ids.map(id => getIllust(id, queryPool)))
// Filter out null results (non-existent illusts)
return results.filter(illust => illust !== null)
}
/**
* Helper: Rebuild MongoDB-style illust object from PostgreSQL rows
*/
function rebuildIllustFromRow(illust, images, ugoira) {
const result = {
id: illust.id,
title: illust.title || '',
type: illust.type,
comment: illust.comment,
description: illust.description,
author_id: illust.author_id,
author_name: illust.author_name || 'Unknown',
tags: Array.isArray(illust.tags) ? illust.tags : [],
sl: illust.sl,
restrict: illust.restrict,
x_restrict: illust.x_restrict,
ai_type: illust.ai_type,
deleted: illust.deleted,
deleted_at: illust.deleted_at
}
if (illust.type === 2 && ugoira) {
// Ugoira
result.imgs_ = {
cover_img_url: ugoira.cover_img_url,
size: [{ width: ugoira.width, height: ugoira.height }]
}
result.tg_file_id = ugoira.tg_file_id
} else if (images && images.length > 0) {
// Regular illust
result.imgs_ = {
thumb_urls: images.map(img => img.thumb_url),
regular_urls: images.map(img => img.regular_url),
original_urls: images.map(img => img.original_url),
size: images.map(img => ({ width: img.width, height: img.height }))
}
if (images[0]?.tg_file_id) {
result.tg_file_id = images[0].tg_file_id
}
}
return result
}
// ============================================
// Illust Collection Wrapper
// ============================================
function createIllustCollection() {
return {
findOne: async (query) => {
if (!query || query.id === undefined) return null
const id = query.id
const illustResult = await pool.query(
'SELECT i.*, a.author_name FROM illust i LEFT JOIN author a ON i.author_id = a.author_id WHERE i.id = $1',
[id]
)
if (!illustResult.rows[0]) return null
const illust = illustResult.rows[0]
// For ugoira (type=2), get ugoira_meta
if (illust.type === 2) {
const ugoiraResult = await pool.query(
'SELECT * FROM ugoira_meta WHERE illust_id = $1',
[id]
)
const ugoira = ugoiraResult.rows[0]
if (ugoira) {
return rebuildIllustObject(illust, [], ugoira)
}
}
// For regular illusts, get images
const imagesResult = await pool.query(
'SELECT * FROM illust_image WHERE illust_id = $1 ORDER BY page_index',
[id]
)
return rebuildIllustObject(illust, imagesResult.rows, null)
},
find: (query) => {
return new PostgresCursor('illust', query, pool)
},
updateOne: async (query, update, options = {}) => {
const id = query.id
const data = update.$set || {}
const upsert = options.upsert || false
try {
await pool.query('BEGIN')
// Extract illust main fields
const illustFields = ['title', 'type', 'comment', 'description', 'author_id',
'tags', 'sl', 'restrict', 'x_restrict', 'ai_type', 'page_count', 'deleted', 'deleted_at']
const illustData = {}
for (const field of illustFields) {
if (data[field] !== undefined) {
illustData[field] = data[field]
}
}
// Handle author - insert or update author_name
if (data.author_id && data.author_name) {
await pool.query(`
INSERT INTO author (author_id, author_name)
VALUES ($1, $2)
ON CONFLICT (author_id) DO UPDATE SET author_name = $2, updated_at = NOW()
`, [data.author_id, data.author_name])
}
// Upsert illust main table
if (Object.keys(illustData).length > 0 || upsert) {
const columns = ['id', ...Object.keys(illustData)]
const values = [id, ...Object.values(illustData)]
const placeholders = values.map((_, i) => `$${i + 1}`).join(', ')
const updateClauses = Object.keys(illustData)
.map((col, i) => `${col} = $${i + 2}`)
.join(', ')
if (updateClauses) {
await pool.query(`
INSERT INTO illust (${columns.join(', ')})
VALUES (${placeholders})
ON CONFLICT (id) DO UPDATE SET ${updateClauses}, updated_at = NOW()
`, values)
} else if (upsert) {
await pool.query(`
INSERT INTO illust (id, title) VALUES ($1, $2)
ON CONFLICT (id) DO NOTHING
`, [id, data.title || ''])
}
}
// Handle imgs_ field - convert to illust_image rows
if (data.imgs_) {
const imgs = data.imgs_
const type = data.type ?? 0
if (type === 2 && imgs.cover_img_url) {
// Ugoira - update ugoira_meta
await pool.query(`
INSERT INTO ugoira_meta (illust_id, cover_img_url, width, height)
VALUES ($1, $2, $3, $4)
ON CONFLICT (illust_id) DO UPDATE SET
cover_img_url = $2, width = $3, height = $4, updated_at = NOW()
`, [
id,
imgs.cover_img_url,
imgs.size?.[0]?.width || null,
imgs.size?.[0]?.height || null
])
} else if (imgs.thumb_urls) {
// Regular illust - update illust_image
// Delete existing images first
await pool.query('DELETE FROM illust_image WHERE illust_id = $1', [id])
// Insert new images
for (let i = 0; i < imgs.thumb_urls.length; i++) {
await pool.query(`
INSERT INTO illust_image (illust_id, page_index, thumb_url, regular_url, original_url, width, height)
VALUES ($1, $2, $3, $4, $5, $6, $7)
`, [
id,
i,
imgs.thumb_urls[i] || null,
imgs.regular_urls?.[i] || null,
imgs.original_urls?.[i] || null,
imgs.size?.[i]?.width || null,
imgs.size?.[i]?.height || null
])
}
}
}
// Handle tg_file_id update for ugoira
if (data.tg_file_id !== undefined && data.type === 2) {
await pool.query(`
UPDATE ugoira_meta SET tg_file_id = $1, updated_at = NOW()
WHERE illust_id = $2
`, [data.tg_file_id, id])
}
await pool.query('COMMIT')
return { acknowledged: true, matchedCount: 1, modifiedCount: 1 }
} catch (error) {
await pool.query('ROLLBACK')
console.error('updateOne error:', error)
throw error
}
},
insertOne: async (doc) => {
// Use direct updateIllust with upsert
return await updateIllust(doc.id, doc, pool, { upsert: true })
},
deleteOne: async (query) => {
// Use direct deleteIllust
return await deleteIllust(query.id, pool)
},
createIndex: async () => {
// Indexes are created in schema.sql
return true
}
}
}
/**
* Rebuild MongoDB-style illust object from PostgreSQL data
*/
function rebuildIllustObject(illust, images, ugoira) {
const result = {
id: illust.id,
title: illust.title || '',
type: illust.type,
comment: illust.comment,
description: illust.description,
author_id: illust.author_id,
author_name: illust.author_name || 'Unknown', // Null safety
tags: Array.isArray(illust.tags) ? illust.tags : [],
sl: illust.sl,
restrict: illust.restrict,
x_restrict: illust.x_restrict,
ai_type: illust.ai_type,
deleted: illust.deleted,
deleted_at: illust.deleted_at
}
if (illust.type === 2 && ugoira) {
// Ugoira
result.imgs_ = {
cover_img_url: ugoira.cover_img_url,
size: [{ width: ugoira.width, height: ugoira.height }]
}
result.tg_file_id = ugoira.tg_file_id
} else if (images.length > 0) {
// Regular illust
result.imgs_ = {
thumb_urls: images.map(img => img.thumb_url),
regular_urls: images.map(img => img.regular_url),
original_urls: images.map(img => img.original_url),
size: images.map(img => ({ width: img.width, height: img.height }))
}
// Use first image's tg_file_id as the illust's tg_file_id
if (images[0]?.tg_file_id) {
result.tg_file_id = images[0].tg_file_id
}
}
return result
}
// ============================================
// Chat Setting Collection Wrapper
// ============================================
function createChatSettingCollection() {
return {
findOne: async (query) => {
if (!query || query.id === undefined) return null
const id = query.id
// Check for subscription query
for (const key in query) {
if (key.startsWith('subscribe_author_list.')) {
const authorId = key.split('.')[1]
const result = await pool.query(
'SELECT 1 FROM chat_subscribe_author WHERE chat_id = $1 AND author_id = $2',
[id, authorId]
)
return result.rows[0] ? { id } : null
}
if (key.startsWith('subscribe_author_bookmarks_list.')) {
const authorId = key.split('.')[1]
const result = await pool.query(
'SELECT 1 FROM chat_subscribe_bookmarks WHERE chat_id = $1 AND author_id = $2',
[id, authorId]
)
return result.rows[0] ? { id } : null
}
}
// Query main settings
const settingResult = await pool.query('SELECT * FROM chat_setting WHERE id = $1', [id])
const setting = settingResult.rows[0]
if (!setting) {
// Return empty object structure for new chats
return null
}
// Query subscriptions
const subscribeAuthorsResult = await pool.query(
'SELECT author_id, subscribed_at FROM chat_subscribe_author WHERE chat_id = $1',
[id]
)
const subscribeBookmarksResult = await pool.query(
'SELECT author_id, subscribed_at FROM chat_subscribe_bookmarks WHERE chat_id = $1',
[id]
)
// Query linked chats
const linksResult = await pool.query(
'SELECT * FROM chat_link WHERE source_chat_id = $1',
[id]
)
return rebuildSettingObject(setting, subscribeAuthorsResult.rows, subscribeBookmarksResult.rows, linksResult.rows)
},
find: (query) => {
return new ChatSettingCursor(query, pool)
},
updateOne: async (query, update, options = {}) => {
const id = query.id
const setData = update.$set || {}
const unsetData = update.$unset || {}
const upsert = options.upsert || false
try {
// START TRANSACTION
await pool.query('BEGIN')
// Handle $set operations
if (Object.keys(setData).length > 0) {
const columns = []
const values = [id]
let paramIndex = 2
// Handle format fields
if (setData.format) {
for (const key in setData.format) {
columns.push(`format_${key} = $${paramIndex}`)
values.push(setData.format[key])
paramIndex++
}
}
// Handle default fields
if (setData.default) {
for (const key in setData.default) {
columns.push(`default_${key} = $${paramIndex}`)
values.push(setData.default[key])
paramIndex++
}
}
// Handle subscription lists
for (const key in setData) {
if (key.startsWith('subscribe_author_list.')) {
const authorId = key.split('.')[1]
await pool.query(`
INSERT INTO chat_subscribe_author (chat_id, author_id, subscribed_at)
VALUES ($1, $2, to_timestamp($3 / 1000.0))
ON CONFLICT DO NOTHING
`, [id, authorId, setData[key]])
} else if (key.startsWith('subscribe_author_bookmarks_list.')) {
const authorId = key.split('.')[1]
await pool.query(`
INSERT INTO chat_subscribe_bookmarks (chat_id, author_id, subscribed_at)
VALUES ($1, $2, to_timestamp($3 / 1000.0))
ON CONFLICT DO NOTHING
`, [id, authorId, setData[key]])
} else if (key.startsWith('link_chat_list.')) {
const linkedChatId = key.split('.')[1]
const linkData = setData[key]
await pool.query(`
INSERT INTO chat_link (source_chat_id, linked_chat_id, sync, administrator_only, repeat, chat_type, mediagroup_count)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (source_chat_id, linked_chat_id) DO UPDATE SET
sync = $3, administrator_only = $4, repeat = $5, chat_type = $6, mediagroup_count = $7, updated_at = NOW()
`, [id, linkedChatId, linkData.sync || 0, linkData.administrator_only || 0, linkData.repeat || 0, linkData.type, linkData.mediagroup_count || 1])
}
}
// Update main table if there are columns to update
if (columns.length > 0 || upsert) {
if (columns.length > 0) {
await pool.query(`
INSERT INTO chat_setting (id) VALUES ($1)
ON CONFLICT (id) DO UPDATE SET ${columns.join(', ')}, updated_at = NOW()
`, values)
} else if (upsert) {
await pool.query(`
INSERT INTO chat_setting (id) VALUES ($1)
ON CONFLICT (id) DO NOTHING
`, [id])
}
}
}
// Handle $unset operations
if (Object.keys(unsetData).length > 0) {
for (const key in unsetData) {
if (key.startsWith('subscribe_author_list.')) {
const authorId = key.split('.')[1]
await pool.query(
'DELETE FROM chat_subscribe_author WHERE chat_id = $1 AND author_id = $2',
[id, authorId]
)
} else if (key.startsWith('subscribe_author_bookmarks_list.')) {
const authorId = key.split('.')[1]
await pool.query(
'DELETE FROM chat_subscribe_bookmarks WHERE chat_id = $1 AND author_id = $2',
[id, authorId]
)
} else if (key.startsWith('link_chat_list.')) {
const linkedChatId = key.split('.')[1]
await pool.query(
'DELETE FROM chat_link WHERE source_chat_id = $1 AND linked_chat_id = $2',
[id, linkedChatId]
)
} else if (key === 'default') {
// Reset all default fields to null
await pool.query(`
UPDATE chat_setting SET
default_tags = NULL, default_description = NULL, default_open = NULL,
default_share = NULL, default_remove_keyboard = NULL, default_remove_caption = NULL,
default_single_caption = NULL, default_album = NULL, default_album_one = NULL,
default_album_equal = NULL, default_reverse = NULL, default_overwrite = NULL,
default_asfile = NULL, default_append_file = NULL, default_append_file_immediate = NULL,
default_caption_extraction = NULL, default_caption_above = NULL, default_show_id = NULL,
default_auto_spoiler = NULL, default_telegraph_title = NULL,
default_telegraph_author_name = NULL, default_telegraph_author_url = NULL,
updated_at = NOW()
WHERE id = $1
`, [id])
} else if (key === 'format') {
// Reset all format fields to null
await pool.query(`
UPDATE chat_setting SET
format_message = NULL, format_mediagroup_message = NULL,
format_inline = NULL, format_version = 'v2',
updated_at = NOW()
WHERE id = $1
`, [id])
}
}
}
// COMMIT TRANSACTION
await pool.query('COMMIT')
return { acknowledged: true, matchedCount: 1, modifiedCount: 1 }
} catch (error) {
// ROLLBACK ON ERROR
await pool.query('ROLLBACK')
console.error('chat_setting updateOne error:', error)
throw error
}
},
insertOne: async (doc) => {
return collection.chat_setting.updateOne({ id: doc.id }, { $set: doc }, { upsert: true })
},
updateMany: async (query, update) => {
// Convert MongoDB query to SQL WHERE conditions
const conditions = []
const values = []
let paramIndex = 1
// Handle format field matching
if (query['format.message']) {
conditions.push(`format_message = $${paramIndex}`)
values.push(query['format.message'])
paramIndex++
}
if (query['format.inline']) {
conditions.push(`format_inline = $${paramIndex}`)
values.push(query['format.inline'])
paramIndex++
}
const whereClause = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : ''
// Build SET clause from $set
const setClauses = []
if (update.$set) {
for (const key in update.$set) {
if (key.startsWith('format.')) {
const field = 'format_' + key.split('.')[1]
setClauses.push(`${field} = $${paramIndex}`)
values.push(update.$set[key])
paramIndex++
}
}
}
// Build UNSET clause
if (update.$unset) {
for (const key in update.$unset) {
if (key.startsWith('format.')) {
const field = 'format_' + key.split('.')[1]
setClauses.push(`${field} = NULL`)
}
}
}
if (setClauses.length > 0) {
const sql = `UPDATE chat_setting SET ${setClauses.join(', ')}, updated_at = NOW() ${whereClause}`
const result = await pool.query(sql, values)
return { acknowledged: true, matchedCount: result.rowCount, modifiedCount: result.rowCount }
}
return { acknowledged: true, matchedCount: 0, modifiedCount: 0 }
},
createIndex: async () => {
return true
}
}
}
/**
* Rebuild MongoDB-style setting object from PostgreSQL data
*/
function rebuildSettingObject(setting, subscribeAuthors, subscribeBookmarks, links) {
// Rebuild format object
const format = {}
if (setting.format_message) format.message = setting.format_message
if (setting.format_mediagroup_message) format.mediagroup_message = setting.format_mediagroup_message
if (setting.format_inline) format.inline = setting.format_inline
format.version = setting.format_version || 'v2'
// Rebuild default object
const defaultSettings = {}
const defaultFields = [
'tags', 'description', 'open', 'share', 'remove_keyboard', 'remove_caption',
'single_caption', 'album', 'album_one', 'album_equal', 'reverse', 'overwrite',
'asfile', 'append_file', 'append_file_immediate', 'caption_extraction',
'caption_above', 'show_id', 'auto_spoiler', 'telegraph_title',
'telegraph_author_name', 'telegraph_author_url'
]
for (const field of defaultFields) {
const dbField = `default_${field}`
if (setting[dbField] !== null && setting[dbField] !== undefined) {
defaultSettings[field] = setting[dbField]
}
}
// Rebuild subscribe_author_list
const subscribe_author_list = {}
for (const s of subscribeAuthors) {
subscribe_author_list[s.author_id] = new Date(s.subscribed_at).getTime()
}
// Rebuild subscribe_author_bookmarks_list
const subscribe_author_bookmarks_list = {}
for (const s of subscribeBookmarks) {
subscribe_author_bookmarks_list[s.author_id] = new Date(s.subscribed_at).getTime()
}
// Rebuild link_chat_list
const link_chat_list = {}
for (const link of links) {
link_chat_list[link.linked_chat_id] = {
sync: link.sync,
administrator_only: link.administrator_only,
repeat: link.repeat,
type: link.chat_type,
mediagroup_count: link.mediagroup_count
}
}
return {
id: setting.id,
format: Object.keys(format).length > 0 ? format : undefined,
default: Object.keys(defaultSettings).length > 0 ? defaultSettings : undefined,
subscribe_author_list,
subscribe_author_bookmarks_list,
link_chat_list
}
}
// ============================================
// Other Collection Wrappers
// ============================================
function createNovelCollection() {
return {
findOne: async (query) => {
if (!query || query.id === undefined) return null
const result = await pool.query('SELECT * FROM novel WHERE id = $1', [query.id])
return result.rows[0] || null
},
insertOne: async (doc) => {
await pool.query(`
INSERT INTO novel (id, title, description, series_type, user_name, user_id, restrict, x_restrict, tags, create_date, cover_url, content)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
ON CONFLICT (id) DO NOTHING
`, [doc.id, doc.title, doc.description, doc.seriesType, doc.userName, doc.userId, doc.restrict, doc.xRestrict, doc.tags, doc.createDate, doc.coverUrl, doc.content])
return { acknowledged: true, insertedId: doc.id }
},
createIndex: async () => { return true }
}
}
function createRankingCollection() {
return {
findOne: async (query) => {
if (!query || query.id === undefined) return null
const result = await pool.query('SELECT * FROM ranking WHERE id = $1', [query.id])
if (!result.rows[0]) return null
return {
id: result.rows[0].id,
mode: result.rows[0].mode,
date: result.rows[0].date,
contents: result.rows[0].contents
}
},
insertOne: async (doc) => {
await pool.query(`
INSERT INTO ranking (id, mode, date, contents)
VALUES ($1, $2, $3, $4)
ON CONFLICT (id) DO NOTHING
`, [doc.id, doc.mode, doc.date, JSON.stringify(doc.contents)])
return { acknowledged: true, insertedId: doc.id }
},
createIndex: async () => { return true }
}
}
function createAuthorCollection() {
return {
findOne: async (query) => {
if (!query) return null
const id = query.id || query.author_id
if (!id) return null
const result = await pool.query('SELECT * FROM author WHERE author_id = $1', [id])
return result.rows[0] || null
},
updateOne: async (query, update, _options = {}) => {
const id = query.id || query.author_id
const data = update.$set || {}
await pool.query(`
INSERT INTO author (author_id, author_name, author_avatar_url, comment, comment_html, status)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (author_id) DO UPDATE SET
author_name = COALESCE($2, author.author_name),
author_avatar_url = COALESCE($3, author.author_avatar_url),
comment = COALESCE($4, author.comment),
comment_html = COALESCE($5, author.comment_html),
status = COALESCE($6, author.status),
updated_at = NOW()
`, [id, data.author_name, data.author_avatar_url, data.comment, data.comment_html, data.status])
return { acknowledged: true, matchedCount: 1, modifiedCount: 1 }
},
createIndex: async () => { return true }
}
}
function createTelegraphCollection() {
return {
findOne: async (query) => {
if (!query || query.telegraph_url === undefined) return null
const result = await pool.query('SELECT * FROM telegraph WHERE telegraph_url = $1', [query.telegraph_url])
if (!result.rows[0]) return null
return {
telegraph_url: result.rows[0].telegraph_url,
ids: result.rows[0].illust_ids,
user_id: result.rows[0].user_id
}
},
insertOne: async (doc) => {
await pool.query(`
INSERT INTO telegraph (telegraph_url, illust_ids, user_id)
VALUES ($1, $2, $3)
ON CONFLICT (telegraph_url) DO NOTHING
`, [doc.telegraph_url, doc.ids, doc.user_id])
return { acknowledged: true, insertedId: doc.telegraph_url }
},
createIndex: async () => { return true }
}
}
// ============================================
// Cursor Classes for Query Chaining