forked from libredb/libredb-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoracle.ts
More file actions
1123 lines (982 loc) · 40.2 KB
/
Copy pathoracle.ts
File metadata and controls
1123 lines (982 loc) · 40.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
/**
* Oracle Database Provider
* Full Oracle support with connection pooling (Thin mode - no Instant Client needed)
*/
import oracledb from "oracledb";
import { SQLBaseProvider } from "./sql-base";
import {
type DatabaseConnection,
type TableSchema,
type QueryResult,
type HealthInfo,
type MaintenanceType,
type MaintenanceResult,
type ProviderOptions,
type ProviderCapabilities,
type ProviderLabels,
type SlowQuery,
type ActiveSession,
type DatabaseOverview,
type PerformanceMetrics,
type SlowQueryStats,
type ActiveSessionDetails,
type TableStats,
type IndexStats,
type StorageStats,
type PreparedQuery,
type QueryPrepareOptions,
} from "../../types";
import { DatabaseConfigError, ConnectionError, QueryError, mapDatabaseError } from "../../errors";
import { formatBytes } from "../../utils/pool-manager";
import { analyzeQuery, DEFAULT_QUERY_LIMIT, MAX_UNLIMITED_ROWS } from "../../utils/query-limiter";
import { resolveSqlGrammar } from "@/lib/sql/grammar";
import { readStatementEnd } from "@/lib/sql/statement-end";
// ============================================================================
// SQL Statements
// ============================================================================
// Multi-line SQL is hoisted to module scope so per-line coverage attribution
// stays stable (repo pattern, see the SCHEMA_*_SQL consts in mssql.ts).
const SCHEMA_COLUMNS_SQL = `SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_DEFAULT, COLUMN_ID
FROM ALL_TAB_COLUMNS WHERE OWNER = :1
ORDER BY TABLE_NAME, COLUMN_ID`;
const SCHEMA_PRIMARY_KEYS_SQL = `SELECT ac.TABLE_NAME, acc.COLUMN_NAME
FROM ALL_CONSTRAINTS ac
JOIN ALL_CONS_COLUMNS acc ON ac.CONSTRAINT_NAME = acc.CONSTRAINT_NAME AND ac.OWNER = acc.OWNER
WHERE ac.OWNER = :1 AND ac.CONSTRAINT_TYPE = 'P'`;
const SCHEMA_FOREIGN_KEYS_SQL = `SELECT ac.TABLE_NAME,
acc.COLUMN_NAME,
rc.TABLE_NAME AS REF_TABLE,
rcc.COLUMN_NAME AS REF_COLUMN
FROM ALL_CONSTRAINTS ac
JOIN ALL_CONS_COLUMNS acc ON ac.CONSTRAINT_NAME = acc.CONSTRAINT_NAME AND ac.OWNER = acc.OWNER
JOIN ALL_CONSTRAINTS rc ON ac.R_CONSTRAINT_NAME = rc.CONSTRAINT_NAME AND ac.R_OWNER = rc.OWNER
JOIN ALL_CONS_COLUMNS rcc ON rc.CONSTRAINT_NAME = rcc.CONSTRAINT_NAME AND rc.OWNER = rcc.OWNER
WHERE ac.OWNER = :1 AND ac.CONSTRAINT_TYPE = 'R'`;
const SCHEMA_INDEXES_SQL = `SELECT ai.TABLE_NAME, ai.INDEX_NAME, ai.UNIQUENESS, aic.COLUMN_NAME, aic.COLUMN_POSITION
FROM ALL_INDEXES ai
JOIN ALL_IND_COLUMNS aic ON ai.INDEX_NAME = aic.INDEX_NAME AND ai.OWNER = aic.INDEX_OWNER
WHERE ai.OWNER = :1
ORDER BY ai.TABLE_NAME, ai.INDEX_NAME, aic.COLUMN_POSITION`;
// Shared by getHealth() and getPerformanceMetrics().
const CACHE_HIT_RATIO_SQL = `SELECT ROUND(
(1 - (SUM(DECODE(NAME, 'physical reads', VALUE, 0)) /
NULLIF(SUM(DECODE(NAME, 'db block gets', VALUE, 0)) + SUM(DECODE(NAME, 'consistent gets', VALUE, 0)), 0)
)) * 100, 2) AS HIT_RATIO
FROM V$SYSSTAT
WHERE NAME IN ('db block gets', 'consistent gets', 'physical reads')`;
const HEALTH_SLOW_QUERIES_SQL = `SELECT * FROM (
SELECT SUBSTR(SQL_TEXT, 1, 100) AS QUERY,
EXECUTIONS AS CALLS,
ROUND(ELAPSED_TIME / NULLIF(EXECUTIONS, 0) / 1000, 2) || 'ms' AS AVGTIME
FROM V$SQL
WHERE EXECUTIONS > 0
ORDER BY ELAPSED_TIME DESC
) WHERE ROWNUM <= 5`;
const HEALTH_ACTIVE_SESSIONS_SQL = `SELECT * FROM (
SELECT SID, USERNAME, STATUS, SUBSTR(NVL(SQL_ID, ''), 1, 100) AS QUERY,
SCHEMANAME AS "DATABASE",
NVL(TO_CHAR(LOGON_TIME, 'HH24:MI:SS'), 'N/A') AS DURATION
FROM V$SESSION
WHERE TYPE = 'USER' AND STATUS = 'ACTIVE'
ORDER BY LOGON_TIME DESC
) WHERE ROWNUM <= 10`;
const OVERVIEW_OBJECT_COUNTS_SQL = `SELECT
(SELECT COUNT(*) FROM USER_TABLES) AS TABLE_COUNT,
(SELECT COUNT(*) FROM USER_INDEXES) AS INDEX_COUNT
FROM DUAL`;
// Interpolated before " WHERE ROWNUM <= <limit>" in getSlowQueries().
const SLOW_QUERIES_BODY_SQL = `SELECT * FROM (
SELECT SQL_ID AS QUERY_ID,
SUBSTR(SQL_TEXT, 1, 500) AS QUERY,
EXECUTIONS AS CALLS,
ROUND(ELAPSED_TIME / 1000, 2) AS TOTAL_TIME,
ROUND(ELAPSED_TIME / NULLIF(EXECUTIONS, 0) / 1000, 2) AS AVG_TIME,
ROWS_PROCESSED AS ROW_CNT,
BUFFER_GETS AS BUF_GETS,
DISK_READS
FROM V$SQL
WHERE EXECUTIONS > 0
ORDER BY ELAPSED_TIME DESC
)`;
// Interpolated before " WHERE ROWNUM <= <limit>" in getActiveSessions().
const ACTIVE_SESSIONS_BODY_SQL = `SELECT * FROM (
SELECT s.SID, s.SERIAL#, s.USERNAME, s.SCHEMANAME, s.PROGRAM,
s.MACHINE, s.STATUS, s.SQL_ID,
SUBSTR(sq.SQL_TEXT, 1, 500) AS QUERY,
s.LOGON_TIME,
ROUND((SYSDATE - s.LOGON_TIME) * 86400) AS DURATION_SECS,
s.WAIT_CLASS, s.EVENT
FROM V$SESSION s
LEFT JOIN V$SQL sq ON s.SQL_ID = sq.SQL_ID AND s.SQL_CHILD_NUMBER = sq.CHILD_NUMBER
WHERE s.TYPE = 'USER'
ORDER BY CASE s.STATUS WHEN 'ACTIVE' THEN 0 ELSE 1 END, s.LOGON_TIME DESC
)`;
const TABLE_STATS_SQL = `SELECT t.TABLE_NAME,
NVL(t.NUM_ROWS, 0) AS ROW_COUNT,
NVL(s.BYTES, 0) AS TABLE_SIZE_BYTES,
NVL(idx_size.BYTES, 0) AS INDEX_SIZE_BYTES,
t.LAST_ANALYZED
FROM ALL_TABLES t
LEFT JOIN USER_SEGMENTS s ON s.SEGMENT_NAME = t.TABLE_NAME AND s.SEGMENT_TYPE = 'TABLE'
LEFT JOIN (
SELECT TABLE_NAME, SUM(BYTES) AS BYTES
FROM USER_SEGMENTS
WHERE SEGMENT_TYPE = 'INDEX'
GROUP BY TABLE_NAME
) idx_size ON idx_size.TABLE_NAME = t.TABLE_NAME
WHERE t.OWNER = :1
ORDER BY NVL(s.BYTES, 0) DESC`;
const INDEX_STATS_SQL = `SELECT ai.TABLE_NAME, ai.INDEX_NAME, ai.INDEX_TYPE, ai.UNIQUENESS,
NVL(us.BYTES, 0) AS INDEX_SIZE_BYTES,
ai.LEAF_BLOCKS, ai.DISTINCT_KEYS
FROM ALL_INDEXES ai
LEFT JOIN USER_SEGMENTS us ON us.SEGMENT_NAME = ai.INDEX_NAME AND us.SEGMENT_TYPE = 'INDEX'
WHERE ai.OWNER = :1
ORDER BY NVL(us.BYTES, 0) DESC`;
const INDEX_COLUMNS_SQL = `SELECT INDEX_NAME, COLUMN_NAME, COLUMN_POSITION
FROM ALL_IND_COLUMNS WHERE INDEX_OWNER = :1
ORDER BY INDEX_NAME, COLUMN_POSITION`;
const STORAGE_DBA_FILES_SQL = `SELECT TABLESPACE_NAME AS NAME,
SUM(BYTES) AS SIZE_BYTES
FROM DBA_DATA_FILES
GROUP BY TABLESPACE_NAME
ORDER BY SUM(BYTES) DESC`;
const STORAGE_USER_SEGMENTS_SQL = `SELECT TABLESPACE_NAME AS NAME,
SUM(BYTES) AS SIZE_BYTES
FROM USER_SEGMENTS
GROUP BY TABLESPACE_NAME
ORDER BY SUM(BYTES) DESC`;
// ============================================================================
// Oracle Provider
// ============================================================================
// node-oracledb's Thin/Thick client mode is a process-wide singleton:
// oracledb.initOracleClient() throws if called more than once, or after any
// connection/pool already exists. Track it at module scope so it runs at most
// once across every OracleProvider instance in this process, not once per
// constructor call.
let thickClientInitialized = false;
export class OracleProvider extends SQLBaseProvider {
private pool: oracledb.Pool | null = null;
// Transaction support: dedicated connection held outside pool
private txConn: oracledb.Connection | null = null;
private txActive = false;
// Track running connections for cancellation
private runningConns = new Map<string, oracledb.Connection>();
constructor(config: DatabaseConnection, options: ProviderOptions = {}) {
super(config, options);
// Thin mode (pure JS, no Oracle Instant Client) is the unconditional default.
// Thick mode is an explicit opt-in for servers older than Oracle Database 12.1,
// which Thin mode cannot connect to (node-oracledb NJS-138).
const libDir = process.env.ORACLE_CLIENT_LIB_DIR;
if (libDir && !thickClientInitialized) {
try {
oracledb.initOracleClient({ libDir });
} catch (error) {
// A bad ORACLE_CLIENT_LIB_DIR (e.g. no Instant Client at that path) makes
// node-oracledb throw a raw driver error (DPI-1047). Surface it as a
// non-retryable configuration error that names the offending env var, so it
// is actionable rather than looking like a transient failure.
throw new DatabaseConfigError(
`Failed to load the Oracle Instant Client from ORACLE_CLIENT_LIB_DIR=${libDir}: ${String(error)}. ` +
"Verify the path points at an installed Oracle Instant Client 'lib' directory " +
"(Instant Client 19c is required to reach Oracle 11.2 servers).",
"oracle",
);
}
thickClientInitialized = true;
}
oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT;
oracledb.autoCommit = true;
this.validate();
}
// ============================================================================
// Provider Metadata
// ============================================================================
public override getCapabilities(): ProviderCapabilities {
return {
...super.getCapabilities(),
defaultPort: 1521,
// Disabled until an Oracle dialect wrapper exists (#126): a real plan flow needs
// EXPLAIN PLAN FOR + DBMS_XPLAN, which the single-statement explain path cannot express.
supportsExplain: false,
supportsConnectionString: true,
supportsInlineRowEdit: true,
maintenanceOperations: ["analyze", "optimize", "kill"],
};
}
public override getLabels(): ProviderLabels {
return {
...super.getLabels(),
analyzeAction: "Gather Statistics",
vacuumAction: "Rebuild Indexes",
analyzeGlobalLabel: "Gather Stats",
analyzeGlobalTitle: "Gather Statistics",
analyzeGlobalDesc: "Collects optimizer statistics for all tables to improve query performance.",
vacuumGlobalLabel: "Rebuild Indexes",
vacuumGlobalTitle: "Rebuild All Indexes",
vacuumGlobalDesc: "Rebuilds all indexes to reclaim space and improve performance.",
};
}
// ============================================================================
// Validation
// ============================================================================
public validate(): void {
super.validate();
if (!this.config.connectionString) {
if (!this.config.host) {
throw new DatabaseConfigError("Host is required for Oracle", "oracle");
}
}
}
// ============================================================================
// Connection Management
// ============================================================================
private getConnectString(): string {
if (this.config.connectionString) {
return this.config.connectionString;
}
const host = this.config.host || "localhost";
const port = this.config.port || 1521;
const serviceName = this.config.serviceName || this.config.database || "ORCL";
return `${host}:${port}/${serviceName}`;
}
public async connect(): Promise<void> {
if (this.pool) {
return;
}
try {
// No pool `error` listener here, unlike the PostgreSQL and SQL Server providers
// (#298): oracledb's pool has no pool-level `error` event to listen for. Audited in
// the installed package — `oracledb/lib/pool.js` extends EventEmitter but emits only
// the internal `_afterPoolClose` and `_allCheckedIn`, and nothing under `oracledb/lib`
// emits `error` at all. Connection failures surface through the awaiting call.
this.pool = await oracledb.createPool({
user: this.config.user,
password: this.config.password,
connectString: this.getConnectString(),
poolMin: this.poolConfig.min,
poolMax: this.poolConfig.max,
poolTimeout: Math.floor(this.poolConfig.idleTimeout / 1000),
});
// Test the connection
const conn = await this.pool.getConnection();
await conn.close();
this.setConnected(true);
} catch (error) {
this.setError(error instanceof Error ? error : new Error(String(error)));
// NJS-138 (server predates Oracle 12.1, incompatible with Thin mode) is a permanent
// configuration problem, not a transient connection failure — map it through
// mapDatabaseError() so it surfaces as a non-retryable DatabaseConfigError instead of
// the generic ConnectionError every other connect() failure falls back to below.
const mapped = mapDatabaseError(error, "oracle");
if (mapped instanceof DatabaseConfigError) {
throw mapped;
}
throw new ConnectionError(
`Failed to connect to Oracle: ${error instanceof Error ? error.message : error}`,
"oracle",
this.config.host,
this.config.port,
);
}
}
public async disconnect(): Promise<void> {
if (this.pool) {
try {
await this.pool.close(0);
} catch {
// Force close on error
}
this.pool = null;
this.setConnected(false);
}
}
// ============================================================================
// Query Execution
// ============================================================================
public async query(sql: string, params?: unknown[], queryId?: string): Promise<QueryResult> {
this.ensureConnected();
return this.trackQuery(async () => {
const { result, executionTime } = await this.measureExecution(async () => {
let conn: oracledb.Connection | undefined;
try {
conn = await this.pool!.getConnection();
if (queryId) {
this.runningConns.set(queryId, conn);
}
const bindParams = params || [];
const res = await conn.execute(sql, bindParams, {
outFormat: oracledb.OUT_FORMAT_OBJECT,
autoCommit: true,
});
return res;
} catch (error) {
throw mapDatabaseError(error, "oracle", sql);
} finally {
if (queryId) this.runningConns.delete(queryId);
if (conn) {
try {
await conn.close();
} catch {
/* ignore */
}
}
}
});
const rows = (result.rows || []) as Record<string, unknown>[];
const fields = result.metaData?.map((m: { name: string }) => m.name) ?? [];
return {
rows,
fields,
rowCount: rows.length,
executionTime,
};
});
}
public async cancelQuery(queryId: string): Promise<boolean> {
const conn = this.runningConns.get(queryId);
if (!conn) return false;
try {
await conn.break();
return true;
} catch (error) {
console.error("[Oracle] Failed to cancel query:", error);
return false;
}
}
// ============================================================================
// Query Preparation (Oracle FETCH FIRST instead of LIMIT)
// ============================================================================
public override prepareQuery(query: string, options: QueryPrepareOptions = {}): PreparedQuery {
const { limit = DEFAULT_QUERY_LIMIT, offset = 0, unlimited = false } = options;
const effectiveLimit = unlimited ? MAX_UNLIMITED_ROWS : limit;
const queryInfo = analyzeQuery(query, this.type);
if (queryInfo.type === "SELECT" && !queryInfo.hasLimit) {
// Both branches append at the tail, so both used to have their clause
// swallowed by a trailing line comment while this method still reported
// `wasLimited: true` - the statement reached Oracle unbounded and the UI
// said it was capped (#280). The clause goes between the statement and its
// trailing trivia instead, which also keeps the `;` out of the comment.
// A statement whose end may not be cut has nowhere honest to take the
// clause, so it is returned untouched rather than bounded on a guess. On
// Oracle that is a literal Oracle and MySQL would close in different
// places. `#` in an identifier (`ID#`) used to reach the same refusal and
// no longer does: the end is read under Oracle's own grammar (#292), where
// `#` is an identifier character and opens no comment.
const source = query.trim();
const { end, rewritable } = readStatementEnd(source, resolveSqlGrammar(this.type));
if (!rewritable) {
return { query, wasLimited: false, limit: effectiveLimit, offset };
}
const statement = source.slice(0, end);
const trailing = source.slice(end);
const clause =
offset > 0
? `OFFSET ${offset} ROWS FETCH NEXT ${effectiveLimit} ROWS ONLY`
: `FETCH FIRST ${effectiveLimit} ROWS ONLY`;
return {
query: `${statement} ${clause}${trailing}`,
wasLimited: true,
limit: effectiveLimit,
offset,
};
}
return { query, wasLimited: false, limit: effectiveLimit, offset };
}
// ============================================================================
// Transaction Support
// ============================================================================
public async beginTransaction(): Promise<void> {
this.ensureConnected();
if (this.txActive) throw new QueryError("Transaction already active", "oracle");
this.txConn = await this.pool!.getConnection();
// Oracle auto-starts a transaction; we just hold the connection
this.txActive = true;
}
public async commitTransaction(): Promise<void> {
if (!this.txConn || !this.txActive) throw new QueryError("No active transaction", "oracle");
try {
await this.txConn.commit();
} finally {
await this.txConn.close();
this.txConn = null;
this.txActive = false;
}
}
public async rollbackTransaction(): Promise<void> {
if (!this.txConn || !this.txActive) throw new QueryError("No active transaction", "oracle");
try {
await this.txConn.rollback();
} finally {
await this.txConn.close();
this.txConn = null;
this.txActive = false;
}
}
public isInTransaction(): boolean {
return this.txActive;
}
public async queryInTransaction(sql: string, params?: unknown[]): Promise<QueryResult> {
if (!this.txConn || !this.txActive) throw new QueryError("No active transaction", "oracle");
return this.trackQuery(async () => {
const { result, executionTime } = await this.measureExecution(async () => {
try {
return await this.txConn!.execute(sql, params || [], {
outFormat: oracledb.OUT_FORMAT_OBJECT,
autoCommit: false,
});
} catch (error) {
throw mapDatabaseError(error, "oracle", sql);
}
});
const rows = (result.rows || []) as Record<string, unknown>[];
const fields = result.metaData?.map((m: { name: string }) => m.name) ?? [];
return {
rows,
fields,
rowCount: rows.length,
executionTime,
};
});
}
// ============================================================================
// Schema Operations
// ============================================================================
public async getSchema(): Promise<TableSchema[]> {
this.ensureConnected();
let conn: oracledb.Connection | undefined;
try {
conn = await this.pool!.getConnection();
const owner = this.config.user?.toUpperCase() || "";
// Get tables
const tablesRes = await conn.execute(
`SELECT TABLE_NAME, NUM_ROWS FROM ALL_TABLES WHERE OWNER = :1 ORDER BY TABLE_NAME`,
[owner],
{ outFormat: oracledb.OUT_FORMAT_OBJECT },
);
const tables = (tablesRes.rows || []) as Record<string, unknown>[];
// Get columns
const colsRes = await conn.execute(SCHEMA_COLUMNS_SQL, [owner], { outFormat: oracledb.OUT_FORMAT_OBJECT });
const allCols = (colsRes.rows || []) as Record<string, unknown>[];
// Get primary keys
const pkRes = await conn.execute(SCHEMA_PRIMARY_KEYS_SQL, [owner], { outFormat: oracledb.OUT_FORMAT_OBJECT });
const pkRows = (pkRes.rows || []) as Record<string, unknown>[];
const pkMap = new Map<string, Set<string>>();
for (const row of pkRows) {
const tbl = String(row.TABLE_NAME || "");
const col = String(row.COLUMN_NAME || "");
if (!pkMap.has(tbl)) pkMap.set(tbl, new Set());
pkMap.get(tbl)!.add(col);
}
// Get foreign keys
const fkRes = await conn.execute(SCHEMA_FOREIGN_KEYS_SQL, [owner], { outFormat: oracledb.OUT_FORMAT_OBJECT });
const fkRows = (fkRes.rows || []) as Record<string, unknown>[];
// Get indexes
const idxRes = await conn.execute(SCHEMA_INDEXES_SQL, [owner], { outFormat: oracledb.OUT_FORMAT_OBJECT });
const idxRows = (idxRes.rows || []) as Record<string, unknown>[];
// Group columns, indexes, foreign keys by table
const colsByTable = new Map<string, Record<string, unknown>[]>();
for (const c of allCols) {
const tbl = String(c.TABLE_NAME || "");
if (!colsByTable.has(tbl)) colsByTable.set(tbl, []);
colsByTable.get(tbl)!.push(c);
}
const fksByTable = new Map<string, Record<string, unknown>[]>();
for (const fk of fkRows) {
const tbl = String(fk.TABLE_NAME || "");
if (!fksByTable.has(tbl)) fksByTable.set(tbl, []);
fksByTable.get(tbl)!.push(fk);
}
const idxByTable = new Map<string, Map<string, { unique: boolean; columns: string[] }>>();
for (const idx of idxRows) {
const tbl = String(idx.TABLE_NAME || "");
const idxName = String(idx.INDEX_NAME || "");
if (!idxByTable.has(tbl)) idxByTable.set(tbl, new Map());
const tableIdxs = idxByTable.get(tbl)!;
if (!tableIdxs.has(idxName)) {
tableIdxs.set(idxName, {
unique: String(idx.UNIQUENESS || "") === "UNIQUE",
columns: [],
});
}
tableIdxs.get(idxName)!.columns.push(String(idx.COLUMN_NAME || ""));
}
return tables.map((t) => {
const tableName = String(t.TABLE_NAME || "");
const pks = pkMap.get(tableName) || new Set();
const columns = (colsByTable.get(tableName) || []).map((c) => ({
name: String(c.COLUMN_NAME || ""),
type: String(c.DATA_TYPE || ""),
nullable: String(c.NULLABLE || "") === "Y",
isPrimary: pks.has(String(c.COLUMN_NAME || "")),
defaultValue: c.DATA_DEFAULT ? String(c.DATA_DEFAULT).trim() : undefined,
}));
const foreignKeys = (fksByTable.get(tableName) || []).map((fk) => ({
columnName: String(fk.COLUMN_NAME || ""),
referencedTable: String(fk.REF_TABLE || ""),
referencedColumn: String(fk.REF_COLUMN || ""),
}));
const tableIdxs = idxByTable.get(tableName) || new Map();
const indexes = Array.from(tableIdxs.entries()).map(([name, info]) => ({
name,
columns: info.columns,
unique: info.unique,
}));
return {
name: tableName,
rowCount: Number(t.NUM_ROWS || 0),
columns,
indexes,
foreignKeys,
};
});
} finally {
if (conn) await conn.close();
}
}
// ============================================================================
// Health & Monitoring
// ============================================================================
public async getHealth(): Promise<HealthInfo> {
this.ensureConnected();
let conn: oracledb.Connection | undefined;
try {
conn = await this.pool!.getConnection();
let activeConnections = 0;
let databaseSize = "N/A";
let cacheHitRatio = "N/A";
const slowQueries: SlowQuery[] = [];
const activeSessions: ActiveSession[] = [];
// Active connections
try {
const connRes = await conn.execute(`SELECT COUNT(*) AS CNT FROM V$SESSION WHERE STATUS = 'ACTIVE'`, [], {
outFormat: oracledb.OUT_FORMAT_OBJECT,
});
const rows = (connRes.rows || []) as Record<string, unknown>[];
activeConnections = Number(rows[0]?.CNT || 0);
} catch {
/* V$ requires privileges */
}
// Database size
try {
const sizeRes = await conn.execute(
`SELECT ROUND(SUM(BYTES) / 1024 / 1024, 2) AS SIZE_MB FROM USER_SEGMENTS`,
[],
{ outFormat: oracledb.OUT_FORMAT_OBJECT },
);
const sizeRows = (sizeRes.rows || []) as Record<string, unknown>[];
const mb = Number(sizeRows[0]?.SIZE_MB || 0);
databaseSize = mb > 1024 ? `${(mb / 1024).toFixed(2)} GB` : `${mb} MB`;
} catch {
/* ignore */
}
// Cache hit ratio
try {
const cacheRes = await conn.execute(CACHE_HIT_RATIO_SQL, [], { outFormat: oracledb.OUT_FORMAT_OBJECT });
const cacheRows = (cacheRes.rows || []) as Record<string, unknown>[];
cacheHitRatio = `${cacheRows[0]?.HIT_RATIO || 0}%`;
} catch {
/* ignore */
}
// Slow queries
try {
const slowRes = await conn.execute(HEALTH_SLOW_QUERIES_SQL, [], { outFormat: oracledb.OUT_FORMAT_OBJECT });
for (const row of (slowRes.rows || []) as Record<string, unknown>[]) {
slowQueries.push({
query: String(row.QUERY || ""),
calls: Number(row.CALLS || 0),
avgTime: String(row.AVGTIME || "N/A"),
});
}
} catch {
/* V$SQL requires privileges */
}
// Active sessions
try {
const sessRes = await conn.execute(HEALTH_ACTIVE_SESSIONS_SQL, [], { outFormat: oracledb.OUT_FORMAT_OBJECT });
for (const row of (sessRes.rows || []) as Record<string, unknown>[]) {
activeSessions.push({
pid: String(row.SID || ""),
user: String(row.USERNAME || "unknown"),
database: String(row.DATABASE || ""),
state: String(row.STATUS || "unknown"),
query: String(row.QUERY || ""),
duration: String(row.DURATION || "N/A"),
});
}
} catch {
/* ignore */
}
return { activeConnections, databaseSize, cacheHitRatio, slowQueries, activeSessions };
} finally {
if (conn) await conn.close();
}
}
// ============================================================================
// Maintenance Operations
// ============================================================================
public async runMaintenance(type: MaintenanceType, target?: string): Promise<MaintenanceResult> {
this.ensureConnected();
const { result, executionTime } = await this.measureExecution(async () => {
let conn: oracledb.Connection | undefined;
try {
conn = await this.pool!.getConnection();
let sql = "";
switch (type) {
case "analyze":
if (target) {
sql = `BEGIN DBMS_STATS.GATHER_TABLE_STATS(USER, '${target.replace(/'/g, "''")}'); END;`;
} else {
sql = `BEGIN DBMS_STATS.GATHER_SCHEMA_STATS(USER); END;`;
}
break;
case "optimize":
if (target) {
sql = `ALTER INDEX "${target.replace(/"/g, '""')}" REBUILD`;
} else {
// Rebuild all indexes for user
const idxRes = await conn.execute(`SELECT INDEX_NAME FROM USER_INDEXES WHERE INDEX_TYPE = 'NORMAL'`, [], {
outFormat: oracledb.OUT_FORMAT_OBJECT,
});
for (const row of (idxRes.rows || []) as Record<string, unknown>[]) {
try {
await conn.execute(`ALTER INDEX "${String(row.INDEX_NAME)}" REBUILD`);
} catch {
/* individual index rebuild may fail */
}
}
return { success: true };
}
break;
case "kill":
if (!target) {
throw new QueryError("Target SID,SERIAL# is required for kill operation", "oracle");
}
sql = `ALTER SYSTEM KILL SESSION '${target.replace(/'/g, "''")}'`;
break;
}
// Unsupported types fall through the switch with sql left empty. A
// `default:` label is deliberately avoided here: bun's coverage emits
// a 0-hit line record for `default:` that no runtime execution ever
// credits, which permanently poisons the merged lcov report.
if (!sql) {
throw new QueryError(`Unsupported maintenance type: ${type}`, "oracle");
}
await conn.execute(sql);
return { success: true };
} finally {
if (conn) await conn.close();
}
});
return {
success: result.success,
executionTime,
message: `${type.toUpperCase()} completed successfully`,
};
}
// ============================================================================
// Pool Statistics
// ============================================================================
public getPoolStats() {
if (!this.pool) {
return { total: 0, idle: 0, active: 0, waiting: 0 };
}
return {
total: this.pool.connectionsOpen,
idle: this.pool.connectionsOpen - this.pool.connectionsInUse,
active: this.pool.connectionsInUse,
waiting: 0,
};
}
// ============================================================================
// Extended Monitoring Methods
// ============================================================================
public async getOverview(): Promise<DatabaseOverview> {
this.ensureConnected();
let conn: oracledb.Connection | undefined;
try {
conn = await this.pool!.getConnection();
let version = "Oracle";
let uptime = "N/A";
let startTime: Date | undefined;
let activeConnections = 0;
let maxConnections = 0;
let databaseSize = "0 bytes";
let databaseSizeBytes = 0;
let tableCount = 0;
let indexCount = 0;
// Version and uptime
try {
const vRes = await conn.execute(`SELECT BANNER FROM V$VERSION WHERE ROWNUM = 1`, [], {
outFormat: oracledb.OUT_FORMAT_OBJECT,
});
const vRows = (vRes.rows || []) as Record<string, unknown>[];
if (vRows[0]?.BANNER) version = String(vRows[0].BANNER);
} catch {
/* ignore */
}
try {
const upRes = await conn.execute(
`SELECT STARTUP_TIME, (SYSDATE - STARTUP_TIME) * 86400 AS UPTIME_SECS FROM V$INSTANCE`,
[],
{ outFormat: oracledb.OUT_FORMAT_OBJECT },
);
const upRows = (upRes.rows || []) as Record<string, unknown>[];
if (upRows[0]) {
const secs = Number(upRows[0].UPTIME_SECS || 0);
const days = Math.floor(secs / 86400);
const hours = Math.floor((secs % 86400) / 3600);
const minutes = Math.floor((secs % 3600) / 60);
uptime = days > 0 ? `${days}d ${hours}h ${minutes}m` : hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
if (upRows[0].STARTUP_TIME) startTime = new Date(String(upRows[0].STARTUP_TIME));
}
} catch {
/* ignore */
}
// Connections
try {
const sessRes = await conn.execute(`SELECT COUNT(*) AS CNT FROM V$SESSION WHERE TYPE = 'USER'`, [], {
outFormat: oracledb.OUT_FORMAT_OBJECT,
});
activeConnections = Number(((sessRes.rows || []) as Record<string, unknown>[])[0]?.CNT || 0);
const maxRes = await conn.execute(`SELECT VALUE FROM V$PARAMETER WHERE NAME = 'sessions'`, [], {
outFormat: oracledb.OUT_FORMAT_OBJECT,
});
maxConnections = Number(((maxRes.rows || []) as Record<string, unknown>[])[0]?.VALUE || 0);
} catch {
/* ignore */
}
// Database size
try {
const sizeRes = await conn.execute(`SELECT SUM(BYTES) AS TOTAL FROM USER_SEGMENTS`, [], {
outFormat: oracledb.OUT_FORMAT_OBJECT,
});
databaseSizeBytes = Number(((sizeRes.rows || []) as Record<string, unknown>[])[0]?.TOTAL || 0);
databaseSize = formatBytes(databaseSizeBytes);
} catch {
/* ignore */
}
// Table and index counts
try {
const cntRes = await conn.execute(OVERVIEW_OBJECT_COUNTS_SQL, [], { outFormat: oracledb.OUT_FORMAT_OBJECT });
const cntRows = (cntRes.rows || []) as Record<string, unknown>[];
tableCount = Number(cntRows[0]?.TABLE_COUNT || 0);
indexCount = Number(cntRows[0]?.INDEX_COUNT || 0);
} catch {
/* ignore */
}
return {
version,
uptime,
startTime,
activeConnections,
maxConnections,
databaseSize,
databaseSizeBytes,
tableCount,
indexCount,
};
} finally {
if (conn) await conn.close();
}
}
public async getPerformanceMetrics(): Promise<PerformanceMetrics> {
this.ensureConnected();
let conn: oracledb.Connection | undefined;
try {
conn = await this.pool!.getConnection();
let cacheHitRatio = 100;
let bufferPoolUsage: number | undefined;
try {
const cacheRes = await conn.execute(CACHE_HIT_RATIO_SQL, [], { outFormat: oracledb.OUT_FORMAT_OBJECT });
const rows = (cacheRes.rows || []) as Record<string, unknown>[];
cacheHitRatio = Number(rows[0]?.HIT_RATIO || 100);
bufferPoolUsage = cacheHitRatio;
} catch {
/* ignore */
}
return {
cacheHitRatio,
bufferPoolUsage,
};
} finally {
if (conn) await conn.close();
}
}
public async getSlowQueries(options?: { limit?: number }): Promise<SlowQueryStats[]> {
this.ensureConnected();
const limit = options?.limit ?? 10;
let conn: oracledb.Connection | undefined;
try {
conn = await this.pool!.getConnection();
const res = await conn.execute(
`${SLOW_QUERIES_BODY_SQL} WHERE ROWNUM <= ${Math.max(1, Math.trunc(Number(limit)) || 1)}`,
[],
{
outFormat: oracledb.OUT_FORMAT_OBJECT,
},
);
return ((res.rows || []) as Record<string, unknown>[]).map((r) => ({
queryId: String(r.QUERY_ID || ""),
query: String(r.QUERY || ""),
calls: Number(r.CALLS || 0),
totalTime: Number(r.TOTAL_TIME || 0),
avgTime: Number(r.AVG_TIME || 0),
rows: Number(r.ROW_CNT || 0),
sharedBlksHit: Number(r.BUF_GETS || 0),
sharedBlksRead: Number(r.DISK_READS || 0),
}));
} catch {
return [];
} finally {
if (conn) await conn.close();
}
}
public async getActiveSessions(options?: { limit?: number }): Promise<ActiveSessionDetails[]> {
this.ensureConnected();
const limit = options?.limit ?? 50;
let conn: oracledb.Connection | undefined;
try {
conn = await this.pool!.getConnection();
const res = await conn.execute(
`${ACTIVE_SESSIONS_BODY_SQL} WHERE ROWNUM <= ${Math.max(1, Math.trunc(Number(limit)) || 1)}`,
[],
{
outFormat: oracledb.OUT_FORMAT_OBJECT,
},
);
return ((res.rows || []) as Record<string, unknown>[]).map((r) => {
const secs = Number(r.DURATION_SECS || 0);
const durationStr =
secs > 3600
? `${Math.floor(secs / 3600)}h ${Math.floor((secs % 3600) / 60)}m`
: secs > 60
? `${Math.floor(secs / 60)}m ${secs % 60}s`
: `${secs}s`;
return {
pid: `${r.SID},${r["SERIAL#"]}`,
user: String(r.USERNAME || "unknown"),
database: String(r.SCHEMANAME || ""),
applicationName: String(r.PROGRAM || ""),
clientAddr: String(r.MACHINE || ""),
state: String(r.STATUS || "unknown"),
query: String(r.QUERY || r.SQL_ID || ""),
queryStart: r.LOGON_TIME ? new Date(String(r.LOGON_TIME)) : undefined,
duration: durationStr,
durationMs: secs * 1000,
waitEventType: r.WAIT_CLASS ? String(r.WAIT_CLASS) : undefined,
waitEvent: r.EVENT ? String(r.EVENT) : undefined,
blocked: false,
};
});
} catch {
return [];
} finally {
if (conn) await conn.close();