@kealthas-dev/opencode-oracle-query 0.0.0-stage → 1.1.23
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.
- package/README.md +90 -2
- package/dist/cli.js +180 -0
- package/package.json +32 -4
package/README.md
CHANGED
|
@@ -1,3 +1,91 @@
|
|
|
1
|
-
#
|
|
1
|
+
# oracle
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Read-only SQL for the agent as a command, `opencode-oracle-query`, which reads one statement from stdin, connects straight to Oracle, runs it and prints the rows as CSV. Written in TypeScript (one file, `src/cli.ts`), compiled to `dist/`. There is no server to run.
|
|
4
|
+
|
|
5
|
+
It is a command, not an MCP tool, because an MCP tool result goes into the model's context whole: the agent cannot `head`, `grep` or `awk` it first. A command's stdout can be cut, piped or redirected to a file.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
opencode-oracle-query <<'SQL'
|
|
11
|
+
SELECT * FROM employees WHERE dept = 10
|
|
12
|
+
SQL
|
|
13
|
+
|
|
14
|
+
opencode-oracle-query <<'SQL' > /tmp/big.csv
|
|
15
|
+
SELECT * FROM big_table
|
|
16
|
+
SQL
|
|
17
|
+
|
|
18
|
+
opencode-oracle-query <<'SQL' | head -n 20
|
|
19
|
+
SELECT * FROM big_table
|
|
20
|
+
SQL
|
|
21
|
+
|
|
22
|
+
opencode-oracle-query < query.sql
|
|
23
|
+
opencode-oracle-query --help
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The statement is read from stdin, always. There is no argument form on purpose: SQL is full of single quotes and sometimes `$`, so quoting it as an argument is a way to get it wrong (inside double quotes the shell expands `$`, so `v$session` would reach Oracle as `v`). With a quoted heredoc delimiter (`<<'SQL'`) the shell touches nothing.
|
|
27
|
+
|
|
28
|
+
That is the whole interface: one SQL statement on stdin, every row of the result on stdout as CSV, no arguments, no options. Nothing is cut off, so cut the output in the SQL (a `WHERE` clause, an aggregate, `FETCH FIRST n ROWS ONLY`) or in the shell. A database error is printed to stderr exactly as the database gave it, nothing added.
|
|
29
|
+
|
|
30
|
+
Exit codes: `0` ok, `1` anything went wrong (the SQL, the connection, the config, a usage error); stderr says what.
|
|
31
|
+
|
|
32
|
+
## Design
|
|
33
|
+
|
|
34
|
+
- **One connection per run.** Nothing a statement leaves open outlives the run (closing rolls back), concurrent runs never share a session, and a session dropped on the database side fails only that run.
|
|
35
|
+
- **Read-only by two layers.** Every query runs after `SET TRANSACTION READ ONLY`, so Oracle itself refuses `INSERT`, `UPDATE` and `DELETE` (`ORA-01456`) even for an account that holds write grants. **DDL is not covered:** it commits first and then runs, so `CREATE TABLE` or `DROP TABLE` goes through. The connecting account's own grants are the real boundary, see below.
|
|
36
|
+
- **Plain output.** CLOB and NCLOB come back as text, BLOB as base64, RAW as hex, DATE and TIMESTAMP as `YYYY-MM-DD HH24:MI:SS` text (a TIMESTAMP keeps milliseconds, nothing finer; time-zone types become an ISO instant). A trailing `;` on a `SELECT` is dropped, since Oracle rejects it. The session's date format is set to match the output, so a date literal in the SQL converts the way the output prints. A join with two columns of the same name keeps both (the driver renames the second to `ID_1`).
|
|
37
|
+
- **A table changed a moment ago cannot be read for a few seconds.** A read-only transaction takes a snapshot, and Oracle answers `ORA-01466` for a table whose definition changed within about the last few seconds. It passes by itself.
|
|
38
|
+
|
|
39
|
+
## Recommended read-only account
|
|
40
|
+
|
|
41
|
+
The transaction guard does not stop DDL, so the account `ORACLE_USER` points at is the actual safety boundary. Give it read access only, for example:
|
|
42
|
+
|
|
43
|
+
```sql
|
|
44
|
+
CREATE USER readonly IDENTIFIED BY "<a real password>";
|
|
45
|
+
|
|
46
|
+
GRANT CREATE SESSION, READ ANY TABLE, SELECT ANY SEQUENCE,
|
|
47
|
+
SELECT ANY DICTIONARY, SELECT_CATALOG_ROLE, EXECUTE_CATALOG_ROLE
|
|
48
|
+
TO readonly;
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- `SELECT ANY DICTIONARY` does **not** expose `SYS.USER$` (password hashes) or other similarly hardened SYS tables: Oracle hardcodes that protection regardless of grants.
|
|
52
|
+
- `EXECUTE_CATALOG_ROLE` is broader than its name suggests: it grants `EXECUTE` on 115 SYS packages, not just `DBMS_METADATA`, including `DBMS_LOCK`, `DBMS_FILE_TRANSFER`, `DBMS_REDEFINITION` and `DBMS_RLS`. It is there for DDL extraction through `DBMS_METADATA`; drop it if you do not need that.
|
|
53
|
+
|
|
54
|
+
## Configuration
|
|
55
|
+
|
|
56
|
+
The connection settings are read from a file, not environment variables, at a fixed location under `$HOME/.config/kealthas-dev/opencode-oracle-query/`: `config.json` by default, or `config-<name>.json` with `ORACLE_CONFIG_ENV=<name>`. Only a short name is taken from the environment, never a path, so a shell that did not expand `~` cannot point the command at a wrong location. The file is read on every run, so editing it needs nothing restarted.
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
{
|
|
60
|
+
"ORACLE_CONNECT_STRING": "hostname:1521/service_name",
|
|
61
|
+
"ORACLE_USER": "username",
|
|
62
|
+
"ORACLE_PASSWORD": "password",
|
|
63
|
+
"ORACLE_DEFAULT_SCHEMA": "SCHEMA_NAME"
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`ORACLE_CONNECT_STRING` is an Easy Connect string (`host:port/service_name`) or a full TNS descriptor. `ORACLE_DEFAULT_SCHEMA` is optional (exact case as Oracle stores it, normally uppercase): it sets the session's current schema, so the SQL can leave the schema prefix off. A missing or broken file makes the run fail with the path and the expected shape in the message. `config.example.json` shows the shape.
|
|
68
|
+
|
|
69
|
+
```text
|
|
70
|
+
~/.config/kealthas-dev/opencode-oracle-query/
|
|
71
|
+
├── config.json # used when ORACLE_CONFIG_ENV is unset
|
|
72
|
+
├── config-prod.json # ORACLE_CONFIG_ENV=prod
|
|
73
|
+
└── config-dev.json # ORACLE_CONFIG_ENV=dev
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Installing it
|
|
77
|
+
|
|
78
|
+
Published as `@kealthas-dev/opencode-oracle-query`. Install it globally, which puts `opencode-oracle-query` on `PATH`, and write the config file. See SETUP.md step 6.
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
npm install -g @kealthas-dev/opencode-oracle-query
|
|
82
|
+
echo 'SELECT 1 FROM dual' | ORACLE_CONFIG_ENV=prod opencode-oracle-query # reads config-prod.json
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
For the repo's own checkout, `npm install && npm run build` in this directory, then `node dist/cli.js < query.sql`.
|
|
86
|
+
|
|
87
|
+
## Status
|
|
88
|
+
|
|
89
|
+
`oracle.test.ts` runs against a real Oracle instance in the docker sandbox (see `docker/notes.md`, "Oracle test instance"), running the built command the way an agent would: CSV output and quoting, a trailing semicolon, `$`, quotes and a backslash arriving untouched, a `V$` view through a quoted heredoc, an argument refused, a 50000-row result coming back whole, `| head` closing the pipe early, duplicate column names, dates/CLOB/BLOB/RAW as text, `ORACLE_DEFAULT_SCHEMA`, `INSERT`/`UPDATE`/`DELETE` refused with nothing changed, an Oracle error passed through untouched, usage errors, bad credentials, and a missing or broken config file.
|
|
90
|
+
|
|
91
|
+
Known, not covered: DDL goes through (see Design), and a TIMESTAMP loses anything finer than milliseconds.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import oracledb from "oracledb";
|
|
6
|
+
// Exit codes: 0 ok, 1 anything went wrong (stderr says what).
|
|
7
|
+
const EXIT_FAILURE = 1;
|
|
8
|
+
const NAME = "opencode-oracle-query";
|
|
9
|
+
const CONFIG_DIR = join(homedir(), ".config", "kealthas-dev", "opencode-oracle-query");
|
|
10
|
+
// oracledb has no timeout of any kind by default (getConnection() can hang
|
|
11
|
+
// forever against a host that accepts the TCP connection but never
|
|
12
|
+
// responds, and execute() the same against a connection that goes dark
|
|
13
|
+
// mid-session, e.g. blocked on a lock) - both units are oracledb's own,
|
|
14
|
+
// not a shared convention: connectTimeout is seconds, callTimeout is ms.
|
|
15
|
+
const CONNECT_TIMEOUT_SECONDS = 10;
|
|
16
|
+
const CALL_TIMEOUT_MS = 30_000;
|
|
17
|
+
const HELP = `Usage: ${NAME} <<'SQL'
|
|
18
|
+
<sql, any number of lines>
|
|
19
|
+
SQL
|
|
20
|
+
|
|
21
|
+
Runs one read-only SQL statement, read from stdin, against the configured Oracle database and prints every row to
|
|
22
|
+
stdout as CSV. Nothing is cut off, and errors from the database are printed exactly as the database gave them.
|
|
23
|
+
|
|
24
|
+
There are no arguments and no options. The statement goes in a heredoc with a quoted delimiter (<<'SQL', as above),
|
|
25
|
+
so the shell leaves it alone: a $ (as in v$session), a backtick, a quote or a backslash all reach Oracle as written.
|
|
26
|
+
|
|
27
|
+
Exit codes: 0 ok, 1 failed; stderr says why.`;
|
|
28
|
+
function usageError(message) {
|
|
29
|
+
console.error(`${NAME}: ${message}\n\n${HELP}`);
|
|
30
|
+
process.exit(EXIT_FAILURE);
|
|
31
|
+
}
|
|
32
|
+
async function readStdin() {
|
|
33
|
+
const chunks = [];
|
|
34
|
+
for await (const chunk of process.stdin)
|
|
35
|
+
chunks.push(chunk);
|
|
36
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
37
|
+
}
|
|
38
|
+
// The whole of stdin is the statement. There is deliberately no argument form: SQL is full of single quotes and
|
|
39
|
+
// sometimes $, so any shell quoting of it is a way to get it wrong.
|
|
40
|
+
async function readSql(argv) {
|
|
41
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
42
|
+
console.log(HELP);
|
|
43
|
+
process.exit(0);
|
|
44
|
+
}
|
|
45
|
+
if (argv.length > 0)
|
|
46
|
+
usageError("the statement is read from stdin, not given as an argument");
|
|
47
|
+
if (process.stdin.isTTY)
|
|
48
|
+
usageError("no statement: give it on stdin, with a heredoc");
|
|
49
|
+
const sql = await readStdin();
|
|
50
|
+
if (sql.trim() === "")
|
|
51
|
+
usageError("the statement on stdin is empty");
|
|
52
|
+
return sql;
|
|
53
|
+
}
|
|
54
|
+
const SAMPLE_CONFIG = {
|
|
55
|
+
ORACLE_CONNECT_STRING: "hostname:1521/service_name (Easy Connect or TNS, either works)",
|
|
56
|
+
ORACLE_USER: "username",
|
|
57
|
+
ORACLE_PASSWORD: "password",
|
|
58
|
+
ORACLE_DEFAULT_SCHEMA: "SCHEMA_NAME (optional; exact case as Oracle stores it - normally UPPERCASE, e.g. HR not hr)",
|
|
59
|
+
};
|
|
60
|
+
// config.json by default, config-<name>.json when ORACLE_CONFIG_ENV is set. Read on every run,
|
|
61
|
+
// so editing it needs nothing restarted. Only a short name is taken from the environment, never a path.
|
|
62
|
+
function loadDatabaseConfig() {
|
|
63
|
+
const envName = process.env.ORACLE_CONFIG_ENV;
|
|
64
|
+
const path = join(CONFIG_DIR, envName ? `config-${envName}.json` : "config.json");
|
|
65
|
+
const sample = `Expected database config file at: ${path}\n${JSON.stringify(SAMPLE_CONFIG, null, 2)}`;
|
|
66
|
+
if (!existsSync(path))
|
|
67
|
+
throw new Error(`Database config file not found.\n${sample}`);
|
|
68
|
+
try {
|
|
69
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
70
|
+
if (!raw.ORACLE_CONNECT_STRING || !raw.ORACLE_USER || !raw.ORACLE_PASSWORD) {
|
|
71
|
+
throw new Error("missing one of ORACLE_CONNECT_STRING, ORACLE_USER, ORACLE_PASSWORD");
|
|
72
|
+
}
|
|
73
|
+
return { connectString: raw.ORACLE_CONNECT_STRING, user: raw.ORACLE_USER, password: raw.ORACLE_PASSWORD, schema: raw.ORACLE_DEFAULT_SCHEMA };
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
throw new Error(`Failed to load database config from ${path}: ${err.message}\n${sample}`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// Everything comes back as plain text or numbers, never as a driver object:
|
|
80
|
+
// - CLOB/NCLOB as strings and BLOB as base64 (Lob objects hold the connection and can't be printed)
|
|
81
|
+
// - RAW as hex
|
|
82
|
+
// - DATE/TIMESTAMP as "YYYY-MM-DD HH24:MI:SS[.mmm]" wall-clock text. The driver hands these over as JS Dates built
|
|
83
|
+
// in this process's time zone, so the local getters give back the stored wall-clock value; a JS Date holds
|
|
84
|
+
// milliseconds, so finer fractions are cut. Time-zone types become an ISO instant.
|
|
85
|
+
const pad = (n, width = 2) => String(n).padStart(width, "0");
|
|
86
|
+
const wallClock = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
87
|
+
oracledb.fetchTypeHandler = (meta) => {
|
|
88
|
+
const t = meta.dbType;
|
|
89
|
+
if (t === oracledb.DB_TYPE_CLOB || t === oracledb.DB_TYPE_NCLOB)
|
|
90
|
+
return { type: oracledb.STRING };
|
|
91
|
+
if (t === oracledb.DB_TYPE_BLOB) {
|
|
92
|
+
return { type: oracledb.BUFFER, converter: (val) => val?.toString("base64") ?? null };
|
|
93
|
+
}
|
|
94
|
+
if (t === oracledb.DB_TYPE_RAW)
|
|
95
|
+
return { type: oracledb.STRING };
|
|
96
|
+
if (t === oracledb.DB_TYPE_DATE)
|
|
97
|
+
return { converter: (val) => (val instanceof Date ? wallClock(val) : val) };
|
|
98
|
+
if (t === oracledb.DB_TYPE_TIMESTAMP) {
|
|
99
|
+
return { converter: (val) => (val instanceof Date ? wallClock(val) + (val.getMilliseconds() ? `.${pad(val.getMilliseconds(), 3)}` : "") : val) };
|
|
100
|
+
}
|
|
101
|
+
if (t === oracledb.DB_TYPE_TIMESTAMP_TZ || t === oracledb.DB_TYPE_TIMESTAMP_LTZ) {
|
|
102
|
+
return { converter: (val) => (val instanceof Date ? val.toISOString() : val) };
|
|
103
|
+
}
|
|
104
|
+
return undefined;
|
|
105
|
+
};
|
|
106
|
+
// A trailing ";" is a SQL*Plus convention; the server rejects it (ORA-00911). Agents add one by habit.
|
|
107
|
+
function stripTrailingSemicolon(sql) {
|
|
108
|
+
return /^\s*(select|with)\b/i.test(sql) ? sql.replace(/;\s*$/, "") : sql;
|
|
109
|
+
}
|
|
110
|
+
const cell = (v) => (v === null || v === undefined ? "" : typeof v === "object" ? JSON.stringify(v) : String(v));
|
|
111
|
+
function toCsv(columns, rows) {
|
|
112
|
+
const esc = (s) => (/[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s);
|
|
113
|
+
return [columns.map(esc).join(","), ...rows.map((r) => r.map((v) => esc(cell(v))).join(","))].join("\n") + "\n";
|
|
114
|
+
}
|
|
115
|
+
async function main() {
|
|
116
|
+
const sql = await readSql(process.argv.slice(2));
|
|
117
|
+
let config;
|
|
118
|
+
try {
|
|
119
|
+
config = loadDatabaseConfig();
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
console.error(`${NAME}: ${err.message}`);
|
|
123
|
+
return EXIT_FAILURE;
|
|
124
|
+
}
|
|
125
|
+
// One connection per run: nothing a statement leaves open outlives it (closing rolls back).
|
|
126
|
+
let connection;
|
|
127
|
+
try {
|
|
128
|
+
connection = await oracledb.getConnection({
|
|
129
|
+
connectString: config.connectString,
|
|
130
|
+
user: config.user,
|
|
131
|
+
password: config.password,
|
|
132
|
+
connectTimeout: CONNECT_TIMEOUT_SECONDS,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
console.error(err.message); // the database's own words
|
|
137
|
+
return EXIT_FAILURE;
|
|
138
|
+
}
|
|
139
|
+
connection.callTimeout = CALL_TIMEOUT_MS;
|
|
140
|
+
try {
|
|
141
|
+
// ALTER SESSION commits implicitly, and SET TRANSACTION must be the first
|
|
142
|
+
// statement of a transaction, so all session setup comes first.
|
|
143
|
+
// No bind variables for identifiers in ALTER SESSION: the schema is interpolated, which is fine
|
|
144
|
+
// for a caller that may run arbitrary SQL anyway.
|
|
145
|
+
if (config.schema)
|
|
146
|
+
await connection.execute(`ALTER SESSION SET CURRENT_SCHEMA = "${config.schema}"`);
|
|
147
|
+
// So a date literal in the SQL ('2024-01-02 03:04:05') converts the way the output prints.
|
|
148
|
+
await connection.execute(`ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS' NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF' NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF TZR'`);
|
|
149
|
+
// DML is then refused by Oracle itself (ORA-01456), even for an account that holds write grants.
|
|
150
|
+
// DDL is not covered (it commits first), so the account's own grants stay the real boundary.
|
|
151
|
+
await connection.execute("SET TRANSACTION READ ONLY");
|
|
152
|
+
const result = await connection.execute(stripTrailingSemicolon(sql), [], { outFormat: oracledb.OUT_FORMAT_ARRAY });
|
|
153
|
+
if (!result.metaData) {
|
|
154
|
+
console.log("statement executed, no result set"); // DDL and the like
|
|
155
|
+
return 0;
|
|
156
|
+
}
|
|
157
|
+
process.stdout.write(toCsv(result.metaData.map((c) => c.name), (result.rows ?? [])));
|
|
158
|
+
return 0;
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
const message = err.message;
|
|
162
|
+
console.error(message); // the database's own words, nothing added
|
|
163
|
+
return EXIT_FAILURE;
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
await connection.close().catch(() => { });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
// `... | head` closes the pipe early; that is not an error.
|
|
170
|
+
process.stdout.on("error", (err) => {
|
|
171
|
+
if (err.code === "EPIPE")
|
|
172
|
+
process.exit(0);
|
|
173
|
+
throw err;
|
|
174
|
+
});
|
|
175
|
+
main().then((code) => {
|
|
176
|
+
process.exitCode = code;
|
|
177
|
+
}, (err) => {
|
|
178
|
+
console.error(`${NAME}: ${err.message}`);
|
|
179
|
+
process.exitCode = EXIT_FAILURE;
|
|
180
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kealthas-dev/opencode-oracle-query",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "1.1.23",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Read-only SQL for the agent as a command, `opencode-oracle-query`, reading the statement from stdin and connecting straight to Oracle - see README.md for the design and the config.json-driven config",
|
|
6
|
+
"main": "dist/cli.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"opencode-oracle-query": "dist/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist"
|
|
12
|
+
],
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/Keal-thas/opencode-toolkit.git",
|
|
19
|
+
"directory": "cli/oracle"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "tsc",
|
|
23
|
+
"test": "tsx --test oracle.test.ts"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"oracledb": "^6.5.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^22.0.0",
|
|
30
|
+
"@types/oracledb": "^6.5.0",
|
|
31
|
+
"tsx": "^4.19.0",
|
|
32
|
+
"typescript": "^5.6.0"
|
|
33
|
+
}
|
|
34
|
+
}
|