아도니스js / adonisjs db migration / db column add / alter table
AdonisJS migration column 변경
migration file 생성
c:\a\proj>adonis make:migration user_hist
> Choose an action Select table
√ create database\migrations\1553738938867_user_hist_schema.js
file 변경
'use strict'
/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')
class UserHistSchema extends Schema {
up () {
this.table('user_hists', (table) => {
// alter table
table.string('power', 124).notNullable().alter();
})
// create
this.create('trans', (table) => {
table.increments();
table.integer('user_id').unsigned().notNullable();
table.string('type', 50).notNullable().collate('utf8_unicode_ci');
table.timestamps();
table.index('user_id');
table.charset = 'utf8';
table.collation = 'utf8_unicode_ci';
// table 의 collate 을 utf8_unicode_ci 로 설정하기
// https://adonisjs.com/docs/4.0/migrations#_executing_arbitrary_code
this.schedule(async (trx) => {
// ALTER TABLE `cma_transaction` CONVERT TO CHARACTER SET UTF8 COLLATE utf8_unicode_ci
await Database.raw('ALTER TABLE `trans` CONVERT TO CHARACTER SET UTF8 COLLATE utf8_unicode_ci').transacting(trx)
})
});
}
down () {
this.table('user_hists', (table) => {
// reverse alternations
table.string('power', 60).notNullable().alter();
})
}
}
module.exports = UserHistSchema
status 보기
c:\a\proj>adonis migration:status
migration:status 를 이용하면 현재 어떤 schema 까지 적용이 됐는지 확인할 수 있다.
run
아래처럼 실행하면 된다.
c:\a\proj>adonis migration:run
migrate: 1553738938867_user_hist_schema.js
Database migrated successfully in 1.25 s
alter
아래 link 에서 table 의 column 추가 등의 변경사항에 관한 부분을 확인할 수 있다.
knex alter
alter 와 관련된 사항은 위의 link 에서 자세히 확인할 수 있다.
기본적으로 table(t) 에 어떤 함수를 부르면 add 의 의미이다.
table.bigInteger('mycolumn') // mycolumn 이란 이름을 가진 bigInteger type 의 column 을 table 에 추가
그래서 위의 경우는 table 에 'mycolumn' 을 추가 하는 의미이다.
그런데, 뒤에 alter() 를 붙이면, 이전의 값을 없애고, 새로운 값으로 변경하는 것이다.
t.integer('mycolumn').alter();
그래서 위의 경우는 이전의 'mycolumn' 이란 column 의 type 을 'integer' 로 변경하는 것이다. 그리고 type 을 변경하면서, not null constraint 와 default value 도 drop 하게 된다.
in production
Error: Cannot run migrations in production. Use --force flag to continue
at MigrationRun._validateState (/home/ubuntu/new-funded-backend/node_modules/@adonisjs/lucid/commands/BaseMigration.js:58:13)
...
기본적으로 "adonis migration:run --force" 를 하지 않으면 error 가 난다.
References
- Adonis Migrations