Usage
This MySQL simulator offers a super easy API that, at the highest level, looks
like:
import simulate from '@simplehealth/mysql-simulator';
const db = simulate('./path/to/migrations');
The resulting DB instance is an in-memory representation of the final DB state
after applying all the SQL migrations in order, exactly as it would be in
MySQL. The DB object can now conveniently be introspected, for example:
for (const table of db.getTables()) {
console.log(`- ${table.name}`);
}
const users = db.getTable('users');
console.log(users.getColumn('email').getTypeInfo().baseType);
console.log(users.getColumn('email').getTypeInfo().nullable);
console.log(users.getColumn('email').toString());
console.log(users.toString());
These objects are fully Flow-typed.
Usage from the command line
There's a command line interface that might help you if you simply want to
apply some migrations and output the resulting table definitions:
$ bin/mysql-simulate <path>
This assumes a directory of *.sql
files containing SQL statements, which are
numbered sequentially, for example: 0001-create-table.sql
,
0002-change-field.sql
, etc.
To run it on all *.sql
migration files in a directory:
$ bin/mysql-simulate path/to/migrations
This will simulate running the migrations found in that directory sequentially.
At the end, the DB's state is outputted as a single SQL table definition dump.
For developers
Regenerating the parser
After changing the grammar file (src/parser/mysql.pegjs
), you need to
recompile the parser:
$ yarn build:parser
Running the test suite
The test suite for this project is a little bit different from "normal"
JavaScript project tests. It's invoked by
$ yarn test
And will basically do the following for all test files found in tests/*.sql
:
- Run test files against a real, running, MySQL database. Output to
tests/real/*.sql
. - Run test files against the simulator. Output to
tests/simulated/*.sql
. - Diff the results. No diff means test suite passes.
This setup offers the level of confidence that the simulator is actually
working as expected, and at the same time makes it really easy to add specific
test cases later on: simply add a new *.sql
file!