Reputation: 107
I'm creating a project in node.js and one of my pages will show a list of all the tables in the database. I would like to know if Sequelize has a function like "Show tables".
Thanks!
Upvotes: 8
Views: 18586
Reputation: 3740
Actually there is a "DB-agnostic" call for doing what OP was asking for in v6
. On the queryInterface
object use showAllTables
method. That promise will be resolved to an array of strings (tablenames). For some reason this (and some other methods) are not documented on the API ref page. I'll look into that, and might update this answer again.
Example for v6
:
sequelize.getQueryInterface().showAllTables().then(function (tableNames) {
console.log(tableNames);
});
Important: In the coming (at the time of this post it's in alpha
) v7
version of sequelize, that method will be renamed on the queryInterface
to listTables
.
Example for coming v7
:
sequelize.getQueryInterface().listTables().then(function (tableNames) {
console.log(tableNames);
});
Upvotes: 0
Reputation: 99
Using MySQL and executing the SHOW Tables
query with a type of sequelize.QueryTypes.SHOWTABLES
will return an array of tables.
sequelize
.query('SHOW Tables', {
type: sequelize.QueryTypes.SHOWTABLES
})
.then(result => {
console.log(result)
})
// ['table1', 'table2']
Upvotes: 1
Reputation: 1152
Use the Sequelize showAllSchemas
method:
var sequelize = new Sequelize('mysql://localhost/mysql');
sequelize.getQueryInterface().showAllSchemas().then((tableObj) => {
console.log('// Tables in database','==========================');
console.log(tableObj);
})
.catch((err) => {
console.log('showAllSchemas ERROR',err);
})
This would be the "proper" Sequelize way to do it as opposed to .query('show tables')
Upvotes: 12
Reputation: 1991
I don't think there's an API in Sequelize, but you can always fall back to raw SQL. "Show tables" is a MySQLism, so you could just do:
var seq = new Sequelize('mysql://localhost/mysql');
seq.query('show tables').then(function(rows) {
console.log(JSON.stringify(rows));
});
Replace the console.log
with your own parsing and display logic.
Upvotes: 8