|
| 1 | +import fs from 'node:fs'; |
| 2 | +import os from 'node:os'; |
1 | 3 | import path from 'node:path'; |
2 | | -import { describe, it, expect } from 'vitest'; |
| 4 | +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; |
3 | 5 | import { defineQuery, schema } from '../src/index'; |
4 | 6 |
|
5 | 7 | const fixture = (name: string) => path.join(__dirname, 'fixtures', name); |
@@ -240,6 +242,54 @@ describe('defineQuery — schema mode', () => { |
240 | 242 | }); |
241 | 243 | }); |
242 | 244 |
|
| 245 | + describe('exportTo option', () => { |
| 246 | + let tmpDir: string; |
| 247 | + |
| 248 | + beforeEach(() => { |
| 249 | + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sql-render-')); |
| 250 | + }); |
| 251 | + |
| 252 | + afterEach(() => { |
| 253 | + fs.rmSync(tmpDir, { recursive: true, force: true }); |
| 254 | + }); |
| 255 | + |
| 256 | + it('writes rendered sql to the given file', () => { |
| 257 | + const query = defineQuery(fixture('simple.sql'), { |
| 258 | + table: schema.identifier, |
| 259 | + id: schema.number, |
| 260 | + }); |
| 261 | + const outPath = path.join(tmpDir, 'rendered.sql'); |
| 262 | + const { sql } = query({ table: 'users', id: 33 }, { exportTo: outPath }); |
| 263 | + expect(fs.readFileSync(outPath, 'utf-8')).toBe(sql); |
| 264 | + }); |
| 265 | + |
| 266 | + it('creates parent directories recursively', () => { |
| 267 | + const query = defineQuery(fixture('simple.sql'), { |
| 268 | + table: schema.identifier, |
| 269 | + id: schema.number, |
| 270 | + }); |
| 271 | + const outPath = path.join(tmpDir, 'nested', 'deep', 'out.sql'); |
| 272 | + query({ table: 'users', id: 1 }, { exportTo: outPath }); |
| 273 | + expect(fs.existsSync(outPath)).toBe(true); |
| 274 | + }); |
| 275 | + |
| 276 | + it('does not write a file when exportTo is omitted', () => { |
| 277 | + const query = defineQuery(fixture('simple.sql'), { |
| 278 | + table: schema.identifier, |
| 279 | + id: schema.number, |
| 280 | + }); |
| 281 | + query({ table: 'users', id: 1 }); |
| 282 | + expect(fs.readdirSync(tmpDir)).toHaveLength(0); |
| 283 | + }); |
| 284 | + |
| 285 | + it('works in generic mode', () => { |
| 286 | + const query = defineQuery<{ table: string; id: number }>(fixture('simple.sql')); |
| 287 | + const outPath = path.join(tmpDir, 'generic.sql'); |
| 288 | + const { sql } = query({ table: 'users', id: 7 }, { exportTo: outPath }); |
| 289 | + expect(fs.readFileSync(outPath, 'utf-8')).toBe(sql); |
| 290 | + }); |
| 291 | + }); |
| 292 | + |
243 | 293 | describe('custom schema types', () => { |
244 | 294 | it('accepts a custom type descriptor', () => { |
245 | 295 | const prodTable = { |
|
0 commit comments