search.migration.ts 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { MigrationInterface, QueryRunner } from "typeorm";
  2. export class SearchMigration1617981663819 implements MigrationInterface {
  3. name = 'searchMigration1617981663819'
  4. public async up(queryRunner: QueryRunner): Promise<void> {
  5. // TODO: escape
  6. await queryRunner.query(`
  7. ALTER TABLE channel
  8. ADD COLUMN search_tsv tsvector
  9. GENERATED ALWAYS AS (
  10. setweight(to_tsvector('english', coalesce("title", '')), 'A')
  11. )
  12. STORED;
  13. `);
  14. await queryRunner.query(`
  15. ALTER TABLE channel
  16. ADD COLUMN search_doc text
  17. GENERATED ALWAYS AS (
  18. coalesce("title", '')
  19. )
  20. STORED;
  21. `);
  22. await queryRunner.query(`CREATE INDEX search_channel_idx ON channel USING GIN (search_tsv)`);
  23. await queryRunner.query(`CREATE INDEX channel_id_idx ON channel (('channel' || '_' || id))`);
  24. await queryRunner.query(`
  25. ALTER TABLE video
  26. ADD COLUMN search_tsv tsvector
  27. GENERATED ALWAYS AS (
  28. setweight(to_tsvector('english', coalesce("title", '')), 'A')
  29. )
  30. STORED;
  31. `);
  32. await queryRunner.query(`
  33. ALTER TABLE video
  34. ADD COLUMN search_doc text
  35. GENERATED ALWAYS AS (
  36. coalesce("title", '')
  37. )
  38. STORED;
  39. `);
  40. await queryRunner.query(`CREATE INDEX search_video_idx ON video USING GIN (search_tsv)`);
  41. await queryRunner.query(`CREATE INDEX video_id_idx ON video (('video' || '_' || id))`);
  42. await queryRunner.query(`
  43. CREATE VIEW search_view AS
  44. SELECT
  45. text 'channel' AS origin_table, 'channel' || '_' || id AS unique_id, id, search_tsv AS tsv, search_doc AS document
  46. FROM
  47. channel
  48. UNION ALL
  49. SELECT
  50. text 'video' AS origin_table, 'video' || '_' || id AS unique_id, id, search_tsv AS tsv, search_doc AS document
  51. FROM
  52. video
  53. `);
  54. }
  55. public async down(queryRunner: QueryRunner): Promise<void> {
  56. await queryRunner.query(`DROP VIEW search_view`);
  57. await queryRunner.query(`DROP INDEX search_channel_idx`);
  58. await queryRunner.query(`DROP INDEX channel_id_idx`);
  59. await queryRunner.query(`ALTER TABLE channel DROP COLUMN search_tsv`);
  60. await queryRunner.query(`ALTER TABLE channel DROP COLUMN search_doc`);
  61. await queryRunner.query(`DROP INDEX search_video_idx`);
  62. await queryRunner.query(`DROP INDEX video_id_idx`);
  63. await queryRunner.query(`ALTER TABLE video DROP COLUMN search_tsv`);
  64. await queryRunner.query(`ALTER TABLE video DROP COLUMN search_doc`);
  65. }
  66. }