Knex Schema Inspector
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
-
TypeError: inspector is not a function
cause Attempting to import `schemaInspector` as a named export or using a CommonJS `require` call on an ESM default export.fixUse the correct ESM default import syntax: `import schemaInspector from 'knex-schema-inspector';` -
Error: Knex client must be initialized with a 'client' option.
cause The Knex instance passed to `schemaInspector` was not properly configured or initialized (e.g., missing `client` in the Knex constructor options).fixEnsure your Knex instance is fully configured and connected before passing it to `schemaInspector`. Example: `const database = Knex({ client: 'pg', connection: {...} });` -
Error: knex-schema-inspector requires knex@^2.0.0. Current version is 1.x.x.
cause The project's `knex` dependency is an older version (1.x) which is incompatible with `knex-schema-inspector` v2.0.0 and later.fixUpgrade your `knex` dependency to version 2.x or newer: `npm install knex@latest` or `yarn add knex@latest`. -
Property 'default_value' is a string but expected number/boolean.
cause Since `knex-schema-inspector` v2.0.0, all `default_value` fields are returned as strings, regardless of their original database type.fixParse the `default_value` string to the desired type manually. For example, `Number(columnInfo.default_value)` or `columnInfo.default_value === 'true'`.
Warnings
- breaking Starting with v3.0.0, the underlying `tedious` driver (used for MS SQL) was updated to v15. This update introduces changes to some default behaviors in how MS SQL connections are handled and queried. Users should consult the `tedious` v15 release notes for potential impacts on existing MS SQL implementations.
- breaking Version 2.0.0 introduced a breaking change requiring `knex@2` or newer as a peer dependency. Older versions of Knex will not be compatible.
- breaking Since v2.0.0, default values for columns are consistently returned as strings across all supported databases, even if they represent numeric or boolean types in the database.
- gotcha In MySQL, the concepts of 'schema' and 'database' are often used interchangeably. The `schema` parameter in methods like `withSchema()` is not officially supported by Knex Schema Inspector for the MySQL dialect, meaning it might not behave as expected or might be ignored.
- gotcha MS SQL does not inherently support comments for tables or columns in the same way other databases like Postgres do. Therefore, `comment` fields in `Table` or `Column` info objects will typically be `null` or undefined when inspecting an MS SQL database.
Install
-
npm install knex-schema-inspector -
yarn add knex-schema-inspector -
pnpm add knex-schema-inspector
Imports
- schemaInspector
import { schemaInspector } from 'knex-schema-inspector'; const schemaInspector = require('knex-schema-inspector');import schemaInspector from 'knex-schema-inspector';
- Knex
import { Knex } from 'knex';import Knex from 'knex';
- Column
import { Column } from 'knex-schema-inspector';import type { Column } from 'knex-schema-inspector';
Quickstart
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();