Skip to content

Instantly share code, notes, and snippets.

@jordanell
Created April 9, 2018 15:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanell/a1f561c9e2583c337972df739b788ff8 to your computer and use it in GitHub Desktop.
Save jordanell/a1f561c9e2583c337972df739b788ff8 to your computer and use it in GitHub Desktop.
Adding TSVectors and indexes to PostgreSQL tables using Sequelize CLI.
const vectorName = '_search';
const searchObjects = {
authors: ['name', 'biography'],
posts: ['name', 'summary'],
};
module.exports = {
up: (queryInterface) => (
queryInterface.sequelize.transaction((t) =>
Promise.all(Object.keys(searchObjects).map((table) =>
queryInterface.sequelize.query(`
ALTER TABLE ${table} ADD COLUMN ${vectorName} TSVECTOR;
`, { transaction: t })
.then(() =>
queryInterface.sequelize.query(`
UPDATE ${table} SET ${vectorName} = to_tsvector('english', ${searchObjects[table].join(" || ' ' || ")});
`, { transaction: t })
).then(() =>
queryInterface.sequelize.query(`
CREATE INDEX ${table}_search ON ${table} USING gin(${vectorName});
`, { transaction: t })
).then(() =>
queryInterface.sequelize.query(`
CREATE TRIGGER ${table}_vector_update
BEFORE INSERT OR UPDATE ON ${table}
FOR EACH ROW EXECUTE PROCEDURE tsvector_update_trigger(${vectorName}, 'pg_catalog.english', ${searchObjects[table].join(', ')});
`, { transaction: t })
)
.error(console.log)
))
)
),
down: (queryInterface) => (
queryInterface.sequelize.transaction((t) =>
Promise.all(Object.keys(searchObjects).map((table) =>
queryInterface.sequelize.query(`
DROP TRIGGER ${table}_vector_update ON ${table};
`, { transaction: t })
.then(() =>
queryInterface.sequelize.query(`
DROP INDEX ${table}_search;
`, { transaction: t })
).then(() =>
queryInterface.sequelize.query(`
ALTER TABLE ${table} DROP COLUMN ${vectorName};
`, { transaction: t })
)
))
)
),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment