dox_orm 3.2.3
dox_orm: ^3.2.3 copied to clipboard
PostgreSQL, MySQL, MariaDB and SQLite query builder, Support Model, Where, orWhere, Find, Join, softDeletes, Debugging and many mores.
dox_orm #
Models, relations and a query builder for Postgres, MySQL, MariaDB and SQLite.
Part of Dox, a web backend framework for Dart. Source code: github.com/dartondox/dox-orm.
Install #
dart pub add dox_orm
To see what is ready and what may still change, read Status and roadmap.
Use it #
Set up the connection once:
import 'package:dox_orm/dox_orm.dart';
DatabaseConfig databaseConfig = DatabaseConfig(
connection: 'sqlite',
connections: <String, ConnectionConfig>{
'sqlite': ConnectionConfig(
driver: Driver.sqlite,
database: 'storage/app.db', // file path, or ':memory:'
),
},
);
SqlQueryBuilder.initializeWithDatabaseConfig(databaseConfig);
Write a model. dox_builder makes the BlogGenerator class
(dart pub add dev:dox_builder dev:build_runner, then dart run build_runner build):
part 'blog.model.g.dart';
@DoxModel(table: 'blogs')
class Blog extends BlogGenerator {
@Column()
String? title;
@Column()
String? status;
}
Use it:
Blog blog = Blog();
blog.title = 'Hello';
blog.status = 'active';
await blog.save();
List<Blog> active = await Blog().where('status', 'active').orderBy('id', 'desc').get();
Blog? one = await Blog().find(1);
// no model: a list of maps
List<Map<String, dynamic>> rows = await QueryBuilder.table('blogs').where('id', '>', 10).get();
// filter by a relation, without loading it (User has a `@HasMany(Post) posts` field)
List<User> writers = await User().whereHas('posts', (QueryBuilder<dynamic> q) {
q.where('published', true);
}).get();
// conditions in brackets
List<Blog> blogs = await Blog()
.where('status', 'active')
.whereGroup((QueryBuilder<Blog> q) {
q.where('views', '>', 100).orWhere('pinned', true);
})
.get();
// write methods return the number of changed rows
int changed = await Blog().where('status', 'draft').update(<String, dynamic>{'status': 'active'});
int deleted = await Blog().where('status', 'spam').delete();
// lock a row in a transaction
await QueryBuilder.transaction(() async {
Blog blog = await Blog().lockForUpdate().findOrFail(1);
blog.status = 'archived';
await blog.save();
});
In a Dox app, start the ORM in a DoxProvider, so each isolate gets its own pool.
Features #
- One API for Postgres, MySQL 8+, MariaDB and SQLite.
- Postgres and MySQL use the native Rust drivers (
dox_postgres_native,dox_mysql_native). When the native library does not load, the app stops with an error that says why and how to fix it. - Models with
@Column, timestamps, soft deletes, events andhiddenfields. - Relations:
@HasOne,@HasMany,@BelongsTo,@ManyToMany, with eager loading. - Filter by relations:
whereHas,orWhereHas,whereDoesntHave,orWhereDoesntHaveandhas('posts', '>=', 3). Nested names likeposts.commentswork. - Query builder:
where(anullvalue isIS NULLorIS NOT NULL),whereIn(also with a sub query),whereBetween,whereColumn,whereLike,whereExists,whereDate,whereYear,whereJsonContains,whereGroup,whereNot(a callback, or a column and value),when,unless,whenValue,join,joinSub,fromSub,union,groupBy,having,distinct,latest,paginate, raw SQL with bound values.toSql()andtoRawSql()(quoted values) for debugging. - Read helpers:
first(same asgetFirst),firstOrFailandfindOrFail(throwModelNotFoundException),hasRows,hasNoRows(alsodoesntExist),pluck,pluckMap,valueOf,chunkandchunkById. - Aggregates:
count,sum,avg,min,max, andwithCount,withSum,withMaxfor relations. - Writes:
createandinsertreturn the new model or map.update,delete,increment,decrement,upsertandinsertOrIgnorereturn the number of changed rows.insertGetIdreturns the new id.insertManyinserts many rows and reads nothing back.firstOrCreate,firstOrNewandupdateOrCreate. - Transactions with
QueryBuilder.transaction(), nested with savepoints, and row locks withlockForUpdate()andsharedLock(). - Schema builder for migrations (used by
dox_migration). - Opt-in behaviors with
OrmFlags, all off by default. Passflags: OrmFlags.all()toDatabaseConfigto turn them all on. See Database setup. - DTO rules
@Uniqueand@Existsthat check the database.
Documentation #
License #
MIT. See LICENSE.