Created
April 9, 2018 15:35
-
-
Save jordanell/a1f561c9e2583c337972df739b788ff8 to your computer and use it in GitHub Desktop.
Adding TSVectors and indexes to PostgreSQL tables using Sequelize CLI.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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