|
| 1 | +// `insta db query` seams — the pure renderers plus the handler flow through an injected api seam |
| 2 | +// (the DomainDeps convention), so nothing here reaches a backend (mirrors db-stats.test.ts / |
| 3 | +// compute-domain-flow.test.ts). |
| 4 | +import { afterAll, afterEach, describe, expect, it, vi } from 'vitest' |
| 5 | + |
| 6 | +import { |
| 7 | + consoleExecPath, execBody, renderMysqlRows, renderRedisReply, renderMongoResult, |
| 8 | + dbQuery, type DbQueryDeps, |
| 9 | +} from '../src/commands/db-query.js' |
| 10 | + |
| 11 | +describe('consoleExecPath', () => { |
| 12 | + it('is the managed-DB console exec route for the service', () => { |
| 13 | + expect(consoleExecPath('pr_1', 'svc_9')).toBe('/projects/pr_1/database/console/svc_9/exec') |
| 14 | + }) |
| 15 | +}) |
| 16 | + |
| 17 | +describe('execBody', () => { |
| 18 | + // mysql/mongodb quote the whole statement, so the tokens rejoin into one command string. |
| 19 | + it('joins mysql args into a single command', () => { |
| 20 | + expect(execBody('mysql', ['select', '*', 'from', 'products', 'limit', '10'])) |
| 21 | + .toEqual({ command: 'select * from products limit 10' }) |
| 22 | + }) |
| 23 | + |
| 24 | + // redis is pre-tokenized: each arg stays a distinct argv element, verbatim — a value that |
| 25 | + // contains a space (already one shell token) must not be re-split. |
| 26 | + it('keeps redis args as a verbatim argv, never a joined string', () => { |
| 27 | + expect(execBody('redis', ['GET', 'mykey'])).toEqual({ argv: ['GET', 'mykey'] }) |
| 28 | + expect(execBody('redis', ['SET', 'greeting', 'hello world'])) |
| 29 | + .toEqual({ argv: ['SET', 'greeting', 'hello world'] }) |
| 30 | + }) |
| 31 | + |
| 32 | + it('adds database for mongodb only when --database is given', () => { |
| 33 | + expect(execBody('mongodb', ['db.users.find().limit(10).toArray()'], 'shop')) |
| 34 | + .toEqual({ command: 'db.users.find().limit(10).toArray()', database: 'shop' }) |
| 35 | + const bare = execBody('mongodb', ['db.users.find()']) |
| 36 | + expect(bare).toEqual({ command: 'db.users.find()' }) |
| 37 | + expect('database' in bare).toBe(false) |
| 38 | + }) |
| 39 | +}) |
| 40 | + |
| 41 | +describe('renderMysqlRows', () => { |
| 42 | + it('renders the header and rows as an aligned table with a count footer', () => { |
| 43 | + const lines = renderMysqlRows({ |
| 44 | + columns: [{ name: 'id' }, { name: 'name' }, { name: 'price' }], |
| 45 | + rows: [ |
| 46 | + ['1', 'apple', '3'], |
| 47 | + ['2', 'banana', null], |
| 48 | + ], |
| 49 | + rowCount: 2, |
| 50 | + truncated: false, |
| 51 | + }) |
| 52 | + expect(lines).toEqual([ |
| 53 | + 'id name price', |
| 54 | + '1 apple 3', |
| 55 | + '2 banana —', |
| 56 | + '(2 rows)', |
| 57 | + ]) |
| 58 | + }) |
| 59 | + |
| 60 | + // A null cell is a missing value, rendered as the repo's em-dash — never an empty string or 0. |
| 61 | + it('renders a null cell as an em-dash', () => { |
| 62 | + const lines = renderMysqlRows({ columns: [{ name: 'v' }], rows: [[null]], rowCount: 1 }) |
| 63 | + expect(lines[1]).toBe('—') |
| 64 | + }) |
| 65 | + |
| 66 | + // The footer reports the server's rowCount (not rows.length) and flags a truncated page. |
| 67 | + it('uses the returned rowCount and marks truncation', () => { |
| 68 | + const lines = renderMysqlRows({ |
| 69 | + columns: [{ name: 'x' }], |
| 70 | + rows: [['a'], ['b']], |
| 71 | + rowCount: 100, |
| 72 | + truncated: true, |
| 73 | + }) |
| 74 | + expect(lines).toEqual(['x', 'a', 'b', '(100 rows, truncated)']) |
| 75 | + }) |
| 76 | +}) |
| 77 | + |
| 78 | +describe('renderRedisReply', () => { |
| 79 | + it('prints a scalar reply raw', () => { |
| 80 | + expect(renderRedisReply('OK')).toBe('OK') |
| 81 | + expect(renderRedisReply(42)).toBe('42') |
| 82 | + expect(renderRedisReply(0)).toBe('0') |
| 83 | + }) |
| 84 | + |
| 85 | + it('pretty-prints a structured reply as JSON', () => { |
| 86 | + expect(renderRedisReply(['a', 'b'])).toBe(JSON.stringify(['a', 'b'], null, 2)) |
| 87 | + expect(renderRedisReply({ field: 'v' })).toBe(JSON.stringify({ field: 'v' }, null, 2)) |
| 88 | + expect(renderRedisReply(null)).toBe('null') |
| 89 | + }) |
| 90 | +}) |
| 91 | + |
| 92 | +describe('renderMongoResult', () => { |
| 93 | + it('pretty-prints the result as JSON', () => { |
| 94 | + const result = [{ _id: 1, name: 'a' }] |
| 95 | + expect(renderMongoResult(result)).toBe(JSON.stringify(result, null, 2)) |
| 96 | + expect(renderMongoResult({})).toBe('{}') |
| 97 | + }) |
| 98 | +}) |
| 99 | + |
| 100 | +// ---- handler flow, through an injected api seam so nothing reaches a backend ---- |
| 101 | +type Svc = { id: string; type: string; name: string } |
| 102 | +type Call = { method: string; path: string; body?: unknown } |
| 103 | +function deps(services: Svc[], res: { status: number; body: any } = { status: 200, body: {} }) { |
| 104 | + const calls: Call[] = [] |
| 105 | + const api = { |
| 106 | + request: async (method: string, path: string) => { |
| 107 | + calls.push({ method, path }) |
| 108 | + return { services } |
| 109 | + }, |
| 110 | + rawRequest: async (method: string, path: string, body?: unknown) => { |
| 111 | + calls.push({ method, path, body }) |
| 112 | + return res |
| 113 | + }, |
| 114 | + } |
| 115 | + return { deps: { api, project: { projectId: 'p1', branch: 'main' } } as unknown as DbQueryDeps, calls } |
| 116 | +} |
| 117 | + |
| 118 | +describe('dbQuery (handler flow, injected api — no network)', () => { |
| 119 | + const stdout: string[] = [] |
| 120 | + const stderr: string[] = [] |
| 121 | + const outSpy = vi.spyOn(process.stdout, 'write').mockImplementation((c: any) => { stdout.push(String(c)); return true }) |
| 122 | + const errSpy = vi.spyOn(process.stderr, 'write').mockImplementation((c: any) => { stderr.push(String(c)); return true }) |
| 123 | + afterEach(() => { stdout.length = 0; stderr.length = 0; process.exitCode = undefined }) |
| 124 | + afterAll(() => { outSpy.mockRestore(); errSpy.mockRestore() }) |
| 125 | + const out = () => stdout.join('') |
| 126 | + const err = () => stderr.join('') |
| 127 | + |
| 128 | + const mysql = [{ id: 'svc_shop', type: 'mysql', name: 'shop' }, { id: 'svc_an', type: 'mysql', name: 'analytics' }] |
| 129 | + |
| 130 | + it('resolves the service by NAME (not type/position) and posts to that id, with the branch on the lookup', async () => { |
| 131 | + const { deps: d, calls } = deps(mysql, { status: 200, body: { columns: [{ name: 'id' }], rows: [['1']], rowCount: 1 } }) |
| 132 | + await dbQuery('analytics', ['select', '*', 'from', 'products'], {}, d) |
| 133 | + expect(calls[0]).toEqual({ method: 'GET', path: '/projects/p1/services?branch=main' }) |
| 134 | + expect(calls[1]).toEqual({ method: 'POST', path: consoleExecPath('p1', 'svc_an'), body: { command: 'select * from products' } }) |
| 135 | + expect(out()).toBe('id\n1\n(1 rows)\n') |
| 136 | + }) |
| 137 | + |
| 138 | + it('rejects a postgres/non-managed service BEFORE any exec is posted', async () => { |
| 139 | + const { deps: d, calls } = deps([{ id: 'svc_pg', type: 'postgres', name: 'db' }]) |
| 140 | + await expect(dbQuery('db', ['select 1'], {}, d)).rejects.toThrow('exit 1') |
| 141 | + expect(process.exitCode).toBe(1) |
| 142 | + expect(err()).toMatch(/managed databases \(mysql\/redis\/mongodb\); postgres uses the SQL editor/) |
| 143 | + expect(calls.map((c) => c.method)).toEqual(['GET']) // never reached the POST |
| 144 | + }) |
| 145 | + |
| 146 | + it('errors when the named service is not on the branch', async () => { |
| 147 | + const { deps: d, calls } = deps(mysql) |
| 148 | + await expect(dbQuery('nope', ['select 1'], {}, d)).rejects.toThrow('exit 1') |
| 149 | + expect(err()).toMatch(/service not found: nope/) |
| 150 | + expect(calls.map((c) => c.method)).toEqual(['GET']) |
| 151 | + }) |
| 152 | + |
| 153 | + it('rejects --database on a non-mongodb engine BEFORE the POST, instead of silently dropping it', async () => { |
| 154 | + const { deps: d, calls } = deps(mysql) |
| 155 | + await expect(dbQuery('shop', ['select 1'], { database: 'other' }, d)).rejects.toThrow('exit 1') |
| 156 | + expect(process.exitCode).toBe(1) |
| 157 | + expect(err()).toMatch(/--database is only supported for mongodb services/) |
| 158 | + expect(calls.map((c) => c.method)).toEqual(['GET']) // resolved the engine, then refused |
| 159 | + }) |
| 160 | + |
| 161 | + it('passes --database through to the exec body for a mongodb service', async () => { |
| 162 | + const { deps: d, calls } = deps([{ id: 'svc_m', type: 'mongodb', name: 'docs' }], { status: 200, body: { result: [] } }) |
| 163 | + await dbQuery('docs', ['db.users.find()'], { database: 'shop' }, d) |
| 164 | + expect(calls[1]).toEqual({ method: 'POST', path: consoleExecPath('p1', 'svc_m'), body: { command: 'db.users.find()', database: 'shop' } }) |
| 165 | + }) |
| 166 | + |
| 167 | + it('rejects empty args BEFORE loading config or making any request', async () => { |
| 168 | + const { deps: d, calls } = deps(mysql) |
| 169 | + await expect(dbQuery('shop', [], {}, d)).rejects.toThrow('exit 1') |
| 170 | + expect(process.exitCode).toBe(1) |
| 171 | + expect(err()).toMatch(/usage: insta db query/) |
| 172 | + expect(calls).toEqual([]) // not even the service lookup ran |
| 173 | + }) |
| 174 | + |
| 175 | + it('relays a 202 approval gate: exit 2, hint on stderr, stdout untouched (non-json)', async () => { |
| 176 | + const body = { status: 'approval_required', action: 'db.query', approvalId: 'appr_1' } |
| 177 | + const { deps: d } = deps(mysql, { status: 202, body }) |
| 178 | + await dbQuery('shop', ['select 1'], {}, d) // handleApproval returns, no throw |
| 179 | + expect(process.exitCode).toBe(2) |
| 180 | + expect(err()).toMatch(/approval required for db\.query — run: insta approvals approve appr_1/) |
| 181 | + expect(out()).toBe('') |
| 182 | + }) |
| 183 | + |
| 184 | + it('--json prints the platform body verbatim and skips the human table', async () => { |
| 185 | + const body = { columns: [{ name: 'id' }], rows: [['1']], rowCount: 1 } |
| 186 | + const { deps: d } = deps(mysql, { status: 200, body }) |
| 187 | + await dbQuery('shop', ['select 1'], { json: true }, d) |
| 188 | + expect(JSON.parse(out())).toEqual(body) |
| 189 | + }) |
| 190 | +}) |
0 commit comments