Thứ Ba, 13 tháng 4, 2021

Migrations trong AdonisJS




## Migrations
Để sử dụng Migrations, cần khai báo `Migrations Provider` ở file `start/app.js`.

Mặc định sẽ có sẵn 2 file migration ở database/migrations
1. Chạy các files bên trong thư mục database/migrations
> adonis migration:run

Các file nào đã chạy rồi thì lần sau khi gõ command trên nó sẽ không chạy lại các files đó.

2. Kiểm tra status của các migration
> adonis migration:status

3. Nếu có sai sót thì rollback trở lại bản trước khi chạy `migration:run`
> adonis migration:rollback

4. Tạo file migration mới:
> adonis make:migration users
==> Output: database/migrations/1502691651527_users_schema.js

## Cấu trúc file Migration (Schema Files)
Một schema file bao gồm 2 phương thức là up và down.

1. `up()`
Phần xử lý chính (tạo mới table, chỉnh sửa field..)

2. `down()`
Được dùng để revert lại các thay đổi do phần `up()` tạo ra.

## Kiểu dữ liệu của một cột
Method Description
table.bigInteger(name) Adds a bigint column.
table.binary(name, [length]) Adds a binary column.
table.boolean(name) Adds a boolean column.
table.date(name) Adds a date column.
table.datetime(name, [precision]) Adds a datetime column.
table.decimal(name, [precision], [scale]) Adds a decimal column.
table.enu(col, values, [options]) Adds a enum column.
table.float(name, [precision], [scale]) Adds a float column.
table.increments(name) Adds an auto incrementing column.
table.integer(name) Adds an integer column.
table.json(name) Adds a json column.
table.string(name, [length=255]) Adds a string column.
table.text(name, [textType]) Adds a text column.
table.time(name, [precision]) Adds a time column.
table.timestamp(name, [useTz], [precision]) Adds a timestamp column.
table.timestamps([useTimestamps], [defaultToNow]) Adds created/updated columns.
table.uuid(name) Adds a uuid column.

## Column Modifiers
https://adonisjs.com/docs/4.1/migrations
Document: https://knexjs.org/#Schema-after

Method Description
.after(field) Set column to be inserted after field.
.alter() Marks the column as an alter/modify.
.collate(collation) Set column collation (e.g. utf8_unicode_ci).
.comment(value) Set column comment.
.defaultTo(value) Set column default value.
.first() Set column to be inserted at the first position.
.index([indexName], [indexType]) Specifies column as an index.
.inTable(table) Set foreign key table (chain after .references).
.notNullable() Set column to not null.
.nullable() Set column to be nullable.
.primary([constraintName]) Set column as the primary key for a table.
.references(column) Set foreign key column.
.unique() Set column as unique.
.unsigned() Set column to unsigned (if integer).

## Sử dụng một connection khác
<!-->
const Schema = use('Schema')
class UsersSchema extends Schema {
static get connection () {
return 'mysql'
}

// ...
}
module.exports = UsersSchema
<-->

## Migration Commands
Command Description
`make:migration` Create a new migration file.
`migration:run` Run all pending migrations.
`migration:rollback` Rollback last set of migrations.
`migration:refresh` Rollback all migrations to the 0 batch then re-run them
`migration:reset` Rollback all migrations to the 0 batch.
`migration:status` Get the status of all the migrations.

- Command Help: `adonis migration:run --help`

## Danh sách schema method sẵn có
1. Tạo bảng mới
> this.create('users', (table) => { .. })

2. Tạo bảng mới nếu nó chưa tồn tại
> this.createIfNotExists('users', (table) => { .. })

3. Đổi tên table
> this.rename('users', 'my_users')

4. Xóa một table
> this.drop('users')

5. Xóa table nếu đã tồn tại
> this.dropIfExists('users')

6. Chỉnh sửa table
<!-->
this.alter('users', (table) => {
// add new columns or remove existing
})
<-->

7. SQL query thuần (raw)
<!-->
up () {
this
.raw("SET sql_mode='TRADITIONAL'")
.table('users', (table) => {
table.dropColumn('name')
table.string('first_name')
table.string('last_name')
})
}
<-->

8. Kiểm tra một table tồn tại hay không
> const exists = await this.hasTable('users')

9. set timestamp với `knex.fn.now()`
> table.timestamp('created_at').defaultTo(this.fn.now())'


## Chạy code tùy ý
<!-->
class UserSchema {
up () {
// create new table
this.create('new_users', (table) => {
})

// copy data
this.schedule(async (trx) => {
const users = await Database.table('users').transacting(trx)
await Database.table('new_users').transacting(trx).insert(users)
})

// drop old table
this.drop('users')
}
}
-->



Không có nhận xét nào:

Đăng nhận xét

Học lập trình web căn bản với PHP

Bài 1: Các kiến thức căn bản Part 1:  https://jimmyvan88.blogspot.com/2012/05/can-ban-lap-trinh-web-voi-php-bai-1-cac.html Part 2:  https://...