드리프트 플러그인(drift plugin)을 사용하면 직접 SQL을 작성하지 않고 객체-관계 매핑(ORM)으로 SQLite를 사용할 수 있습니다.
SQL문과 Drift 사용법을 비교하며 서술해 보겠습니다.
Table 생성하기
SQL
CREATE TABLE product (
id INTEGER PRIMARY KEY AUTOINCREMENT, // 유니크 ID
name VARCHAR NOT NULL, // 이름
quantity INT DEFAULT 0, // 개수
price INT NOT NULL
)
Drift
import 'package:drift/drift.dart';
class Product extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text()();
IntColumn get quantity => integer().withDefault(const Constant(0))();
IntColumn get price => integer().nullable()();
}
INSERT 하기
SQL
INSERT INTO product (name, queantity, price)
VALUES ('김치', 20, 50000)
Drift
Future<int> addProduct() {
return into(product).insert(
ProductCompanion(
name: Value('김치'),
quantity: Value(20),
price: Value(50000),
),
);
}
SELECT 하기
SQL
SELECT * FROM product WHERE id = 1;
Drift
Future<ProductData> getProduct() {
return (select(product)..where((t) => t.id.equals(1))).getSingle();
}
UPDATE 하기
SQL
UPDATE product SET quantity = 100 WHERE id = 1;
Drift
Future<int> updateProduct() {
return (update(product)
..where(
(t) => t.id.equals(1),
))
.write(
ProductCompanion(
quantity: Value(100),
),
);
}
DELETE 하기
SQL
DELETE FROM product WHERE id = 1;
Drift
Future<int> deleteProduct() {
return (delete(product)..where((t) => t.id.equals(1))).go();
}
#SQLite #Flutter #drift #plugin #ORM #DB #Database #SQL