@0xobelisk/graphql-server 1.2.0-pre.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/Dockerfile +31 -0
  2. package/EXPRESS_MIGRATION.md +176 -0
  3. package/LICENSE +92 -0
  4. package/README.md +908 -0
  5. package/dist/config/subscription-config.d.ts +47 -0
  6. package/dist/config/subscription-config.d.ts.map +1 -0
  7. package/dist/config/subscription-config.js +133 -0
  8. package/dist/config/subscription-config.js.map +1 -0
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +217 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/plugins/all-fields-filter-plugin.d.ts +4 -0
  14. package/dist/plugins/all-fields-filter-plugin.d.ts.map +1 -0
  15. package/dist/plugins/all-fields-filter-plugin.js +132 -0
  16. package/dist/plugins/all-fields-filter-plugin.js.map +1 -0
  17. package/dist/plugins/database-introspector.d.ts +23 -0
  18. package/dist/plugins/database-introspector.d.ts.map +1 -0
  19. package/dist/plugins/database-introspector.js +96 -0
  20. package/dist/plugins/database-introspector.js.map +1 -0
  21. package/dist/plugins/enhanced-playground.d.ts +9 -0
  22. package/dist/plugins/enhanced-playground.d.ts.map +1 -0
  23. package/dist/plugins/enhanced-playground.js +97 -0
  24. package/dist/plugins/enhanced-playground.js.map +1 -0
  25. package/dist/plugins/enhanced-server-manager.d.ts +28 -0
  26. package/dist/plugins/enhanced-server-manager.d.ts.map +1 -0
  27. package/dist/plugins/enhanced-server-manager.js +232 -0
  28. package/dist/plugins/enhanced-server-manager.js.map +1 -0
  29. package/dist/plugins/index.d.ts +9 -0
  30. package/dist/plugins/index.d.ts.map +1 -0
  31. package/dist/plugins/index.js +26 -0
  32. package/dist/plugins/index.js.map +1 -0
  33. package/dist/plugins/postgraphile-config.d.ts +94 -0
  34. package/dist/plugins/postgraphile-config.d.ts.map +1 -0
  35. package/dist/plugins/postgraphile-config.js +183 -0
  36. package/dist/plugins/postgraphile-config.js.map +1 -0
  37. package/dist/plugins/query-filter.d.ts +4 -0
  38. package/dist/plugins/query-filter.d.ts.map +1 -0
  39. package/dist/plugins/query-filter.js +42 -0
  40. package/dist/plugins/query-filter.js.map +1 -0
  41. package/dist/plugins/simple-naming.d.ts +4 -0
  42. package/dist/plugins/simple-naming.d.ts.map +1 -0
  43. package/dist/plugins/simple-naming.js +79 -0
  44. package/dist/plugins/simple-naming.js.map +1 -0
  45. package/dist/plugins/welcome-page.d.ts +11 -0
  46. package/dist/plugins/welcome-page.d.ts.map +1 -0
  47. package/dist/plugins/welcome-page.js +203 -0
  48. package/dist/plugins/welcome-page.js.map +1 -0
  49. package/dist/universal-subscriptions.d.ts +32 -0
  50. package/dist/universal-subscriptions.d.ts.map +1 -0
  51. package/dist/universal-subscriptions.js +318 -0
  52. package/dist/universal-subscriptions.js.map +1 -0
  53. package/dist/utils/logger/index.d.ts +80 -0
  54. package/dist/utils/logger/index.d.ts.map +1 -0
  55. package/dist/utils/logger/index.js +232 -0
  56. package/dist/utils/logger/index.js.map +1 -0
  57. package/docker-compose.yml +87 -0
  58. package/package.json +71 -0
  59. package/server.log +62 -0
  60. package/src/config/subscription-config.ts +186 -0
  61. package/src/index.ts +239 -0
  62. package/src/plugins/README.md +123 -0
  63. package/src/plugins/all-fields-filter-plugin.ts +158 -0
  64. package/src/plugins/database-introspector.ts +126 -0
  65. package/src/plugins/enhanced-playground.ts +105 -0
  66. package/src/plugins/enhanced-server-manager.ts +282 -0
  67. package/src/plugins/index.ts +9 -0
  68. package/src/plugins/postgraphile-config.ts +226 -0
  69. package/src/plugins/query-filter.ts +50 -0
  70. package/src/plugins/simple-naming.ts +105 -0
  71. package/src/plugins/welcome-page.ts +218 -0
  72. package/src/universal-subscriptions.ts +397 -0
  73. package/src/utils/logger/README.md +193 -0
  74. package/src/utils/logger/index.ts +315 -0
  75. package/sui-indexer-schema.graphql +1004 -0
  76. package/test-express.js +124 -0
  77. package/test_listen_subscription.js +121 -0
  78. package/test_notification.js +63 -0
  79. package/tsconfig.json +28 -0
