@directus/schema
Utility for extracting information about the database schema
Usage
The package is initialized by passing it an instance of Knex:
import knex from 'knex';
import schema from '@directus/schema';
const database = knex({
client: 'mysql',
connection: {
host: '127.0.0.1',
user: 'your_database_user',
password: 'your_database_password',
database: 'myapp_test',
charset: 'utf8',
},
});
const inspector = schema(database);
export default inspector;
Examples
import inspector from './inspector';
async function logTables() {
const tables = await inspector.tables();
console.log(tables);
}
API
Note: MySQL doesn't support the schema
parameter, as schema and database are ambiguous in MySQL.
Note 2: Some database types might return slightly more information than others. See the type files for a specific
overview what to expect from driver to driver.
Note 3: MSSQL doesn't support comment for either tables or columns
Tables
tables(): Promise<string[]>
Retrieve all tables in the current database.
await inspector.tables();
tableInfo(table?: string): Promise<Table | Table[]>
Retrieve the table info for the given table, or all tables if no table is specified
await inspector.tableInfo('articles');
await inspector.tableInfo();
hasTable(table: string): Promise<boolean>
Check if a table exists in the current database.
await inspector.hasTable('articles');
Columns
columns(table?: string): Promise<{ table: string, column: string }[]>
Retrieve all columns in a given table, or all columns if no table is specified
await inspector.columns();
await inspector.columns('articles');
columnInfo(table?: string, column?: string): Promise<Column[] | Column>
Retrieve all columns from a given table. Returns all columns if table
parameter is undefined.
await inspector.columnInfo('articles');
await inspector.columnInfo('articles', 'id');
primary(table: string): Promise<string>
Retrieve the primary key column for a given table
await inspector.primary('articles');
Misc.
withSchema(schema: string): void
Not supported in MySQL
Set the schema to use. Note: this is set on the inspector instance and only has to be done once:
inspector.withSchema('my-schema');
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
Tests
First start docker containers:
$ docker compose up
Then run tests:
$ npm test
Standard mocha filter (grep) can be used:
$ npm test -- -g '.tableInfo'