Knex Schema Inspector

3.1.0 · active · verified Sun Apr 19

Knex Schema Inspector is a utility library designed to extract detailed information about existing database schemas. It leverages an initialized Knex.js instance to query metadata from various relational databases, including PostgreSQL, MySQL, MS SQL, SQLite, and OracleDB. The current stable version is 3.1.0, with major versions released approximately annually, indicating an active development and maintenance cadence. Its key differentiator is its deep integration with Knex, allowing developers to use their existing Knex configurations to introspect database structures, retrieve table names, column details, primary keys, and foreign key relationships across a wide range of SQL dialects. It ships with TypeScript types, facilitating robust development with type safety. It does not provide migration or schema modification capabilities, focusing solely on schema introspection.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes Knex, creates a schema inspector instance, and then logs all table names, detailed information for the first table found, and all columns within that table. It includes environment variable placeholders for secure database connection and proper resource cleanup.

import Knex from 'knex';
import schemaInspector from 'knex-schema-inspector';

// Initialize Knex with your database configuration
const database = Knex({
  client: 'mysql',
  connection: {
    host: process.env.DB_HOST ?? '127.0.0.1',
    user: process.env.DB_USER ?? 'root',
    password: process.env.DB_PASSWORD ?? '',
    database: process.env.DB_NAME ?? 'myapp_test',
    charset: 'utf8',
  },
});

// Initialize the schema inspector with the Knex instance
const inspector = schemaInspector(database);

async function inspectDatabase() {
  try {
    const tables = await inspector.tables();
    console.log('Tables:', tables);

    if (tables.length > 0) {
      const firstTableInfo = await inspector.tableInfo(tables[0]);
      console.log(`Info for table '${tables[0]}':`, firstTableInfo);

      const columns = await inspector.columns(tables[0]);
      console.log(`Columns in table '${tables[0]}':`, columns);
    }
  } catch (error) {
    console.error('Error inspecting database:', error);
  } finally {
    await database.destroy(); // Always remember to destroy the Knex connection
  }
}

inspectDatabase();

view raw JSON →