@@ -0,0 +1,218 @@
1
+ import type { DynamicTable } from './database-introspector';
2
+
3
+ export interface WelcomePageConfig {
4
+ port: string | number;
5
+ graphqlEndpoint: string;
6
+ nodeEnv: string;
7
+ schema: string;
8
+ enableCors: string;
9
+ enableSubscriptions: string;
10
+ }
11
+
12
+ // Create custom welcome page
13
+ export function createWelcomePage(tables: DynamicTable[], config: WelcomePageConfig): string {
14
+ const { port, graphqlEndpoint, nodeEnv, schema, enableCors, enableSubscriptions } = config;
15
+
16
+ const tableList = tables
17
+ .map((table) => {
18
+ const keyFields = table.fields.filter((f) => f.is_key).map((f) => f.field_name);
19
+ const valueFields = table.fields.filter((f) => !f.is_key).map((f) => f.field_name);
20
+ return `
21
+ <div class="table-info">
22
+ <h3>📊 ${table.table_name}</h3>
23
+ <div class="fields">
24
+ <div><strong>Key Fields:</strong> ${keyFields.join(', ') || 'None'}</div>
25
+ <div><strong>Value Fields:</strong> ${valueFields.join(', ')}</div>
26
+ </div>
27
+ </div>
28
+ `;
29
+ })
30
+ .join('');
31
+
32
+ return `
33
+ <!DOCTYPE html>
34
+ <html>
35
+ <head>
36
+ <title>🚀 Sui Indexer GraphQL API</title>
37
+ <meta charset="utf-8">
38
+ <meta name="viewport" content="width=device-width, initial-scale=1">
39
+ <style>
40
+ body {
41
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
42
+ margin: 0;
43
+ padding: 20px;
44
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
45
+ color: #333;
46
+ min-height: 100vh;
47
+ }
48
+ .container {
49
+ max-width: 1200px;
50
+ margin: 0 auto;
51
+ background: white;
52
+ padding: 40px;
53
+ border-radius: 16px;
54
+ box-shadow: 0 20px 40px rgba(0,0,0,0.1);
55
+ }
56
+ h1 {
57
+ color: #2c3e50;
58
+ text-align: center;
59
+ margin-bottom: 10px;
60
+ font-size: 2.5em;
61
+ }
62
+ .subtitle {
63
+ text-align: center;
64
+ color: #7f8c8d;
65
+ margin-bottom: 40px;
66
+ font-size: 1.2em;
67
+ }
68
+ .link {
69
+ display: inline-block;
70
+ margin: 10px;
71
+ padding: 15px 25px;
72
+ background: linear-gradient(135deg, #74b9ff, #0984e3);
73
+ color: white;
74
+ text-decoration: none;
75
+ border-radius: 8px;
76
+ text-align: center;
77
+ font-weight: 500;
78
+ transition: transform 0.2s ease;
79
+ }
80
+ .link:hover {
81
+ transform: translateY(-2px);
82
+ box-shadow: 0 8px 15px rgba(116, 185, 255, 0.4);
83
+ }
84
+ .status {
85
+ color: #00b894;
86
+ font-weight: bold;
87
+ text-align: center;
88
+ font-size: 1.1em;
89
+ margin: 20px 0;
90
+ }
91
+ .warning {
92
+ background: #ffeaa7;
93
+ border-left: 4px solid #fdcb6e;
94
+ padding: 15px;
95
+ margin: 20px 0;
96
+ border-radius: 4px;
97
+ }
98
+ .warning h4 {
99
+ margin-top: 0;
100
+ color: #e17055;
101
+ }
102
+ .table-info {
103
+ background: #f8f9fa;
104
+ padding: 20px;
105
+ margin: 15px 0;
106
+ border-radius: 8px;
107
+ border-left: 4px solid #74b9ff;
108
+ }
109
+ .table-info h3 {
110
+ margin: 0 0 10px 0;
111
+ color: #2c3e50;
112
+ }
113
+ .fields div {
114
+ margin: 5px 0;
115
+ color: #555;
116
+ }
117
+ .info-grid {
118
+ display: grid;
119
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
120
+ gap: 20px;
121
+ margin: 30px 0;
122
+ }
123
+ .info-card {
124
+ background: #f8f9fa;
125
+ padding: 20px;
126
+ border-radius: 8px;
127
+ border: 1px solid #e9ecef;
128
+ }
129
+ .info-card h3 {
130
+ color: #495057;
131
+ margin-top: 0;
132
+ }
133
+ .center {
134
+ text-align: center;
135
+ }
136
+ .highlight {
137
+ background: linear-gradient(135deg, #fdcb6e, #e17055);
138
+ color: white;
139
+ padding: 2px 8px;
140
+ border-radius: 4px;
141
+ font-weight: 500;
142
+ }
143
+ </style>
144
+ </head>
145
+ <body>
146
+ <div class="container">
147
+ <h1>🚀 Sui Indexer GraphQL API</h1>
148
+ <p class="subtitle">Dynamically scan database, automatically generate GraphQL API</p>
149
+ <p class="status">● Server Status: Running Normally | Scanned <span class="highlight">${
150
+ tables.length
151
+ }</span> tables</p>
152
+
153
+ ${
154
+ enableSubscriptions === 'false'
155
+ ? `
156
+ <div class="warning">
157
+ <h4>⚠️ WebSocket subscription feature is temporarily disabled</h4>
158
+ <p>Currently fixing subscription configuration issues. Basic GraphQL query and mutation functions work perfectly.</p>
159
+ </div>
160
+ `
161
+ : `
162
+ <div class="status">
163
+ <p>📡 Real-time subscription feature: ${enableSubscriptions === 'true' ? 'Enabled' : 'Disabled'}</p>
164
+ </div>
165
+ `
166
+ }
167
+
168
+ <div class="center">
169
+ <a href="${graphqlEndpoint}" class="link">📊 GraphQL API</a>
170
+ <a href="/playground" class="link">🎮 Enhanced GraphQL Playground</a>
171
+ </div>
172
+
173
+ <div class="info-grid">
174
+ <div class="info-card">
175
+ <h3>🎯 Core Features</h3>
176
+ <ul>
177
+ <li>✨ Auto-scan sui-rust-indexer database</li>
178
+ <li>🔄 Dynamically generate GraphQL schema</li>
179
+ <li>📡 Support real-time subscription features ${enableSubscriptions === 'true' ? '✅' : '⚠️'}</li>
180
+ <li>🚀 Complete CRUD operations</li>
181
+ <li>🛡️ PostGraphile powerful features</li>
182
+ </ul>
183
+ </div>
184
+
185
+ <div class="info-card">
186
+ <h3>📊 Server Information</h3>
187
+ <ul>
188
+ <li>Environment: ${nodeEnv}</li>
189
+ <li>Port: ${port}</li>
190
+ <li>Database Schema: ${schema}</li>
191
+ <li>CORS: ${enableCors === 'true' ? 'Enabled' : 'Disabled'}</li>
192
+ <li>Subscriptions: ${enableSubscriptions === 'true' ? 'Enabled' : 'Disabled'}</li>
193
+ </ul>
194
+ </div>
195
+ </div>
196
+
197
+ <h2>📋 Detected Data Tables</h2>
198
+ ${tableList}
199
+
200
+ <div style="margin-top: 40px; padding: 20px; background: #e3f2fd; border-radius: 8px;">
201
+ <h3>💡 Usage Tips</h3>
202
+ <p>1. Visit <strong>Enhanced GraphQL Playground</strong> for better query experience</p>
203
+ <p> • 📊 Visual Schema Explorer - Click-to-build queries</p>
204
+ <p> • 🎨 Modern UI interface and enhanced code highlighting</p>
205
+ <p> • 📝 Code export feature - Generate client code in multiple languages</p>
206
+ <p> • ⌨️ Keyboard shortcuts support - Ctrl/Cmd+Enter to execute queries</p>
207
+ <p>2. All tables support standard GraphQL query, mutation${
208
+ enableSubscriptions === 'true' ? ' and subscription' : ''
209
+ } operations</p>
210
+ <p>3. Dynamic tables (store_*) automatically generate fields based on table_fields metadata</p>
211
+ <p>4. System tables provide core data access for sui-indexer</p>
212
+ ${enableSubscriptions === 'true' ? '<p>5. Use WebSocket for real-time data subscriptions</p>' : ''}
213
+ </div>
214
+ </div>
215
+ </body>
216
+ </html>
217
+ `;
218
+ }
@@ -0,0 +1,397 @@
1
+ import { makeExtendSchemaPlugin, gql } from 'postgraphile';
2
+ import { subscriptionLogger } from './utils/logger';
3
+
4
+ // Database table information interface
5
+ interface TableInfo {
6
+ tableName: string;
7
+ fullTableName: string;
8
+ columns: ColumnInfo[];
9
+ primaryKeys: string[];
10
+ statistics?: {
11
+ rowCount: number;
12
+ totalSize: string;
13
+ tableSize: string;
14
+ };
15
+ generatedAt?: string;
16
+ }
17
+
18
+ interface ColumnInfo {
19
+ columnName: string;
20
+ dataType: string;
21
+ isNullable: boolean;
22
+ defaultValue?: any;
23
+ maxLength?: number;
24
+ precision?: number;
25
+ scale?: number;
26
+ }
27
+
28
+ // Cached table information
29
+ let cachedTables: Record<string, TableInfo> = {};
30
+ let schemaGenerated = false;
31
+
32
+ /**
33
+ * Dynamically retrieve schema information for all store tables
34
+ */
35
+ async function discoverStoreTables(pgClient: any): Promise<Record<string, TableInfo>> {
36
+ if (schemaGenerated && Object.keys(cachedTables).length > 0) {
37
+ return cachedTables;
38
+ }
39
+
40
+ try {
41
+ subscriptionLogger.info('Starting discovery of database store table structure...');
42
+
43
+ // 1. Get all store_* tables
44
+ const tablesResult = await pgClient.query(`
45
+ SELECT table_name
46
+ FROM information_schema.tables
47
+ WHERE table_schema = 'public'
48
+ AND table_name LIKE 'store_%'
49
+ ORDER BY table_name
50
+ `);
51
+
52
+ const tables: Record<string, TableInfo> = {};
53
+
54
+ // 2. Get detailed information for each table
55
+ for (const tableRow of tablesResult.rows) {
56
+ const fullTableName = tableRow.table_name;
57
+ const tableName = fullTableName.replace(/^store_/, '');
58
+
59
+ const tableInfo = await getTableInfo(pgClient, fullTableName);
60
+ tables[tableName] = tableInfo;
61
+ }
62
+
63
+ cachedTables = tables;
64
+ schemaGenerated = true;
65
+
66
+ subscriptionLogger.info(
67
+ `Discovered ${Object.keys(tables).length} store tables: ${Object.keys(tables).join(', ')}`
68
+ );
69
+ return tables;
70
+ } catch (error) {
71
+ subscriptionLogger.error('Failed to discover store tables', error);
72
+ return {};
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Generate pre-built table information - called at server startup
78
+ */
79
+ export async function generateStoreTablesInfo(pgPool: any): Promise<Record<string, TableInfo>> {
80
+ const pgClient = await pgPool.connect();
81
+ try {
82
+ const tables = await discoverStoreTables(pgClient);
83
+ subscriptionLogger.info(
84
+ `Pre-generated schema information for ${Object.keys(tables).length} tables`
85
+ );
86
+ return tables;
87
+ } finally {
88
+ pgClient.release();
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Simplified tools plugin - only provides basic query functionality, let PostGraphile's built-in listen subscriptions work normally
94
+ */
95
+ export function createUniversalSubscriptionsPlugin(preGeneratedTables?: Record<string, TableInfo>) {
96
+ return makeExtendSchemaPlugin((build) => {
97
+ subscriptionLogger.info(
98
+ 'Enabling simplified tools plugin - only keeping basic query functionality'
99
+ );
100
+
101
+ // Use pre-generated table information if available
102
+ if (preGeneratedTables && Object.keys(preGeneratedTables).length > 0) {
103
+ cachedTables = preGeneratedTables;
104
+ schemaGenerated = true;
105
+ }
106
+
107
+ const tableNames = Object.keys(cachedTables);
108
+ subscriptionLogger.info(`Discovered store tables: ${tableNames.join(', ')}`);
109
+
110
+ return {
111
+ typeDefs: gql`
112
+ extend type Query {
113
+ """
114
+ Get Schema information for all store tables
115
+ """
116
+ storeSchema: JSON
117
+
118
+ """
119
+ Query data from specified store table
120
+ """
121
+ storeData(table: String!): JSON
122
+
123
+ """
124
+ Get list of all available store table names
125
+ """
126
+ availableStoreTables: [String!]!
127
+ }
128
+
129
+ # Removed custom subscription types, now only use PostGraphile's built-in listen subscriptions
130
+ `,
131
+
132
+ resolvers: {
133
+ Query: {
134
+ storeSchema: async (root: any, args: any, context: any, info: any) => {
135
+ const { pgClient } = context;
136
+ try {
137
+ const tables = await discoverStoreTables(pgClient);
138
+ return {
139
+ tables,
140
+ generatedAt: new Date().toISOString()
141
+ };
142
+ } catch (error) {
143
+ return {
144
+ error: (error as Error).message,
145
+ tables: {}
146
+ };
147
+ }
148
+ },
149
+
150
+ storeData: async (root: any, args: any, context: any, info: any) => {
151
+ return await executeTableQuery(context, args.table);
152
+ },
153
+
154
+ availableStoreTables: async (root: any, args: any, context: any, info: any) => {
155
+ const { pgClient } = context;
156
+ try {
157
+ const tables = await discoverStoreTables(pgClient);
158
+ return Object.keys(tables);
159
+ } catch (error) {
160
+ subscriptionLogger.error('Failed to get available table list', error);
161
+ return [];
162
+ }
163
+ }
164
+ }
165
+ }
166
+ };
167
+ });
168
+ }
169
+
170
+ // Default plugin export (for backward compatibility)
171
+ export const UniversalSubscriptionsPlugin = createUniversalSubscriptionsPlugin();
172
+
173
+ // =========================
174
+ // Database query functions
175
+ // =========================
176
+
177
+ /**
178
+ * Get detailed table information (columns, primary keys, data statistics, etc.)
179
+ */
180
+ async function getTableInfo(pgClient: any, fullTableName: string): Promise<TableInfo> {
181
+ const tableName = fullTableName.replace(/^store_/, '');
182
+
183
+ // 1. Get column information
184
+ const columnsResult = await pgClient.query(
185
+ `
186
+ SELECT
187
+ column_name,
188
+ data_type,
189
+ is_nullable,
190
+ column_default,
191
+ character_maximum_length,
192
+ numeric_precision,
193
+ numeric_scale
194
+ FROM information_schema.columns
195
+ WHERE table_name = $1
196
+ ORDER BY ordinal_position
197
+ `,
198
+ [fullTableName]
199
+ );
200
+
201
+ // 2. Get primary key information
202
+ const primaryKeysResult = await pgClient.query(
203
+ `
204
+ SELECT column_name
205
+ FROM information_schema.table_constraints tc
206
+ JOIN information_schema.key_column_usage kcu
207
+ ON tc.constraint_name = kcu.constraint_name
208
+ WHERE tc.table_name = $1
209
+ AND tc.constraint_type = 'PRIMARY KEY'
210
+ ORDER BY kcu.ordinal_position
211
+ `,
212
+ [fullTableName]
213
+ );
214
+
215
+ // 3. Try to get primary key information from table_fields table (if exists)
216
+ let tableFieldsKeys: string[] = [];
217
+ try {
218
+ const tableFieldsResult = await pgClient.query(
219
+ `
220
+ SELECT field_name
221
+ FROM table_fields
222
+ WHERE table_name = $1 AND is_key = true
223
+ ORDER BY field_name
224
+ `,
225
+ [tableName]
226
+ );
227
+ tableFieldsKeys = tableFieldsResult.rows.map((row: any) => row.field_name);
228
+ } catch (e) {
229
+ // table_fields table may not exist, ignore error
230
+ }
231
+
232
+ // 4. Get data statistics
233
+ const statsResult = await pgClient.query(`
234
+ SELECT count(*) as row_count
235
+ FROM ${fullTableName}
236
+ `);
237
+
238
+ // 5. Get table size information
239
+ const sizeResult = await pgClient.query(
240
+ `
241
+ SELECT
242
+ pg_size_pretty(pg_total_relation_size($1)) as total_size,
243
+ pg_size_pretty(pg_relation_size($1)) as table_size
244
+ `,
245
+ [fullTableName]
246
+ );
247
+
248
+ const columns: ColumnInfo[] = columnsResult.rows.map((row: any) => ({
249
+ columnName: row.column_name,
250
+ dataType: row.data_type,
251
+ isNullable: row.is_nullable === 'YES',
252
+ defaultValue: row.column_default,
253
+ maxLength: row.character_maximum_length,
254
+ precision: row.numeric_precision,
255
+ scale: row.numeric_scale
256
+ }));
257
+
258
+ const primaryKeys = primaryKeysResult.rows.map((row: any) => row.column_name);
259
+
260
+ return {
261
+ tableName,
262
+ fullTableName,
263
+ columns,
264
+ primaryKeys: primaryKeys.length > 0 ? primaryKeys : tableFieldsKeys,
265
+ statistics: {
266
+ rowCount: parseInt(statsResult.rows[0]?.row_count || '0'),
267
+ totalSize: sizeResult.rows[0]?.total_size || 'unknown',
268
+ tableSize: sizeResult.rows[0]?.table_size || 'unknown'
269
+ },
270
+ generatedAt: new Date().toISOString()
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Dynamically execute table queries
276
+ */
277
+ async function executeTableQuery(context: any, tableName: string): Promise<any> {
278
+ const { pgClient } = context;
279
+ const fullTableName = `store_${tableName}`;
280
+
281
+ try {
282
+ subscriptionLogger.debug(`Executing table query: ${fullTableName}`);
283
+
284
+ // 1. Get table information
285
+ const tableInfo = cachedTables[tableName] || (await getTableInfo(pgClient, fullTableName));
286
+
287
+ if (tableInfo.columns.length === 0) {
288
+ return {
289
+ nodes: [],
290
+ totalCount: 0,
291
+ tableName,
292
+ generatedAt: new Date().toISOString()
293
+ };
294
+ }
295
+
296
+ // 2. Build dynamic nodeId expression
297
+ const nodeIdExpression = buildNodeIdExpression(tableInfo);
298
+
299
+ // 3. Build query fields
300
+ const columnFields = tableInfo.columns
301
+ .map((col) => `'${col.columnName}', ${col.columnName}`)
302
+ .join(', ');
303
+
304
+ // 4. Build WHERE condition
305
+ const whereCondition = buildWhereCondition(tableInfo);
306
+
307
+ // 5. Execute query
308
+ const sql = `
309
+ SELECT
310
+ COALESCE(
311
+ json_agg(
312
+ json_build_object(
313
+ 'nodeId', ${nodeIdExpression},
314
+ ${columnFields}
315
+ )
316
+ ),
317
+ '[]'::json
318
+ ) as nodes,
319
+ count(*) as total_count
320
+ FROM ${fullTableName}
321
+ WHERE ${whereCondition}
322
+ `;
323
+
324
+ subscriptionLogger.debug(`Executing SQL: ${sql}`);
325
+ const result = await pgClient.query(sql);
326
+
327
+ const row = result.rows[0];
328
+ const data = {
329
+ nodes: row?.nodes || [],
330
+ totalCount: parseInt(row?.total_count || '0'),
331
+ tableName,
332
+ generatedAt: new Date().toISOString()
333
+ };
334
+
335
+ subscriptionLogger.debug(`Query result: ${fullTableName} found ${data.totalCount} records`);
336
+ return data;
337
+ } catch (error) {
338
+ subscriptionLogger.error(`Failed to query ${fullTableName}`, error);
339
+ return {
340
+ nodes: [],
341
+ totalCount: 0,
342
+ tableName,
343
+ generatedAt: new Date().toISOString(),
344
+ error: (error as Error).message
345
+ };
346
+ }
347
+ }
348
+
349
+ /**
350
+ * Dynamically build NodeId expression
351
+ */
352
+ function buildNodeIdExpression(tableInfo: TableInfo): string {
353
+ const { tableName, primaryKeys, columns } = tableInfo;
354
+
355
+ if (primaryKeys.length > 0) {
356
+ // Use primary keys to build nodeId
357
+ const keyExpression = primaryKeys
358
+ .map((key) => `COALESCE(${key}::text, 'null')`)
359
+ .join(" || ':' || ");
360
+ return `encode(('${tableName}:' || ${keyExpression})::bytea, 'base64')`;
361
+ }
362
+
363
+ // If no primary key, use first column
364
+ const firstColumn = columns[0]?.columnName || 'unknown';
365
+ return `encode(('${tableName}:' || COALESCE(${firstColumn}::text, 'unknown'))::bytea, 'base64')`;
366
+ }
367
+
368
+ /**
369
+ * Dynamically build WHERE condition - completely generic, no hardcoded field names
370
+ */
371
+ function buildWhereCondition(tableInfo: TableInfo): string {
372
+ const { primaryKeys, columns } = tableInfo;
373
+
374
+ // 1. Prioritize primary key fields as filter conditions (most reliable)
375
+ if (primaryKeys.length > 0) {
376
+ const conditions = primaryKeys.map((key) => `${key} IS NOT NULL`);
377
+ return conditions.join(' AND ');
378
+ }
379
+
380
+ // 2. If no primary key, find first non-null field (reduce empty data)
381
+ const nonNullableColumns = columns.filter((col) => !col.isNullable);
382
+ if (nonNullableColumns.length > 0) {
383
+ return `${nonNullableColumns[0].columnName} IS NOT NULL`;
384
+ }
385
+
386
+ // 3. If all fields can be null, use first field for basic filtering
387
+ if (columns.length > 0) {
388
+ return `${columns[0].columnName} IS NOT NULL`;
389
+ }
390
+
391
+ // 4. Final fallback - return all rows (no filtering)
392
+ return 'true';
393
+ }
394
+
395
+ // Removed getLatestInsertedData function, now only use listen subscriptions
396
+
397
+ // Removed getLatestInsertedDataSince function, now only use simple listen subscriptions