SlowHusky
SlowHusky

Reputation: 107

Make Sequelize show tables

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

Answers (4)

p1100i
p1100i

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

g_let
g_let

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

user2871305
user2871305

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

user2926055
user2926055

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

Related Questions