duxt_orm 0.4.0
duxt_orm: ^0.4.0 copied to clipboard
ActiveRecord-style ORM for Dart. Supports PostgreSQL, MySQL, and SQLite with auto-migrations, query builder, and schema definitions.
import 'package:duxt_orm/duxt_orm.dart';
/// Example User model using the new Entity/Model<T> pattern
class User extends Entity {
int? _id;
String? email;
String? name;
bool isActive;
DateTime? createdAt;
User({int? id, this.email, this.name, this.isActive = true, this.createdAt})
: _id = id;
@override
dynamic get id => _id;
@override
set id(dynamic value) => _id = value as int?;
@override
Map<String, dynamic> toMap() => {
'email': email,
'name': name,
'is_active': isActive ? 1 : 0,
};
factory User.fromRow(Map<String, dynamic> row) => User(
id: row['id'] as int?,
email: row['email'] as String?,
name: row['name'] as String?,
isActive: (row['is_active'] as int?) == 1,
createdAt: row['created_at'] != null
? DateTime.parse(row['created_at'] as String)
: null,
);
static void register() {
Entity.registerModel<User>(
User.fromRow,
schema: {
'id': Column.integer().primaryKey().autoIncrement(),
'email': Column.string(255).unique().notNull(),
'name': Column.string(100).notNull(),
'is_active': Column.boolean().defaultValue(true),
'created_at': Column.dateTime().nullable(),
'updated_at': Column.dateTime().nullable(),
},
);
}
@override
String toString() => 'User(id: $id, email: $email, name: $name)';
}
void main() async {
// 1. Register models
User.register();
// 2. Initialize with SQLite for this example
await DuxtOrm.init((
driver: 'sqlite',
host: '',
port: 0,
database: '',
username: '',
password: '',
path: ':memory:', // In-memory database
ssl: false,
));
// 3. Run migrations (creates tables)
await DuxtOrm.migrate();
print('Database migrated!');
// 4. Create a user using Model<T> interface
final users = Model<User>();
final user = User(email: 'john@example.com', name: 'John Doe');
await user.save();
print('Created: $user');
// 5. Query all users
final allUsers = await users.all();
print('All users: $allUsers');
// 6. Find by ID
final found = await users.find(user.id);
print('Found: $found');
// 7. Update
user.name = 'John Updated';
await user.save();
print('Updated: $user');
// 8. Query with conditions
final activeUsers = await users.where('is_active', 1).get();
print('Active users: $activeUsers');
// 9. Query builder
final results = await users.query()
.where('is_active', 1)
.orderByDesc('id')
.limit(10)
.get();
print('Query results: $results');
// 10. Count
final count = await users.count();
print('Total users: $count');
// 11. Delete
await user.destroy();
print('User deleted');
// 12. Close connection
await DuxtOrm.close();
print('Connection closed');
}