mysql orm template

This commit is contained in:
thomashii 2022-04-30 10:14:23 +08:00
parent 4839e2cef5
commit 985100c271
6 changed files with 122 additions and 95 deletions

View file

@ -1,30 +1,28 @@
# ORM Starter Application for Angel3 framework # ORM Starter Application for Angel3 framework
This is an ORM starter application for [Angel3 framework](https://angel3-framework.web.app) which is a full-stack Web framework in Dart. The default database is `postgresql`. `mysql` support is still in active development. This is an ORM starter application for [Angel3 framework](https://angel3-framework.web.app) which is a full-stack Web framework in Dart. The default database is MariaDB. MySQL support is still in active development.
## Installation & Setup ## Installation & Setup
1. Download and install [Dart](https://dart.dev/get-dart). 1. Download and install [Dart](https://dart.dev/get-dart).
2. Install `postgresql` version 10, 11, 12 and 13 2. Install `MariaDB` 10.2.x or later
3. Create a new user and database in postgres using `psql` cli. For example: 3. Create a new user and database using MySQL Client. For example:
```sql ```sql
postgres=# create database appdb; MariaDB [(none)]> CREATE DATABASE appdb;
postgres=# create user appuser with encrypted password 'App1970#'; MariaDB [(none)]> CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'App1970#';
postgres=# grant all privileges on database appdb to appuser; MariaDB [(none)]> GRANT ALL PRIVILEGES ON appdb.* TO 'appuser'@'localhost';
``` ```
4. Update the `postgres` section in the `config/default.yaml` file with the newly created user and database name. 4. Update the `mariadb` section in the `config/default.yaml` file with the newly created user and database name.
```yaml ```yaml
postgres: mariadb:
host: localhost host: localhost
port: 5432 port: 3306
database_name: appdb database_name: appdb
username: appuser username: appuser
password: App1970# password: App1970#
useSSL: false
time_zone: UTC
``` ```
5. Run the migration to generate `migrations` and `greetings` tables in the database. 5. Run the migration to generate `migrations` and `greetings` tables in the database.
@ -57,8 +55,8 @@ This is an ORM starter application for [Angel3 framework](https://angel3-framewo
4. Query DB: 4. Query DB:
``` ```bash
http://localhost:3000/greetings/ curl http://localhost:3000/greetings/
``` ```
### Production ### Production
@ -71,6 +69,14 @@ This is an ORM starter application for [Angel3 framework](https://angel3-framewo
2. Run as docker. Edit and run the provided `Dockerfile` to build the image. 2. Run as docker. Edit and run the provided `Dockerfile` to build the image.
### Building ORM Model
1. Run the followig command:
```bash
dart run build_runner build
```
## Resources ## Resources
Visit the [Developer Guide](https://angel3-docs.dukefirehawk.com/guides) for dozens of guides and resources, including video tutorials, to get up and running as quickly as possible with Angel3. Visit the [Developer Guide](https://angel3-docs.dukefirehawk.com/guides) for dozens of guides and resources, including video tutorials, to get up and running as quickly as possible with Angel3.

View file

@ -2,7 +2,7 @@ import 'package:angel/src/config/plugins/orm.dart';
import 'package:angel/models.dart'; import 'package:angel/models.dart';
import 'package:angel3_configuration/angel3_configuration.dart'; import 'package:angel3_configuration/angel3_configuration.dart';
import 'package:angel3_migration_runner/angel3_migration_runner.dart'; import 'package:angel3_migration_runner/angel3_migration_runner.dart';
import 'package:angel3_migration_runner/postgres.dart'; import 'package:angel3_migration_runner/mariadb.dart';
import 'package:file/local.dart'; import 'package:file/local.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
@ -20,9 +20,12 @@ void main(List<String> args) async {
var fs = LocalFileSystem(); var fs = LocalFileSystem();
var configuration = await loadStandaloneConfiguration(fs); var configuration = await loadStandaloneConfiguration(fs);
var connection = await connectToPostgres(configuration);
var migrationRunner = PostgresMigrationRunner(connection, migrations: [ // MariaDB database
var connection = await connectToMariaDb(configuration);
var migrationRunner = MariaDbMigrationRunner(connection, migrations: [
GreetingMigration(), GreetingMigration(),
]); ]);
return await runMigrations(migrationRunner, args);
await runMigrations(migrationRunner, args);
} }

View file

@ -2,12 +2,12 @@
jwt_secret: INSECURE_DEFAULT_SECRET jwt_secret: INSECURE_DEFAULT_SECRET
host: 127.0.0.1 host: 127.0.0.1
port: 3000 port: 3000
postgres: mariadb:
host: localhost host: localhost
port: 5432 port: 3306
database_name: appdb database_name: appdb
username: appuser username: appuser
password: App1970# password: App1970#
use_ssl: false
time_zone: UTC

View file

@ -2,37 +2,38 @@ import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'package:angel3_framework/angel3_framework.dart'; import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_orm/angel3_orm.dart'; import 'package:angel3_orm/angel3_orm.dart';
import 'package:angel3_orm_postgres/angel3_orm_postgres.dart'; import 'package:angel3_orm_mysql/angel3_orm_mysql.dart';
import 'package:postgres/postgres.dart'; import 'package:mysql1/mysql1.dart';
// For MariaDb
Future<void> configureServer(Angel app) async { Future<void> configureServer(Angel app) async {
try { try {
var connection = await connectToPostgres(app.configuration); var connection = await connectToMariaDb(app.configuration);
await connection.open(); var executor = MariaDbExecutor(connection, logger: app.logger);
var executor = PostgreSqlExecutor(connection, logger: app.logger);
app app
..container.registerSingleton<QueryExecutor>(executor) ..container.registerSingleton<QueryExecutor>(executor)
..shutdownHooks.add((_) => connection.close()); ..shutdownHooks.add((_) => connection.close());
} catch (e) { } catch (e) {
app.logger.severe("Failed to connect to PostgreSQL. ORM disabled.", e); app.logger.severe("Failed to connect to MariaDB. ORM disabled.", e);
} }
} }
Future<PostgreSQLConnection> connectToPostgres(Map configuration) async { Future<MySqlConnection> connectToMariaDb(Map configuration) async {
var postgresConfig = configuration['postgres'] as Map? ?? {}; var mariaDbConfig = configuration['mariadb'] as Map? ?? {};
var connection = PostgreSQLConnection( var settings = ConnectionSettings(
postgresConfig['host'] as String? ?? 'localhost', host: mariaDbConfig['host'] as String? ?? 'localhost',
postgresConfig['port'] as int? ?? 5432, port: mariaDbConfig['port'] as int? ?? 5432,
postgresConfig['database_name'] as String? ?? db: mariaDbConfig['database_name'] as String? ??
Platform.environment['USER'] ?? Platform.environment['USER'] ??
Platform.environment['USERNAME'] ?? Platform.environment['USERNAME'] ??
'', '',
username: postgresConfig['username'] as String?, user: mariaDbConfig['username'] as String?,
password: postgresConfig['password'] as String?, password: mariaDbConfig['password'] as String?,
timeZone: postgresConfig['time_zone'] as String? ?? 'UTC', timeout: Duration(
timeoutInSeconds: postgresConfig['timeout_in_seconds'] as int? ?? 30, seconds: mariaDbConfig['timeout_in_seconds'] as int? ?? 30000),
useSSL: postgresConfig['use_ssl'] as bool? ?? false); useSSL: mariaDbConfig['use_ssl'] as bool? ?? false);
var connection = await MySqlConnection.connect(settings);
return connection; return connection;
} }

View file

@ -11,9 +11,9 @@ class GreetingMigration extends Migration {
void up(Schema schema) { void up(Schema schema) {
schema.create('greetings', (table) { schema.create('greetings', (table) {
table.serial('id').primaryKey(); table.serial('id').primaryKey();
table.varChar('message');
table.timeStamp('created_at'); table.timeStamp('created_at');
table.timeStamp('updated_at'); table.timeStamp('updated_at');
table.varChar('message', length: 255);
}); });
} }
@ -28,7 +28,8 @@ class GreetingMigration extends Migration {
// ************************************************************************** // **************************************************************************
class GreetingQuery extends Query<Greeting, GreetingQueryWhere> { class GreetingQuery extends Query<Greeting, GreetingQueryWhere> {
GreetingQuery({Set<String>? trampoline}) { GreetingQuery({Query? parent, Set<String>? trampoline})
: super(parent: parent) {
trampoline ??= <String>{}; trampoline ??= <String>{};
trampoline.add(tableName); trampoline.add(tableName);
_where = GreetingQueryWhere(this); _where = GreetingQueryWhere(this);
@ -37,6 +38,8 @@ class GreetingQuery extends Query<Greeting, GreetingQueryWhere> {
@override @override
final GreetingQueryValues values = GreetingQueryValues(); final GreetingQueryValues values = GreetingQueryValues();
List<String> _selectedFields = [];
GreetingQueryWhere? _where; GreetingQueryWhere? _where;
@override @override
@ -51,7 +54,15 @@ class GreetingQuery extends Query<Greeting, GreetingQueryWhere> {
@override @override
List<String> get fields { List<String> get fields {
return const ['id', 'message', 'created_at', 'updated_at']; const _fields = ['id', 'created_at', 'updated_at', 'message'];
return _selectedFields.isEmpty
? _fields
: _fields.where((field) => _selectedFields.contains(field)).toList();
}
GreetingQuery select(List<String> selectedFields) {
_selectedFields = selectedFields;
return this;
} }
@override @override
@ -64,40 +75,42 @@ class GreetingQuery extends Query<Greeting, GreetingQueryWhere> {
return GreetingQueryWhere(this); return GreetingQueryWhere(this);
} }
static Greeting? parseRow(List row) { Optional<Greeting> parseRow(List row) {
if (row.every((x) => x == null)) return null; if (row.every((x) => x == null)) {
return Optional.empty();
}
var model = Greeting( var model = Greeting(
id: row[0].toString(), id: fields.contains('id') ? row[0].toString() : null,
message: (row[1] as String?), createdAt: fields.contains('created_at') ? (row[1] as DateTime?) : null,
createdAt: (row[2] as DateTime?), updatedAt: fields.contains('updated_at') ? (row[2] as DateTime?) : null,
updatedAt: (row[3] as DateTime?)); message: fields.contains('message') ? (row[3] as String?) : null);
return model; return Optional.of(model);
} }
@override @override
Optional<Greeting> deserialize(List row) { Optional<Greeting> deserialize(List row) {
return Optional.ofNullable(parseRow(row)); return parseRow(row);
} }
} }
class GreetingQueryWhere extends QueryWhere { class GreetingQueryWhere extends QueryWhere {
GreetingQueryWhere(GreetingQuery query) GreetingQueryWhere(GreetingQuery query)
: id = NumericSqlExpressionBuilder<int>(query, 'id'), : id = NumericSqlExpressionBuilder<int>(query, 'id'),
message = StringSqlExpressionBuilder(query, 'message'),
createdAt = DateTimeSqlExpressionBuilder(query, 'created_at'), createdAt = DateTimeSqlExpressionBuilder(query, 'created_at'),
updatedAt = DateTimeSqlExpressionBuilder(query, 'updated_at'); updatedAt = DateTimeSqlExpressionBuilder(query, 'updated_at'),
message = StringSqlExpressionBuilder(query, 'message');
final NumericSqlExpressionBuilder<int> id; final NumericSqlExpressionBuilder<int> id;
final StringSqlExpressionBuilder message;
final DateTimeSqlExpressionBuilder createdAt; final DateTimeSqlExpressionBuilder createdAt;
final DateTimeSqlExpressionBuilder updatedAt; final DateTimeSqlExpressionBuilder updatedAt;
final StringSqlExpressionBuilder message;
@override @override
List<SqlExpressionBuilder> get expressionBuilders { List<SqlExpressionBuilder> get expressionBuilders {
return [id, message, createdAt, updatedAt]; return [id, createdAt, updatedAt, message];
} }
} }
@ -112,11 +125,6 @@ class GreetingQueryValues extends MapQueryValues {
} }
set id(String? value) => values['id'] = value; set id(String? value) => values['id'] = value;
String? get message {
return (values['message'] as String?);
}
set message(String? value) => values['message'] = value;
DateTime? get createdAt { DateTime? get createdAt {
return (values['created_at'] as DateTime?); return (values['created_at'] as DateTime?);
} }
@ -127,10 +135,15 @@ class GreetingQueryValues extends MapQueryValues {
} }
set updatedAt(DateTime? value) => values['updated_at'] = value; set updatedAt(DateTime? value) => values['updated_at'] = value;
String? get message {
return (values['message'] as String?);
}
set message(String? value) => values['message'] = value;
void copyFrom(Greeting model) { void copyFrom(Greeting model) {
message = model.message;
createdAt = model.createdAt; createdAt = model.createdAt;
updatedAt = model.updatedAt; updatedAt = model.updatedAt;
message = model.message;
} }
} }
@ -140,46 +153,49 @@ class GreetingQueryValues extends MapQueryValues {
@generatedSerializable @generatedSerializable
class Greeting extends _Greeting { class Greeting extends _Greeting {
Greeting({this.id, required this.message, this.createdAt, this.updatedAt}); Greeting({this.id, this.createdAt, this.updatedAt, required this.message});
/// A unique identifier corresponding to this item.
@override
String? id;
/// The time at which this item was created.
@override
DateTime? createdAt;
/// The last time at which this item was updated.
@override
DateTime? updatedAt;
@override @override
final String? id; String? message;
@override
final String? message;
@override
final DateTime? createdAt;
@override
final DateTime? updatedAt;
Greeting copyWith( Greeting copyWith(
{String? id, String? message, DateTime? createdAt, DateTime? updatedAt}) { {String? id, DateTime? createdAt, DateTime? updatedAt, String? message}) {
return Greeting( return Greeting(
id: id ?? this.id, id: id ?? this.id,
message: message ?? this.message,
createdAt: createdAt ?? this.createdAt, createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt); updatedAt: updatedAt ?? this.updatedAt,
message: message ?? this.message);
} }
@override @override
bool operator ==(other) { bool operator ==(other) {
return other is _Greeting && return other is _Greeting &&
other.id == id && other.id == id &&
other.message == message &&
other.createdAt == createdAt && other.createdAt == createdAt &&
other.updatedAt == updatedAt; other.updatedAt == updatedAt &&
other.message == message;
} }
@override @override
int get hashCode { int get hashCode {
return hashObjects([id, message, createdAt, updatedAt]); return hashObjects([id, createdAt, updatedAt, message]);
} }
@override @override
String toString() { String toString() {
return 'Greeting(id=$id, message=$message, createdAt=$createdAt, updatedAt=$updatedAt)'; return 'Greeting(id=$id, createdAt=$createdAt, updatedAt=$updatedAt, message=$message)';
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
@ -212,7 +228,6 @@ class GreetingSerializer extends Codec<Greeting, Map> {
@override @override
GreetingEncoder get encoder => const GreetingEncoder(); GreetingEncoder get encoder => const GreetingEncoder();
@override @override
GreetingDecoder get decoder => const GreetingDecoder(); GreetingDecoder get decoder => const GreetingDecoder();
static Greeting fromMap(Map map) { static Greeting fromMap(Map map) {
@ -222,29 +237,28 @@ class GreetingSerializer extends Codec<Greeting, Map> {
return Greeting( return Greeting(
id: map['id'] as String?, id: map['id'] as String?,
message: map['message'] as String?,
createdAt: map['created_at'] != null createdAt: map['created_at'] != null
? (map['created_at'] is DateTime ? (map['created_at'] is DateTime
? (map['created_at'] as DateTime?) ? (map['created_at'] as DateTime)
: DateTime.parse(map['created_at'].toString())) : DateTime.parse(map['created_at'].toString()))
: null, : null,
updatedAt: map['updated_at'] != null updatedAt: map['updated_at'] != null
? (map['updated_at'] is DateTime ? (map['updated_at'] is DateTime
? (map['updated_at'] as DateTime?) ? (map['updated_at'] as DateTime)
: DateTime.parse(map['updated_at'].toString())) : DateTime.parse(map['updated_at'].toString()))
: null); : null,
message: map['message'] as String?);
} }
static Map<String, dynamic> toMap(_Greeting model) { static Map<String, dynamic> toMap(_Greeting? model) {
if (model.message == null) { if (model == null) {
throw FormatException("Missing required field 'message' on Greeting."); throw FormatException("Required field [model] cannot be null");
} }
return { return {
'id': model.id, 'id': model.id,
'message': model.message,
'created_at': model.createdAt?.toIso8601String(), 'created_at': model.createdAt?.toIso8601String(),
'updated_at': model.updatedAt?.toIso8601String() 'updated_at': model.updatedAt?.toIso8601String(),
'message': model.message
}; };
} }
} }
@ -252,16 +266,16 @@ class GreetingSerializer extends Codec<Greeting, Map> {
abstract class GreetingFields { abstract class GreetingFields {
static const List<String> allFields = <String>[ static const List<String> allFields = <String>[
id, id,
message,
createdAt, createdAt,
updatedAt updatedAt,
message
]; ];
static const String id = 'id'; static const String id = 'id';
static const String message = 'message';
static const String createdAt = 'created_at'; static const String createdAt = 'created_at';
static const String updatedAt = 'updated_at'; static const String updatedAt = 'updated_at';
static const String message = 'message';
} }

View file

@ -11,7 +11,7 @@ dependencies:
angel3_jael: ^6.0.0 angel3_jael: ^6.0.0
angel3_migration: ^6.0.0 angel3_migration: ^6.0.0
angel3_orm: ^6.0.0 angel3_orm: ^6.0.0
angel3_orm_postgres: ^6.0.0 angel3_orm_mysql: ^6.0.0-beta.1
angel3_serialize: ^6.0.0 angel3_serialize: ^6.0.0
angel3_production: ^6.0.0 angel3_production: ^6.0.0
angel3_static: ^6.0.0 angel3_static: ^6.0.0
@ -29,3 +29,6 @@ dev_dependencies:
io: ^1.0.0 io: ^1.0.0
test: ^1.21.0 test: ^1.21.0
lints: ^1.0.0 lints: ^1.0.0
dependency_overrides:
angel3_migration_runner:
path: ../belatuk/packages/orm/angel_migration_runner