ธุรกรรมและการย้ายข้อมูล
นำธุรกรรมฐานข้อมูลมาใช้สำหรับการดำเนินการแบบอะตอมิก และจัดการการเปลี่ยนแปลงสคีมาอย่างมีประสิทธิภาพด้วยการย้ายข้อมูลของ TypeORM
ธุรกรรมและการย้ายข้อมูล เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Atomic Operations: Transactions
Imagine transferring money between two bank accounts. If the deduction from one account succeeds but the addition to the other fails, your data is inconsistent!
Database transactions solve this by grouping multiple database operations into a single, atomic unit. Either all operations succeed (commit), or none of them do (rollback).
Understanding ACID Properties
Transactions ensure data reliability by adhering to ACID properties:
- Atomicity: All or nothing.
- Consistency: Database state remains valid.
- Isolation: Concurrent transactions don't interfere.
- Durability: Committed changes are permanent.
These properties are vital for maintaining data integrity in complex applications.
TypeORM Manual Transactions
TypeORM allows you to manage transactions manually using the DataSource or EntityManager. This gives you fine-grained control over when to commit or rollback.
You typically use dataSource.transaction(async manager => { ... }), where manager is a transactional entity manager.
Manual Transaction Example
Here's a simplified example of transferring funds within a transaction. If any step fails, the entire operation is rolled back.
import { DataSource, Entity, PrimaryGeneratedColumn, Column, Repository } from 'typeorm';
@Entity()
export class Account {
@PrimaryGeneratedColumn() id: number;
@Column({ type: 'decimal', precision: 10, scale: 2 }) balance: number;
}
async function runTransaction() {
const AppDataSource = new DataSource({
type: 'sqlite',
database: ':memory:',
entities: [Account],
synchronize: true,
});
await AppDataSource.initialize();
const accountRepo = AppDataSource.getRepository(Account);
await AppDataSource.transaction(async manager => {
const sender = await manager.save(accountRepo.create({ balance: 100 }));
const receiver = await manager.save(accountRepo.create({ balance: 50 }));
console.log(`Initial: Sender ${sender.balance}, Receiver ${receiver.balance}`);
sender.balance -= 20;
receiver.balance += 20;
await manager.save(sender);
// Simulate an error here to trigger rollback:
// throw new Error('Failed to update receiver!');
await manager.save(receiver);
console.log(`Final: Sender ${sender.balance}, Receiver ${receiver.balance}`);
});
await AppDataSource.destroy();
}
// To run this in a Node.js context:
// runTransaction().catch(console.error);
// For CoddyKit, we just show the code.Decorators for Transactions
NestJS and TypeORM often work together. For convenience, TypeORM provides the @Transaction() and @TransactionManager() decorators.
You can apply @Transaction() to a service method, and TypeORM will automatically wrap the method's execution in a transaction.
Decorator Transaction Example
Using the @Transaction() decorator makes your service code cleaner, as you don't need to manually handle transaction commits or rollbacks.
import { Injectable } from '@nestjs/common';
import { Repository, EntityManager } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Transaction } from 'typeorm'; // Import Transaction decorator
// Assume Account Entity is defined elsewhere
class Account {
id: number;
balance: number;
}
@Injectable()
export class BankService {
constructor(
@InjectRepository(Account) private accountRepository: Repository<Account>,
) {}
@Transaction()
async transferFunds(
senderId: number,
receiverId: number,
amount: number,
@TransactionManager() manager?: EntityManager, // Manager is injected
): Promise<boolean> {
const accountManager = manager || this.accountRepository.manager; // Use injected manager
const sender = await accountManager.findOneBy(Account, { id: senderId });
const receiver = await accountManager.findOneBy(Account, { id: receiverId });
if (!sender || !receiver || sender.balance < amount) {
throw new Error('Transfer failed: Invalid accounts or insufficient funds');
}
sender.balance -= amount;
receiver.balance += amount;
await accountManager.save(sender);
await accountManager.save(receiver);
console.log(`Transferred ${amount}. Sender: ${sender.balance}, Receiver: ${receiver.balance}`);
return true;
}
}
// Note: This code is illustrative within a NestJS service context.
// It's not runnable as a standalone script without a full NestJS setup.Managing Schema Changes: Migrations
As your application evolves, your database schema will change (e.g., adding new columns, tables). Directly modifying the database can be risky and hard to track.
Database migrations provide a structured, version-controlled way to apply changes to your database schema, ensuring consistency across environments.
Generating TypeORM Migrations
TypeORM has a powerful CLI to generate migration files. It compares your entities with the current database schema and creates a script to bridge the differences.
First, ensure your ormconfig.json or DataSource is set up correctly. Then, run the command:
npx typeorm migration:generate src/migration/MyNewMigration
This creates a timestamped .ts file in the specified folder.
Migration File Structure
Each migration file contains two key methods:
up(queryRunner: QueryRunner): Promise: Defines changes to apply to the database (e.g., create table, add column).down(queryRunner: QueryRunner): Promise: Defines how to revert the changes made byup(e.g., drop table, remove column).
This allows you to easily roll forward and backward through schema versions.
import { MigrationInterface, QueryRunner, Table } from 'typeorm';
export class MyNewMigration1678886400000 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: 'products',
columns: [
{ name: 'id', type: 'int', isPrimary: true, isGenerated: true, generationStrategy: 'increment' },
{ name: 'name', type: 'varchar' },
{ name: 'price', type: 'decimal', precision: 10, scale: 2, default: 0 },
],
}),
true,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('products');
}
}Applying and Reverting Migrations
Once you've written or generated your migration files, you need to apply them to your database:
- Apply all pending migrations:
npx typeorm migration:run - Revert the last applied migration:
npx typeorm migration:revert
Always run migrations in your development and production environments to keep schemas synchronized.
Check Your Knowledge
Which of the following statements about database transactions and migrations in TypeORM is FALSE?
Recap: Transactions & Migrations
You've learned about two critical concepts for robust database management:
- Transactions: Ensure data integrity through atomic operations following ACID principles, using TypeORM's manual methods or the
@Transaction()decorator. - Migrations: Provide a structured way to evolve your database schema, using TypeORM CLI to generate and apply changes via
up()anddown()methods.
Mastering these will help you build more reliable and maintainable backend APIs.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 20
- บทเรียน
- 76
คำถามที่พบบ่อย
บทเรียน “ธุรกรรมและการย้ายข้อมูล” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ธุรกรรมและการย้ายข้อมูล” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ธุรกรรมและการย้ายข้อมูล”
นำธุรกรรมฐานข้อมูลมาใช้สำหรับการดำเนินการแบบอะตอมิก และจัดการการเปลี่ยนแปลงสคีมาอย่างมีประสิทธิภาพด้วยการย้ายข้อมูลของ TypeORM คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน
บทเรียน “ธุรกรรมและการย้ายข้อมูล” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม
ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ที่เก็บข้อมูล TypeORM แบบกำหนดเอง
- ธุรกรรมและการย้ายข้อมูล
- การเติมข้อมูลเริ่มต้นและการทดสอบฐานข้อมูล