pg-format.test.ts57 lines · main
1import { describe, expect, it } from 'vitest'
2
3import { quoteLiteral } from './pg-format'
4
5describe('quoteLiteral', () => {
6 it('returns NULL for null and undefined', () => {
7 expect(quoteLiteral(null)).toBe('NULL')
8 expect(quoteLiteral(undefined)).toBe('NULL')
9 })
10
11 it('returns correct literals for booleans', () => {
12 expect(quoteLiteral(true)).toBe("'t'")
13 expect(quoteLiteral(false)).toBe("'f'")
14 })
15
16 it('returns quoted string for numbers', () => {
17 expect(quoteLiteral(123)).toBe("'123'")
18 expect(quoteLiteral(-45.67)).toBe("'-45.67'")
19 })
20
21 it('escapes single quotes and backslashes in strings', () => {
22 expect(quoteLiteral("O'Reilly")).toBe("'O''Reilly'")
23 expect(quoteLiteral('back\\slash')).toBe("E'back\\\\slash'")
24 expect(quoteLiteral("quote'and\\backslash")).toBe("E'quote''and\\\\backslash'")
25 })
26
27 it('formats Date objects as UTC strings', () => {
28 const date = new Date('2023-01-01T12:34:56Z')
29 expect(quoteLiteral(date)).toBe("'2023-01-01 12:34:56.000+00'")
30 })
31
32 it('handles Buffer objects', () => {
33 expect(quoteLiteral(Buffer.from('abc'))).toBe("E'\\\\x616263'")
34 })
35
36 it('formats arrays of primitives', () => {
37 expect(quoteLiteral([1, 2, 3])).toBe("'1','2','3'")
38 expect(quoteLiteral(['a', "b'c", 'd'])).toBe("'a','b''c','d'")
39 })
40
41 it('formats nested arrays', () => {
42 expect(
43 quoteLiteral([
44 [1, 2],
45 [3, 4],
46 ])
47 ).toBe("('1', '2'), ('3', '4')")
48 })
49
50 it('formats objects as jsonb', () => {
51 expect(quoteLiteral({ foo: 'bar', n: 1 })).toBe('\'{"foo":"bar","n":1}\'::jsonb')
52 })
53
54 it('handles empty string', () => {
55 expect(quoteLiteral('')).toBe("''")
56 })
57})