Version: 0.14.x
Custom logic with Plugins
It's possible to write custom queries to be executed during migrations using Plugins.
Currently a plugin can only declare tap on the Writer system, with the write
and tap
methods:
The arguments are:
operation: string
, can be one of the following:table.create
table.rename
table.comment.set
table.drop
table.index.create
table.index.drop
table.primary.set
table.primary.drop
table.unique.create
table.unique.drop
table.foreign.create
table.foreign.drop
column.create
column.rename
column.alter
column.drop
type: 'before' | 'after'
callback: function
which get those parameters:operation
: the operation object (see Operation.ts)transaction
: the Knex SQL transaction
Then, instantiate the plugin in the plugins
option array of the migrateDB
method.
For example, let's say we have the following schema:
Now we want to migrate the user
table from two columns fname
and lname
into one:
Here is the example code to achieve this:
The above code does the following:
- Remove the
fname
field from the schema. - Rename
lname
tofullname
in the schema. - Annotate the
fullname
field to indicate it's the new name oflname
. - We declare a plugin that tap into the
column.drop
write operation. - In this hook, we read the users and update each one of them to merge the two columns into
lname
before thefname
column is dropped.