迁移
¥Migrations
迁移允许你定义架构更改集,因此升级数据库变得轻而易举。
¥Migrations allow for you to define sets of schema changes so upgrading a database is a breeze.
迁移命令行接口
¥Migration CLI
迁移 CLI 与 knex 安装打包在一起,并由 node-liftoff 模块驱动。要全局安装,请运行:
¥The migration CLI is bundled with the knex install, and is driven by the node-liftoff module. To install globally, run:
$ npm install knex -g
迁移 CLI 接受以下常规命令行选项。你可以使用 --help
查看每个命令的帮助文本和附加选项。例如。knex migrate:latest --help
。
¥The migration CLI accepts the following general command-line options. You can view help text and additional options for each command using --help
. E.g. knex migrate:latest --help
.
--debug
:运行并调试¥
--debug
: Run with debugging--knexfile [path]
:指定 knex 文件路径¥
--knexfile [path]
: Specify the knexfile path--knexpath [path]
:指定 knex 实例的路径¥
--knexpath [path]
: Specify the path to the knex instance--cwd [path]
:指定工作目录¥
--cwd [path]
: Specify the working directory--client [name]
:设置数据库客户端¥
--client [name]
: Set the DB client--connection [address]
:设置数据库连接¥
--connection [address]
: Set the DB connection--migrations-table-name
:设置迁移表名¥
--migrations-table-name
: Set the migration table name--migrations-directory
:设置迁移目录¥
--migrations-directory
: Set the migrations directory--env
:环境,默认:process.
env.NODE_ENV || development ¥
--env
: environment, default:process.
env.NODE_ENV || development --esm
:实现 ESM 模块互操作性--help
:显示特定命令的帮助文本并退出。¥
--help
: Display help text for a particular command and exit.
迁移使用 knexfile,它指定模块的各种配置设置。要创建新的 knex 文件,请运行以下命令:
¥Migrations use a knexfile, which specify various configuration settings for the module. To create a new knexfile, run the following:
$ knex init
# or for .ts
$ knex init -x ts
将创建一个示例 knexfile.js - 该文件包含我们的各种数据库配置。一旦有了 knexfile.js,你就可以使用迁移工具创建迁移文件到指定目录(默认迁移)。可以通过运行以下命令来创建新的迁移文件:
¥will create a sample knexfile.js - the file which contains our various database configurations. Once you have a knexfile.js, you can use the migration tool to create migration files to the specified directory (default migrations). Creating new migration files can be achieved by running:
$ knex migrate:make migration_name
# or for .ts
$ knex migrate:make migration_name -x ts
你还可以使用特定的存根文件创建迁移,这用作迁移模板以加快常见迁移操作的开发
¥you can also create your migration using a specific stub file, this serves as a migration template to speed up development for common migration operations
如果未传递 --stub 选项,CLI 将使用所选扩展的 knex 默认存根或 config.stub 文件
¥if the --stub option is not passed, the CLI will use either the knex default stub for the chosen extension, or the config.stub file
$ knex migrate:make --stub
# or
$ knex migrate:make --stub
如果提供了存根路径,它必须相对于 knexfile.[js、ts 等] 位置
¥if a stub path is provided, it must be relative to the knexfile.[js, ts, etc] location
如果使用 a,则通过文件名选择存根。CLI 将在 config.migrations.directory 文件夹中查找此文件。如果 config.migrations.directory 未定义,此操作将失败
¥if a is used, the stub is selected by its file name. The CLI will look for this file in the config.migrations.directory folder. If the config.migrations.directory is not defined, this operation will fail
完成迁移的编写后,你可以通过运行以下命令来更新与 NODE_ENV
匹配的数据库:
¥Once you have finished writing the migrations, you can update the database matching your NODE_ENV
by running:
$ knex migrate:latest
你还可以传递 --env
标志或设置 NODE_ENV
来选择替代环境:
¥You can also pass the --env
flag or set NODE_ENV
to select an alternative environment:
$ knex migrate:latest --env production
# or
$ NODE_ENV=production knex migrate:latest
回滚最后一批迁移:
¥To rollback the last batch of migrations:
$ knex migrate:rollback
要回滚所有已完成的迁移:
¥To rollback all the completed migrations:
$ knex migrate:rollback --all
运行尚未运行的下一个迁移
¥To run the next migration that has not yet been run
$ knex migrate:up
运行尚未运行的指定迁移
¥To run the specified migration that has not yet been run
$ knex migrate:up 001_migration_name.js
撤消上次运行的迁移
¥To undo the last migration that was run
$ knex migrate:down
撤消已运行的指定迁移
¥To undo the specified migration that was run
$ knex migrate:down 001_migration_name.js
列出已完成和待处理的迁移:
¥To list both completed and pending migrations:
$ knex migrate:list
种子文件
¥Seed files
种子文件允许你使用独立于迁移文件的测试或种子数据填充数据库。
¥Seed files allow you to populate your database with test or seed data independent of your migration files.
种子 CLI
¥Seed CLI
要创建种子文件,请运行:
¥To create a seed file, run:
$ knex seed:make seed_name
种子文件是在 knexfile.js 中为当前环境指定的目录中创建的。示例种子配置如下所示:
¥Seed files are created in the directory specified in your knexfile.js for the current environment. A sample seed configuration looks like:
module.exports = {
// ...
development: {
client: {/* ... */},
connection: {/* ... */},
seeds: {
directory: './seeds/dev'
}
}
// ...
}
如果未定义 seeds.directory
,则在 ./seeds
中创建文件。请注意,种子目录需要是相对路径。不支持绝对路径(也不是好的做法)。
¥If no seeds.directory
is defined, files are created in ./seeds
. Note that the seed directory needs to be a relative path. Absolute paths are not supported (nor is it good practice).
要运行种子文件,请执行:
¥To run seed files, execute:
$ knex seed:run
种子文件按字母顺序执行。与迁移不同,运行命令时将执行每个种子文件。你应该设计种子文件,以便在插入数据之前根据需要重置表。
¥Seed files are executed in alphabetical order. Unlike migrations, every seed file will be executed when you run the command. You should design your seed files to reset tables as needed before inserting data.
要运行特定的种子文件,请执行:
¥To run specific seed files, execute:
$ knex seed:run --specific=seed-filename.js --specific=another-seed-filename.js
knexfile.js
knexfile.js 通常包含数据库的所有配置。它可以选择为不同的环境提供不同的配置。你可以将 --knexfile
选项传递给任何命令行语句以指定 knexfile 的备用路径。
¥A knexfile.js generally contains all of the configuration for your database. It can optionally provide different configuration for different environments. You may pass a --knexfile
option to any of the command line statements to specify an alternate path to your knexfile.
基本配置
¥Basic configuration
module.exports = {
client: 'pg',
connection: process.env.DATABASE_URL || {
user: 'me',
database: 'my_app'
}
};
你还可以使用异步函数来获取配置的连接详细信息。当你需要从保险库等安全位置获取凭据时,这非常有用。
¥You can also use an async function to get connection details for your configuration. This is useful when you need to fetch credentials from a secure location like vault.
const getPassword = async () => {
// TODO: implement me
return 'my_pass'
}
module.exports = {
client: 'pg',
connection: async () => {
const password = await getPassword()
return { user: 'me', password }
},
migrations: {}
};
环境配置
¥Environment configuration
module.exports = {
development: {
client: 'pg',
connection: { user: 'me', database: 'my_app' }
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL
}
};
自定义迁移
¥Custom migration
你可以提供自定义迁移存根来代替默认选项。
¥You may provide a custom migration stub to be used in place of the default option.
module.exports = {
client: 'pg',
migrations: {
stub: 'migration.stub'
}
};
自定义迁移名称
¥Custom migration name
你可以提供自定义迁移名称来代替默认选项。
¥You may provide a custom migration name to be used in place of the default option.
module.exports = {
client: 'pg',
migrations: {
getNewMigrationName: (name) => {
return `${+new Date()}-${name}.js`;
}
}
};
生成的迁移扩展
¥Generated migration extension
你可以控制生成的迁移的扩展。
¥You can control extension of generated migrations.
module.exports = {
client: 'pg',
migrations: {
extension: 'ts'
}
};
Knexfile 用其他语言
¥Knexfile in other languages
Knex 使用 升空 来支持用其他编译为 js 的语言编写的 knexfile。
¥Knex uses Liftoff to support knexfile written in other compile-to-js languages.
根据语言的不同,这可能需要你安装其他依赖。每种支持的语言的完整依赖列表可以在 此处。
¥Depending on the language, this may require you to install additional dependencies. The complete list of dependencies for each supported language can be found here.
最常见的情况是 typescript(建议使用 typescript 和 ts-node 包)和 Coffeescript(需要 coffeescript 依赖)。
¥Most common cases are typescript (for which typescript and ts-node packages are recommended), and coffeescript (for which coffeescript dependency is required).
如果你没有明确指定扩展名,生成的迁移/种子文件的扩展名将从 knexfile 扩展名推断出来
¥If you don't specify the extension explicitly, the extension of generated migrations/seed files will be inferred from the knexfile extension
迁移 API
¥Migration API
knex.migrate
是 knex 迁移 cli 使用的类。
¥knex.migrate
is the class utilized by the knex migrations cli.
每个方法都采用一个可选的 config
对象,该对象可以指定以下属性:
¥Each method takes an optional config
object, which may specify the following properties:
directory
:包含迁移文件的目录的相对路径。可以是路径数组(默认./migrations
)¥
directory
: a relative path to the directory containing the migration files. Can be an array of paths (default./migrations
)extension
:用于生成的迁移文件的文件扩展名(默认js
)¥
extension
: the file extension used for the generated migration files (defaultjs
)tableName
:用于存储迁移状态的表名(默认knex_migrations
)¥
tableName
: the table name used for storing the migration state (defaultknex_migrations
)schemaName
:用于存储具有迁移状态的表的模式名称(可选参数,仅适用于在单个数据库中支持多个模式的数据库,例如 PostgreSQL)¥
schemaName
: the schema name used for storing the table with migration state (optional parameter, only works on DBs that support multiple schemas in a single DB, such as PostgreSQL)disableTransactions
:不要在事务内运行迁移(默认false
)¥
disableTransactions
: don't run migrations inside transactions (defaultfalse
)disableMigrationsListValidation
:不验证所有已执行的迁移是否仍然存在于迁移目录中(默认false
)¥
disableMigrationsListValidation
: do not validate that all the already executed migrations are still present in migration directories (defaultfalse
)sortDirsSeparately
:如果 true 且指定了多个目录,则将在下一个文件夹中执行迁移之前执行来自单个目录的所有迁移(默认false
)¥
sortDirsSeparately
: if true and multiple directories are specified, all migrations from a single directory will be executed before executing migrations in the next folder (defaultfalse
)loadExtensions
:knex 将视为迁移的文件扩展名数组。例如,如果你在同一文件夹中将 typescript 转换为 javascript,则你只想执行 javascript 迁移。在这种情况下,将loadExtensions
设置为['.js']
(注意点!)(默认['.co', '.coffee', '.eg', '.iced', '.js', '.litcoffee', '.ls', '.ts']
)¥
loadExtensions
: array of file extensions which knex will treat as migrations. For example, if you have typescript transpiled into javascript in the same folder, you want to execute only javascript migrations. In this case, setloadExtensions
to['.js']
(Notice the dot!) (default['.co', '.coffee', '.eg', '.iced', '.js', '.litcoffee', '.ls', '.ts']
)migrationSource
:指定自定义迁移源,请参阅 自定义迁移源 了解更多信息(默认文件系统)¥
migrationSource
: specify a custom migration source, see Custom Migration Source for more info (default filesystem)
迁移中的事务
¥Transactions in migrations
默认情况下,每个迁移都在事务内运行。无论何时需要,都可以通过通用迁移配置选项 config.disableTransactions
或每次迁移(通过从迁移文件中公开布尔属性 config.transaction
)禁用所有迁移的事务:
¥By default, each migration is run inside a transaction. Whenever needed, one can disable transactions for all migrations via the common migration config option config.disableTransactions
or per-migration, via exposing a boolean property config.transaction
from a migration file:
exports.up = function(knex) {
return knex.schema
.createTable('users', function (table) {
table.increments('id');
table.string('first_name', 255).notNullable();
table.string('last_name', 255).notNullable();
})
.createTable('products', function (table) {
table.increments('id');
table.decimal('price').notNullable();
table.string('name', 1000).notNullable();
});
};
exports.down = function(knex) {
return knex.schema
.dropTable("products")
.dropTable("users");
};
exports.config = { transaction: false };
如果通用配置具有 disableTransactions: true
,则可以使用相同的配置属性来启用事务每次迁移。
¥The same config property can be used for enabling transaction per-migration in case the common configuration has disableTransactions: true
.
make
knex.migrate.make(name, [config])
创建一个新的迁移,并添加迁移的名称。
¥Creates a new migration, with the name of the migration being added.
latest
knex.migrate.latest([config])
运行所有尚未运行的迁移。
¥Runs all migrations that have not yet been run.
如果你需要在所有迁移完成后才运行某些操作,你可以执行以下操作:
¥If you need to run something only after all migrations have finished their execution, you can do something like this:
knex.migrate.latest()
.then(function() {
return knex.seed.run();
})
.then(function() {
// migrations are finished
});
rollback
knex.migrate.rollback([config], [all])
回滚最新的迁移组。如果 all
参数为 true,则将回滚所有已应用的迁移,而不仅仅是最后一批。该参数的默认值为 false
。
¥Rolls back the latest migration group. If the all
parameter is truthy, all applied migrations will be rolled back instead of just the last batch. The default value for this parameter is false
.
up
knex.migrate.up([config])
运行指定的(通过 config.name
参数)或下一个尚未运行的时间顺序迁移。
¥Runs the specified (by config.name
parameter) or the next chronological migration that has not yet be run.
down
knex.migrate.down([config])
将撤消指定的(通过 config.name
参数)或上次运行的迁移。
¥Will undo the specified (by config.name
parameter) or the last migration that was run.
currentVersion
knex.migrate.currentVersion([config])
作为 promise,检索并返回当前的迁移版本。如果尚未运行任何迁移,则返回 "none" 作为 currentVersion 的值。
¥Retrieves and returns the current migration version, as a promise. If there aren't any migrations run yet, returns "none" as the value for the currentVersion.
list
knex.migrate.list([config])
将返回已完成和待处理迁移的列表
¥Will return list of completed and pending migrations
unlock
knex.migrate.forceFreeMigrationsLock([config])
强制解锁迁移锁表,并确保其中只有一行。
¥Forcibly unlocks the migrations lock table, and ensures that there is only one row in it.
关于锁的注意事项
¥Notes about locks
锁系统可以防止多个进程同时运行相同的迁移批次。当一批迁移即将运行时,迁移系统首先尝试使用 SELECT ... FOR UPDATE
语句获取锁(防止竞争条件发生)。如果它可以获得锁定,则迁移批处理将运行。如果不能,它将等待直到锁被释放。
¥A lock system is there to prevent multiple processes from running the same migration batch in the same time. When a batch of migrations is about to be run, the migration system first tries to get a lock using a SELECT ... FOR UPDATE
statement (preventing race conditions from happening). If it can get a lock, the migration batch will run. If it can't, it will wait until the lock is released.
请注意,如果你的进程不幸崩溃,则必须使用 knex migrate:unlock
手动删除锁定才能让迁移再次运行。
¥Please note that if your process unfortunately crashes, the lock will have to be manually removed with knex migrate:unlock
in order to let migrations run again.
锁保存在名为“tableName
_lock”的表中;它有一个名为 is_locked
的列,knex migrate:unlock
将其设置为 0
以释放锁。锁表中的 index
列的存在是为了与某些需要主键的数据库集群兼容,但在其他情况下不会被使用。该表中必须只有一行,否则运行迁移时会抛出错误:"迁移表已被锁定"。运行 knex migrate:unlock
以确保表中只有一行。
¥The locks are saved in a table called "tableName
_lock"; it has a column called is_locked
that knex migrate:unlock
sets to 0
in order to release the lock. The index
column in the lock table exists for compatibility with some database clusters that require a primary key, but is otherwise unused. There must be only one row in this table, or an error will be thrown when running migrations: "Migration table is already locked". Run knex migrate:unlock
to ensure that there is only one row in the table.
自定义迁移源
¥Custom migration sources
Knex 支持自定义迁移源,使你可以完全控制迁移的来源。当与 webpack/browserify 和其他场景打包时,这对于自定义文件夹结构非常有用。
¥Knex supports custom migration sources, allowing you full control of where your migrations come from. This can be useful for custom folder structures, when bundling with webpack/browserify and other scenarios.
// Create a custom migration source class
class MyMigrationSource {
// Must return a Promise containing a list of migrations.
// Migrations can be whatever you want,
// they will be passed as arguments to getMigrationName
// and getMigration
getMigrations() {
// In this example we are just returning migration names
return Promise.resolve(['migration1'])
}
getMigrationName(migration) {
return migration;
}
getMigration(migration) {
switch(migration) {
case 'migration1':
return {
up(knex) { /* ... */ },
down(knex) { /* ... */ },
}
}
}
}
// pass an instance of your migration source as knex config
knex.migrate.latest({
migrationSource: new MyMigrationSource()
})
Webpack 迁移源码示例
¥Webpack migration source example
有关如何创建迁移源(其中迁移包含在 Webpack 打包包中)的示例。
¥An example of how to create a migration source where migrations are included in a webpack bundle.
const path = require('path')
class WebpackMigrationSource {
constructor(migrationContext) {
this.migrationContext = migrationContext
}
getMigrations() {
return Promise.resolve(
this.migrationContext.keys().sort()
)
}
getMigrationName(migration) {
return path.parse(migration).base
}
getMigration(migration) {
return this.migrationContext(migration)
}
}
// pass an instance of your migration source as knex config
knex.migrate.latest({
migrationSource: new WebpackMigrationSource(
require.context('./migrations', false, /.js$/)
)
})
// with webpack >=5, require.context will add
// both the relative and absolute paths to the context
// to avoid duplicate migration errors, you'll need
// to filter out one or the other this example filters
// out absolute paths, leaving only the relative
// ones(./migrations/*.js):
knex.migrate.latest({
migrationSource: new WebpackMigrationSource(
require.context('./migrations', false, /^\.\/.*\.js$/)
)
})
ECMAScript 模块 (ESM) 互操作性
¥ECMAScript modules (ESM) Interoperability
ECMAScript 模块支持 knex CLI 的配置、迁移和种子,由 --esm
标志启用,ECMAScript 互操作性由 'esm' 模块提供。你可以找到 此处 更多有关 'esm' 超能力的信息。
¥ECMAScript Module support for knex CLI's configuration, migration and seeds\ enabled by the --esm
flag, ECMAScript Interoperability is provided by the 'esm' module.\ You can find here more information about 'esm' superpowers.
Node 'mjs' 文件由 NodeJS 自己的导入机制处理,不需要使用 '--esm' 标志。但在某些情况下,对于 Node v10,你可能仍然需要它。你可以找到有关 NodeJS ECMAScript 模块 此处 的详细信息
¥Node 'mjs' files are handled by NodeJS own import mechanics\ and do not require the use of the '--esm' flag.\ But you might need it anyway for Node v10 under certain scenarios.\ You can find details about NodeJS ECMAScript modules here
虽然可以在 knexfile、种子和迁移之间混合和匹配不同的模块格式(扩展名),但某些格式组合将需要特定的 NodeJS 版本,尤其是 mjs/cjs 文件将遵循 NodeJS 导入并需要限制。你可以看到 此处 许多可能的场景,以及 此处 一些示例配置
¥While it is possible to mix and match different module formats (extensions)\ between your knexfile, seeds and migrations,\ some format combinations will require specific NodeJS versions,
Notably mjs/cjs files will follow NodeJS import and require restrictions.\ You can see here many possible scenarios,\ and here some sample configurations
节点 v10.* 需要使用 '--experimental-module' 标志才能使用 'mjs' 或 'cjs' 扩展。
¥Node v10.* require the use of the '--experimental-module' flag in order to use the 'mjs' or 'cjs' extension.
# launching knex on Node v10 to use mjs/cjs modules
node --experimental-modules ./node_modules/.bin/knex $@
当使用带有 '.cjs' 或 '.mjs' 扩展名的迁移和种子文件时,你需要明确指定:
¥When using migration and seed files with '.cjs' or '.mjs' extensions, you will need to specify that explicitly:
/**
* knexfile.mjs
*/
export default {
migrations: {
// ... client, connection,etc ....
directory: './migrations',
loadExtensions: ['.mjs'] //
}
}
当你的 knex 文件使用 '.mjs' 扩展名,种子/迁移使用 '.js' 扩展名时,你需要明确指定。
¥When using '.mjs' extensions for your knexfile and '.js' for the seeds/migrations, you will need to specify that explicitly.
/**
* knexfile.mjs
*/
export default {
migrations: {
// ... client, connection,etc ....
directory: './migrations',
loadExtensions: ['.js'] // knex will search for 'mjs' file by default
}
}
对于 knexfile,你可以使用默认导出,它将优先于命名导出。
¥For the knexfile you can use a default export,\ it will take precedence over named export.
/**
* filename: knexfile.js
* For the knexfile you can use a default export
**/
export default {
client: 'sqlite3',
connection: {
filename: '../test.sqlite3',
},
migrations: {
directory: './migrations',
},
seeds: {
directory: './seeds',
},
}
/**
* filename: knexfile.js
* Let knex find the configuration by providing named exports,
* but if exported a default, it will take precedence, and it will be used instead
**/
const config = {
client: 'sqlite3',
connection: {
filename: '../test.sqlite3',
},
migrations: {
directory: './migrations',
},
seeds: {
directory: './seeds',
},
};
/** this will be used, it has precedence over named export */
export default config;
/** Named exports, will be used if you didn't provide a default export */
export const { client, connection, migrations, seeds } = config;
种子和迁移文件需要遵循 Knex 约定
¥Seed and migration files need to follow Knex conventions
// file: seed.js
/**
* Same as with the CommonJS modules
* You will need to export a "seed" named function.
* */
export function seed(knex) {
// ... seed logic here
}
// file: migration.js
/**
* Same as the CommonJS version, the miration file should export
* "up" and "down" named functions
*/
export function up(knex) {
// ... migration logic here
}
export function down(knex) {
// ... migration logic here
}
种子 API
¥Seed API
knex.seed
是 knex 种子 CLI 使用的类。
¥knex.seed
is the class utilized by the knex seed CLI.
每个方法都采用一个可选的 config
对象,该对象可以指定以下属性:
¥Each method takes an optional config
object, which may specify the following properties:
directory
:包含种子文件的目录的相对路径。可以是路径数组(默认./seeds
)¥
directory
: a relative path to the directory containing the seed files. Can be an array of paths (default./seeds
)loadExtensions
:knex 将视为种子的文件扩展名数组。例如,如果你在同一文件夹中将 typescript 转换为 javascript,则你只想执行 javascript 种子。在这种情况下,将loadExtensions
设置为['.js']
(注意点!)(默认['.co', '.coffee', '.eg', '.iced', '.js', '.litcoffee', '.ls', '.ts']
)¥
loadExtensions
: array of file extensions which knex will treat as seeds. For example, if you have typescript transpiled into javascript in the same folder, you want to execute only javascript seeds. In this case, setloadExtensions
to['.js']
(Notice the dot!) (default['.co', '.coffee', '.eg', '.iced', '.js', '.litcoffee', '.ls', '.ts']
)recursive
:如果为 true,将在指定的目录中递归查找种子文件¥
recursive
: if true, will find seed files recursively in the directory / directories specifiedspecific
:从种子目录运行的特定种子文件或种子文件数组,如果其值为undefined
,它将运行所有种子(默认undefined
)。如果指定了数组,种子文件将以与数组相同的顺序运行¥
specific
: a specific seed file or an array of seed files to run from the seeds directory, if its value isundefined
it will run all the seeds (defaultundefined
). If an array is specified, seed files will be run in the same order as the arraysortDirsSeparately
:如果 true 且指定了多个目录,则将在执行下一个文件夹中的种子之前执行单个目录中的所有种子(默认false
)¥
sortDirsSeparately
: if true and multiple directories are specified, all seeds from a single directory will be executed before executing seeds in the next folder (defaultfalse
)seedSource
:指定自定义种子源,请参阅 定制种子源 了解更多信息(默认文件系统)¥
seedSource
: specify a custom seed source, see Custom Seed Source for more info (default filesystem)extension
:用于新生成的种子的扩展名(默认js
)¥
extension
: extension to be used for newly generated seeds (defaultjs
)timestampFilenamePrefix
:是否应添加时间戳作为新生成的种子的前缀(默认false
)¥
timestampFilenamePrefix
: whether timestamp should be added as a prefix for newly generated seeds (defaultfalse
)
make
knex.seed.make(name, [config])
创建一个新的种子文件,并添加种子文件的名称。如果种子目录配置是路径数组,则种子文件将在指定的最新位置生成。
¥Creates a new seed file, with the name of the seed file being added. If the seed directory config is an array of paths, the seed file will be generated in the latest specified.
run
knex.seed.run([config])
运行当前环境的所有种子文件。
¥Runs all seed files for the current environment.
定制种子来源
¥Custom seed sources
Knex 支持自定义种子源,使你可以完全控制种子的来源。当与 webpack/browserify 和其他场景打包时,这对于自定义文件夹结构非常有用。
¥Knex supports custom seed sources, allowing you full control of where your seeds come from. This can be useful for custom folder structures, when bundling with webpack/browserify and other scenarios.
// Create a custom seed source class
class MySeedSource {
// Must return a Promise containing a list of seeds.
// Seeds can be whatever you want, they will be passed as
// arguments to getSeed
getSeeds() {
// In this example we are just returning seed names
return Promise.resolve(['seed1'])
}
getSeed(seed) {
switch(seed) {
case 'seed1':
return (knex) => { /* ... */ }
}
}
}
// pass an instance of your seed source as knex config
knex.seed.run({ seedSource: new MySeedSource() })