Skip to main content

dox_orm 3.2.3 copy "dox_orm: ^3.2.3" to clipboard
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.

pub package license: MIT

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 and hidden fields.
  • Relations: @HasOne, @HasMany, @BelongsTo, @ManyToMany, with eager loading.
  • Filter by relations: whereHas, orWhereHas, whereDoesntHave, orWhereDoesntHave and has('posts', '>=', 3). Nested names like posts.comments work.
  • Query builder: where (a null value is IS NULL or IS 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() and toRawSql() (quoted values) for debugging.
  • Read helpers: first (same as getFirst), firstOrFail and findOrFail (throw ModelNotFoundException), hasRows, hasNoRows (also doesntExist), pluck, pluckMap, valueOf, chunk and chunkById.
  • Aggregates: count, sum, avg, min, max, and withCount, withSum, withMax for relations.
  • Writes: create and insert return the new model or map. update, delete, increment, decrement, upsert and insertOrIgnore return the number of changed rows. insertGetId returns the new id. insertMany inserts many rows and reads nothing back. firstOrCreate, firstOrNew and updateOrCreate.
  • Transactions with QueryBuilder.transaction(), nested with savepoints, and row locks with lockForUpdate() and sharedLock().
  • Schema builder for migrations (used by dox_migration).
  • Opt-in behaviors with OrmFlags, all off by default. Pass flags: OrmFlags.all() to DatabaseConfig to turn them all on. See Database setup.
  • DTO rules @Unique and @Exists that check the database.

Documentation #

License #

MIT. See LICENSE.

0
likes
160
points
2.48k
downloads

Documentation

API reference

Publisher

verified publisherdartondox.dev

Weekly Downloads

PostgreSQL, MySQL, MariaDB and SQLite query builder, Support Model, Where, orWhere, Find, Join, softDeletes, Debugging and many mores.

Homepage
Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

dox_annotation, dox_mysql_native, dox_postgres_native, dox_validation, sqlite3

More

Packages that depend on dox_orm