Skip to content

Commit

Permalink
Improve usage experience
Browse files Browse the repository at this point in the history
  • Loading branch information
codekeyz committed Apr 21, 2024
1 parent 5cbd351 commit e90c739
Show file tree
Hide file tree
Showing 24 changed files with 347 additions and 249 deletions.
1 change: 1 addition & 0 deletions _tests_/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
database/database.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import 'package:yaroorm/yaroorm.dart';
import 'package:yaroorm_tests/src/models.dart';

class AddUsersTable extends Migration {
@override
void up(List<Schema> schemas) {
schemas.add(UserSchema);
}

@override
void down(List<Schema> schemas) {
schemas.add(Schema.dropIfExists(UserSchema));
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,5 @@
import 'package:yaroorm/yaroorm.dart';

import 'models.dart';

class AddUsersTable extends Migration {
@override
void up(List<Schema> schemas) {
schemas.add(UserSchema);
}

@override
void down(List<Schema> schemas) {
schemas.add(Schema.dropIfExists(UserSchema));
}
}
import 'package:yaroorm_tests/src/models.dart';

class AddPostsTable extends Migration {
@override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import 'package:path/path.dart' as path;
import 'package:yaroorm/yaroorm.dart';

import 'migrations.dart';

part 'database.g.dart';

@DB.useConfig
final config = YaroormConfig(
'foo_sqlite',
connections: [
DatabaseConnection(
'foo_sqlite',
DatabaseDriverType.sqlite,
database: path.absolute('test/integration', 'db.sqlite'),
database: path.absolute('database', 'db.sqlite'),
dbForeignKeys: true,
),
DatabaseConnection(
Expand Down Expand Up @@ -44,5 +40,4 @@ final config = YaroormConfig(
port: 3002,
),
],
migrations: [AddUsersTable(), AddPostsTable()],
);
File renamed without changes.
File renamed without changes.
7 changes: 4 additions & 3 deletions _tests_/test/integration/e2e_basic.dart
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import 'package:test/test.dart';
import 'package:collection/collection.dart';
import 'package:yaroorm/yaroorm.dart';
import 'package:yaroorm_tests/src/models.dart';

import 'fixtures/models.dart';
import '../../database/database.dart';
import '../../lib/test_data.dart';
import 'fixtures/migrator.dart';
import 'fixtures/test_data.dart';

void runBasicE2ETest(String connectionName) {
Query.addTypeDef<User>(userTypeData);
initializeORM();

final driver = DB.driver(connectionName);

Expand Down
10 changes: 1 addition & 9 deletions _tests_/test/integration/fixtures/migrator.dart
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import 'dart:io';

import 'package:test/test.dart';
import 'database.dart';

import 'package:yaroorm/src/cli/orm.dart';

void main(List<String> args) async {
initializeORM();
await OrmCLIRunner.start(args);
}

Future<void> runMigrator(String connectionName, String command) async {
final commands = ['run', '_tests_/test/integration/fixtures/migrator.dart', command, '--connection=$connectionName'];
final commands = ['run', 'yaroorm', command, '--connection=$connectionName'];
print('> dart ${commands.join(' ')}\n');

final result = await Process.run('dart', commands);
Expand Down
4 changes: 2 additions & 2 deletions _tests_/test/integration/mariadb.e2e.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import 'package:test/test.dart';

import 'fixtures/database.dart' as db;
import '../../database/database.dart';
import 'e2e_basic.dart';

void main() async {
db.initializeORM();
initializeORM();

group('MariaDB', () {
group('Basic E2E Test', () => runBasicE2ETest('bar_mariadb'));
Expand Down
4 changes: 2 additions & 2 deletions _tests_/test/integration/mysql.e2e.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import 'package:test/test.dart';

import 'fixtures/database.dart' as db;
import '../../database/database.dart';
import 'e2e_basic.dart';

void main() async {
db.initializeORM();
initializeORM();

group('MySQL', () {
group('Basic E2E Test', () => runBasicE2ETest('moo_mysql'));
Expand Down
4 changes: 2 additions & 2 deletions _tests_/test/integration/pgsql.e2e.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import 'package:test/test.dart';
import 'fixtures/database.dart' as db;
import '../../database/database.dart';
import 'e2e_basic.dart';

void main() async {
db.initializeORM();
initializeORM();

group('Postgres', () {
group('Basic E2E Test', () => runBasicE2ETest('foo_pgsql'));
Expand Down
4 changes: 2 additions & 2 deletions _tests_/test/integration/sqlite.e2e.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import 'package:test/test.dart';

import 'fixtures/database.dart' as db;
import '../../database/database.dart';
import 'e2e_basic.dart';

void main() async {
db.initializeORM();
initializeORM();

group('SQLite', () {
group('Basic E2E Test', () => runBasicE2ETest('foo_sqlite'));
Expand Down
6 changes: 3 additions & 3 deletions _tests_/test/yaroorm_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import 'package:yaroorm/src/database/driver/mysql_driver.dart';
import 'package:yaroorm/src/database/driver/pgsql_driver.dart';
import 'package:yaroorm/src/database/driver/sqlite_driver.dart';
import 'package:yaroorm/yaroorm.dart';
import 'package:yaroorm_tests/src/models.dart';

import 'integration/fixtures/database.dart' as db;
import 'integration/fixtures/models.dart';
import '../database/database.dart';

Matcher throwsArgumentErrorWithMessage(String message) =>
throwsA(isA<ArgumentError>().having((p0) => p0.message, '', message));

void main() {
setUpAll(db.initializeORM);
setUpAll(initializeORM);

group('DatabaseDriver.init', () {
group('when sqlite connection', () {
Expand Down
123 changes: 30 additions & 93 deletions bin/yaroorm.dart
Original file line number Diff line number Diff line change
@@ -1,116 +1,53 @@
import 'dart:io';
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:path/path.dart' as path;
import 'package:source_gen/source_gen.dart';
import 'package:yaroorm/src/cli/logger.dart';
import 'package:yaroorm/src/cli/commands/init_orm_command.dart';

import 'package:yaroorm/src/migration.dart' show Migration;
import 'package:yaroorm/src/database/entity/entity.dart' show Entity;
const _migratorFileContent = '''
import 'package:yaroorm/src/cli/orm.dart';
import 'package:yaroorm/yaroorm.dart';
import '../../database/database.dart';
void main(List<String> args) async {
final migratorDirectoryPath = migratorPath;
initializeORM();
await OrmCLIRunner.start(args);
}
''';

void main(List<String> args) async {
final migratorDirectoryPath = path.join(Directory.current.path, '.dart_tool', 'yaroorm');
final dir = Directory(migratorDirectoryPath);
if (!dir.existsSync()) dir.createSync();

final dartFile = path.join(migratorDirectoryPath, 'migrator.dart');
final aotFilePath = path.join(migratorDirectoryPath, 'migrator');
final kernelFilePath = path.join(migratorDirectoryPath, 'migrator_kernel');

if (args.isNotEmpty && args[0] == 'init') {
await _initOrmInProject(Directory.current);
exit(0);
}
final migratorFile = File(dartFile);
final kernelFile = File(kernelFilePath);

if (!File(dartFile).existsSync()) {
logger.err('🗙 Migrator file does not exist');
exit(0);
final isInitCommand = args.isNotEmpty && args[0] == InitializeOrmCommand.commandName;
if (isInitCommand && kernelFile.existsSync()) {
kernelFile.delete();
}

final aotFile = File(aotFilePath);
if (!aotFile.existsSync()) {
/// TODO(codekeyz): add checksum check for invalidating aot
Process.start('dart', ['compile', 'exe', dartFile, '-o', aotFilePath], mode: ProcessStartMode.detached);
if (!migratorFile.existsSync()) {
await migratorFile.writeAsString(_migratorFileContent);
}

late Process process;

if (aotFile.existsSync()) {
process = await Process.start(aotFilePath, args);
if (kernelFile.existsSync()) {
process = await Process.start('dart', ['run', kernelFilePath, ...args]);
} else {
process = await Process.start('dart', ['run', dartFile, ...args]);
}

stdout.addStream(process.stdout);
stderr.addStream(process.stderr);
}

String get migratorPath {
return path.join(Directory.current.path, '.dart_tool', 'yaroorm/bin');
}

Future<void> _initOrmInProject(Directory workingDir) async {
// final progress = logger.progress('Initializing ORM in project');

final collection = AnalysisContextCollection(
includedPaths: [workingDir.absolute.path],
resourceProvider: PhysicalResourceProvider.INSTANCE,
);

List<Item> migrations = [];
List<Item> entities = [];

await for (final (library, _, _) in _libraries(collection)) {
final result = _validateLibrary(library, library.element.identifier);
if (result == null) continue;

if (result.migrations != null) {
migrations.add(result.migrations!);
}

if (result.entityClasses != null) {
entities.add(result.entityClasses!);
}
}

print(migrations.map((e) => (e.elements.map((e) => e.name), e.path)));
print(entities.map((e) => (e.elements.map((e) => e.name), e.path)));
}

TypeChecker _typeChecker(Type type) => TypeChecker.fromRuntime(type);

class Item {
final Iterable<ClassElement> elements;
final String path;

const Item(this.elements, this.path);
}

({Item? migrations, Item? entityClasses})? _validateLibrary(ResolvedLibraryResult library, String identifier) {
final classElements = library.element.topLevelElements
.where((e) => !e.isPrivate && e is ClassElement && e.supertype != null && !e.isAbstract)
.toList()
.cast<ClassElement>();

if (classElements.isEmpty) return null;

final migrationClasses = classElements.where((element) => _typeChecker(Migration).isExactlyType(element.supertype!));
final entityClasses = classElements.where((element) => _typeChecker(Entity).isExactlyType(element.supertype!));

return (
migrations: migrationClasses.isEmpty ? null : Item(migrationClasses, identifier),
entityClasses: entityClasses.isEmpty ? null : Item(entityClasses, identifier),
);
}

Stream<(ResolvedLibraryResult, String, String)> _libraries(AnalysisContextCollection collection) async* {
for (var context in collection.contexts) {
var analyzedFiles = context.contextRoot.analyzedFiles().toList();
analyzedFiles.sort();
final analyzedDartFiles = analyzedFiles.where((path) => path.endsWith('.dart') && !path.endsWith('_test.dart'));
for (final filePath in analyzedDartFiles) {
final library = await context.currentSession.getResolvedLibrary(filePath);
if (library is ResolvedLibraryResult) {
yield (library, filePath, context.contextRoot.root.path);
}
}
if (!isInitCommand && !kernelFile.existsSync()) {
/// TODO(codekeyz): add checksum check for invalidating kernel snapshot
Process.start('dart', ['compile', 'kernel', dartFile, '-o', kernelFilePath], mode: ProcessStartMode.detached);
}
}
2 changes: 1 addition & 1 deletion lib/builder.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'package:build/build.dart';

import 'src/generator.dart';
import 'src/builder/generator.dart';

/// Builds generators for `build_runner` to run
Builder yaroormBuilder(BuilderOptions options) => generatorFactoryBuilder(options);
Loading

0 comments on commit e90c739

Please sign in to comment.