pg-format.test.ts 1.6 KB

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