fts5-fallback.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
  2. import * as fs from 'fs';
  3. import * as os from 'os';
  4. import * as path from 'path';
  5. import { DatabaseConnection } from '../src/db';
  6. import { QueryBuilder } from '../src/db/queries';
  7. import { Node } from '../src/types';
  8. // Use real SQLite for every operation except the unsupported-module error.
  9. // This must exercise fallback even when the test runner's Node has FTS5.
  10. const { DatabaseSync } = require('node:sqlite');
  11. function simulateMissingFts5(): () => number {
  12. const exec = DatabaseSync.prototype.exec;
  13. let attempts = 0;
  14. vi.spyOn(DatabaseSync.prototype, 'exec').mockImplementation(function (this: unknown, sql: string) {
  15. if (/CREATE VIRTUAL TABLE\b[^;]*\bUSING fts5\s*\(/i.test(sql)) {
  16. attempts++;
  17. throw new Error('no such module: fts5');
  18. }
  19. return exec.call(this, sql);
  20. });
  21. return () => attempts;
  22. }
  23. function makeNode(name: string, docstring?: string): Node {
  24. return {
  25. id: name,
  26. kind: 'function',
  27. name,
  28. qualifiedName: name,
  29. filePath: 'src/users.ts',
  30. language: 'typescript',
  31. startLine: 1,
  32. endLine: 1,
  33. startColumn: 0,
  34. endColumn: 0,
  35. docstring,
  36. updatedAt: Date.now(),
  37. };
  38. }
  39. describe('FTS5 fallback (#1532)', () => {
  40. let dir: string;
  41. let connections: DatabaseConnection[];
  42. beforeEach(() => {
  43. dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-fts5-fallback-'));
  44. connections = [];
  45. });
  46. afterEach(() => {
  47. vi.restoreAllMocks();
  48. for (const connection of connections) connection.close();
  49. fs.rmSync(dir, { recursive: true, force: true });
  50. });
  51. function initialize(filename = 'test.db'): DatabaseConnection {
  52. const connection = DatabaseConnection.initialize(path.join(dir, filename));
  53. connections.push(connection);
  54. return connection;
  55. }
  56. function reopen(connection: DatabaseConnection): DatabaseConnection {
  57. connection.close();
  58. const reopened = DatabaseConnection.open(path.join(dir, 'test.db'));
  59. connections.push(reopened);
  60. return reopened;
  61. }
  62. it.each(['initialization', 'reopening'])('uses LIKE and fuzzy search after %s without FTS5', (state) => {
  63. const attempts = simulateMissingFts5();
  64. const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
  65. let connection = initialize();
  66. expect(attempts()).toBe(1);
  67. expect(connection.fts5Available).toBe(false);
  68. expect(warn).toHaveBeenCalledOnce();
  69. expect(warn).toHaveBeenCalledWith(expect.stringContaining('no such module: fts5'));
  70. expect(warn).toHaveBeenCalledWith(expect.stringContaining('LIKE + fuzzy matching'));
  71. if (state === 'reopening') connection = reopen(connection);
  72. expect(connection.fts5Available).toBe(false);
  73. const db = connection.getDb();
  74. expect(db.prepare("SELECT name FROM sqlite_master WHERE name = 'nodes_fts' OR name IN ('nodes_ai', 'nodes_ad', 'nodes_au')").all()).toEqual([]);
  75. const exec = vi.spyOn(db, 'exec');
  76. connection.beginBulkNodeLoad();
  77. connection.endBulkNodeLoad();
  78. expect(exec).not.toHaveBeenCalled();
  79. const queries = new QueryBuilder(db);
  80. queries.insertNodes([makeNode('getUser'), makeNode('getUserProfile')]);
  81. const prepare = vi.spyOn(db, 'prepare');
  82. expect(queries.searchNodes('User').map(result => result.node.name)).toEqual(expect.arrayContaining(['getUser', 'getUserProfile']));
  83. expect(queries.searchNodes('getUssr').map(result => result.node.name)).toEqual(['getUser']);
  84. // A failed MATCH query is already caught by searchNodesFTS; pin that the
  85. // unavailable path skips the FTS query entirely, rather than retrying it.
  86. expect(prepare.mock.calls.some(([sql]) => /\bnodes_fts\b/.test(sql))).toBe(false);
  87. queries.setMetadata('project_name', 'fts5-fallback');
  88. expect(queries.getMetadata('project_name')).toBe('fts5-fallback');
  89. });
  90. it('keeps every non-FTS table and index when FTS5 creation fails', () => {
  91. const control = initialize('control.db');
  92. const nonFtsSchema = (connection: DatabaseConnection) => connection.getDb().prepare(`
  93. SELECT type, name, sql FROM sqlite_master
  94. WHERE name NOT LIKE 'nodes_fts%'
  95. AND name NOT IN ('nodes_ai', 'nodes_ad', 'nodes_au')
  96. ORDER BY type, name
  97. `).all();
  98. const expected = nonFtsSchema(control);
  99. simulateMissingFts5();
  100. vi.spyOn(console, 'warn').mockImplementation(() => {});
  101. const fallback = initialize();
  102. expect(fallback.fts5Available).toBe(false);
  103. expect(nonFtsSchema(fallback)).toEqual(expected);
  104. });
  105. it.each(['initialization', 'reopening'])('uses real FTS5 after %s', (state) => {
  106. const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
  107. let connection = initialize();
  108. expect(connection.fts5Available).toBe(true);
  109. new QueryBuilder(connection.getDb()).insertNode(makeNode('loadRecord', 'quasar nebula'));
  110. if (state === 'reopening') connection = reopen(connection);
  111. expect(connection.fts5Available).toBe(true);
  112. const queries = new QueryBuilder(connection.getDb());
  113. // Only the docstring contains this token: LIKE/fuzzy name search cannot
  114. // make this assertion pass if the FTS path is accidentally disabled.
  115. expect(queries.searchNodes('nebula').map(result => result.node.name)).toEqual(['loadRecord']);
  116. expect(warn).not.toHaveBeenCalled();
  117. });
  118. it('rebuilds real FTS5 after a bulk node load', () => {
  119. const connection = initialize();
  120. const queries = new QueryBuilder(connection.getDb());
  121. connection.beginBulkNodeLoad();
  122. queries.insertNode(makeNode('loadRecord', 'quasar nebula'));
  123. expect(queries.searchNodes('nebula')).toEqual([]);
  124. connection.endBulkNodeLoad();
  125. expect(queries.searchNodes('nebula').map(result => result.node.name)).toEqual(['loadRecord']);
  126. queries.insertNode(makeNode('saveRecord', 'pulsar supernova'));
  127. expect(queries.searchNodes('supernova').map(result => result.node.name)).toEqual(['saveRecord']);
  128. });
  129. it('repairs an interrupted real FTS5 bulk load on open', () => {
  130. let connection = initialize();
  131. connection.beginBulkNodeLoad();
  132. new QueryBuilder(connection.getDb()).insertNode(makeNode('loadRecord', 'quasar nebula'));
  133. connection = reopen(connection);
  134. expect(connection.fts5Available).toBe(true);
  135. const queries = new QueryBuilder(connection.getDb());
  136. expect(queries.searchNodes('nebula').map(result => result.node.name)).toEqual(['loadRecord']);
  137. queries.insertNode(makeNode('saveRecord', 'pulsar supernova'));
  138. expect(queries.searchNodes('supernova').map(result => result.node.name)).toEqual(['saveRecord']);
  139. });
  140. });