Skip to content

Commit

Permalink
test(supabase): ensure supabase stores associations
Browse files Browse the repository at this point in the history
  • Loading branch information
tshedor committed Sep 6, 2024
1 parent 4a9a66c commit 6e14e78
Show file tree
Hide file tree
Showing 27 changed files with 1,075 additions and 292 deletions.
28 changes: 18 additions & 10 deletions example_supabase/lib/brick/adapters/customer_adapter.g.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,14 @@ Future<Customer> _$CustomerFromSupabase(Map<String, dynamic> data,

Future<Map<String, dynamic>> _$CustomerToSupabase(Customer instance,
{required SupabaseProvider provider, OfflineFirstWithSupabaseRepository? repository}) async {
return {'id': instance.id, 'first_name': instance.firstName, 'last_name': instance.lastName};
return {
'id': instance.id,
'first_name': instance.firstName,
'last_name': instance.lastName,
'pizzas': await Future.wait<Map<String, dynamic>>(instance.pizzas
.map((s) => PizzaAdapter().toSupabase(s, provider: provider, repository: repository))
.toList())
};
}

Future<Customer> _$CustomerFromSqlite(Map<String, dynamic> data,
Expand Down Expand Up @@ -51,7 +58,7 @@ class CustomerAdapter extends OfflineFirstWithSupabaseAdapter<Customer> {
CustomerAdapter();

@override
final tableName = 'customers';
final supabaseTableName = 'customers';
@override
final defaultToNull = true;
@override
Expand All @@ -71,6 +78,8 @@ class CustomerAdapter extends OfflineFirstWithSupabaseAdapter<Customer> {
'pizzas': const RuntimeSupabaseColumnDefinition(
association: true,
columnName: 'pizzas',
associationType: Pizza,
associationIsNullable: false,
)
};
@override
Expand Down Expand Up @@ -132,7 +141,7 @@ class CustomerAdapter extends OfflineFirstWithSupabaseAdapter<Customer> {
'SELECT `f_Pizza_brick_id` FROM `_brick_Customer_pizzas` WHERE `l_Customer_brick_id` = ?',
[instance.primaryKey]);
final pizzasOldIds = pizzasOldColumns.map((a) => a['f_Pizza_brick_id']);
final pizzasNewIds = instance.pizzas?.map((s) => s.primaryKey).whereType<int>() ?? [];
final pizzasNewIds = instance.pizzas.map((s) => s.primaryKey).whereType<int>();
final pizzasIdsToDelete = pizzasOldIds.where((id) => !pizzasNewIds.contains(id));

await Future.wait<void>(pizzasIdsToDelete.map((id) async {
Expand All @@ -141,13 +150,12 @@ class CustomerAdapter extends OfflineFirstWithSupabaseAdapter<Customer> {
[instance.primaryKey, id]).catchError((e) => null);
}));

await Future.wait<int?>(instance.pizzas?.map((s) async {
final id = s.primaryKey ?? await provider.upsert<Pizza>(s, repository: repository);
return await provider.rawInsert(
'INSERT OR IGNORE INTO `_brick_Customer_pizzas` (`l_Customer_brick_id`, `f_Pizza_brick_id`) VALUES (?, ?)',
[instance.primaryKey, id]);
}) ??
[]);
await Future.wait<int?>(instance.pizzas.map((s) async {
final id = s.primaryKey ?? await provider.upsert<Pizza>(s, repository: repository);
return await provider.rawInsert(
'INSERT OR IGNORE INTO `_brick_Customer_pizzas` (`l_Customer_brick_id`, `f_Pizza_brick_id`) VALUES (?, ?)',
[instance.primaryKey, id]);
}));
}
}

Expand Down
5 changes: 3 additions & 2 deletions example_supabase/lib/brick/adapters/pizza_adapter.g.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ Future<Pizza> _$PizzaFromSupabase(Map<String, dynamic> data,
{required SupabaseProvider provider, OfflineFirstWithSupabaseRepository? repository}) async {
return Pizza(
id: data['id'] as int,
toppings: data['toppings'].map(Topping.values.byName).toList().cast<Topping>(),
toppings:
data['toppings'].whereType<String>().map(Topping.values.byName).toList().cast<Topping>(),
frozen: data['frozen'] as bool);
}

Expand Down Expand Up @@ -45,7 +46,7 @@ class PizzaAdapter extends OfflineFirstWithSupabaseAdapter<Pizza> {
PizzaAdapter();

@override
final tableName = 'pizzas';
final supabaseTableName = 'pizzas';
@override
final defaultToNull = true;
@override
Expand Down
52 changes: 0 additions & 52 deletions example_supabase/lib/brick/db/20200121222037.migration.dart

This file was deleted.

48 changes: 0 additions & 48 deletions example_supabase/lib/brick/db/20210111042657.migration.dart

This file was deleted.

74 changes: 74 additions & 0 deletions example_supabase/lib/brick/db/20240906052847.migration.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// GENERATED CODE EDIT WITH CAUTION
// THIS FILE **WILL NOT** BE REGENERATED
// This file should be version controlled and can be manually edited.
part of 'schema.g.dart';

// While migrations are intelligently created, the difference between some commands, such as
// DropTable vs. RenameTable, cannot be determined. For this reason, please review migrations after
// they are created to ensure the correct inference was made.

// The migration version must **always** mirror the file name

const List<MigrationCommand> _migration_20240906052847_up = [
InsertTable('_brick_Customer_pizzas'),
InsertTable('Customer'),
InsertTable('Pizza'),
InsertForeignKey(
'_brick_Customer_pizzas',
'Customer',
foreignKeyColumn: 'l_Customer_brick_id',
onDeleteCascade: true,
onDeleteSetDefault: false,
),
InsertForeignKey(
'_brick_Customer_pizzas',
'Pizza',
foreignKeyColumn: 'f_Pizza_brick_id',
onDeleteCascade: true,
onDeleteSetDefault: false,
),
InsertColumn('id', Column.integer, onTable: 'Customer', unique: true),
InsertColumn('first_name', Column.varchar, onTable: 'Customer'),
InsertColumn('last_name', Column.varchar, onTable: 'Customer'),
InsertColumn('id', Column.integer, onTable: 'Pizza', unique: true),
InsertColumn('toppings', Column.varchar, onTable: 'Pizza'),
InsertColumn('frozen', Column.boolean, onTable: 'Pizza'),
CreateIndex(
columns: ['l_Customer_brick_id', 'f_Pizza_brick_id'],
onTable: '_brick_Customer_pizzas',
unique: true,
),
];

const List<MigrationCommand> _migration_20240906052847_down = [
DropTable('_brick_Customer_pizzas'),
DropTable('Customer'),
DropTable('Pizza'),
DropColumn('l_Customer_brick_id', onTable: '_brick_Customer_pizzas'),
DropColumn('f_Pizza_brick_id', onTable: '_brick_Customer_pizzas'),
DropColumn('id', onTable: 'Customer'),
DropColumn('first_name', onTable: 'Customer'),
DropColumn('last_name', onTable: 'Customer'),
DropColumn('id', onTable: 'Pizza'),
DropColumn('toppings', onTable: 'Pizza'),
DropColumn('frozen', onTable: 'Pizza'),
DropIndex('index__brick_Customer_pizzas_on_l_Customer_brick_id_f_Pizza_brick_id'),
];

//
// DO NOT EDIT BELOW THIS LINE
//

@Migratable(
version: '20240906052847',
up: _migration_20240906052847_up,
down: _migration_20240906052847_down,
)
class Migration20240906052847 extends Migration {
const Migration20240906052847()
: super(
version: 20240906052847,
up: _migration_20240906052847_up,
down: _migration_20240906052847_down,
);
}
9 changes: 5 additions & 4 deletions example_supabase/lib/brick/db/schema.g.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
// GENERATED CODE DO NOT EDIT
// This file should be version controlled
import 'package:brick_sqlite/db.dart';
part '20210111042657.migration.dart';
part '20200121222037.migration.dart';
part '20240906052847.migration.dart';

/// All intelligently-generated migrations from all `@Migratable` classes on disk
final migrations = <Migration>{const Migration20210111042657(), const Migration20200121222037()};
final migrations = <Migration>{
const Migration20240906052847(),
};

/// A consumable database structure including the latest generated migration.
final schema = Schema(20210111042657, generatorVersion: 1, tables: <SchemaTable>{
final schema = Schema(20240906052847, generatorVersion: 1, tables: <SchemaTable>{
SchemaTable('_brick_Customer_pizzas', columns: <SchemaColumn>{
SchemaColumn('_brick_id', Column.integer,
autoincrement: true, nullable: false, isPrimaryKey: true),
Expand Down
4 changes: 2 additions & 2 deletions example_supabase/lib/brick/models/customer.model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ class Customer extends OfflineFirstWithSupabaseModel {

final String? lastName;

final List<Pizza>? pizzas;
final List<Pizza> pizzas;

Customer({
this.id,
this.firstName,
this.lastName,
this.pizzas,
required this.pizzas,
});
}
12 changes: 10 additions & 2 deletions example_supabase/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
brick_supabase:
brick_offline_first_with_supabase:
sqflite:
supabase_flutter:
Expand All @@ -27,10 +26,19 @@ dependency_overrides:
path: ../packages/brick_sqlite_generators
brick_offline_first_with_supabase_build:
path: ../packages/brick_offline_first_with_supabase_build
brick_build:
path: ../packages/brick_build
brick_supabase_generators:
path: ../packages/brick_supabase_generators
brick_offline_first_build:
path: ../packages/brick_offline_first_build
brick_offline_first_with_rest:
path: ../packages/brick_offline_first_with_rest
brick_json_generators:
path: ../packages/brick_json_generators

dev_dependencies:
brick_offline_first_with_supabase_build:

build_runner: any
shelf: ^1.1.0

Expand Down
4 changes: 4 additions & 0 deletions packages/brick_build/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## Unreleased

## 3.2.1

- Revert `.getDisplayString()` change due to Flutter 3.22 being restricted to analyzer <6.4.1. `meta` is pinned to `1.12` in this version of Flutter, and `analyzer >=6.5.0`, where the change was made, requires `meta >= 1.15`. This change will eventually be re-reverted.

## 3.2.0

- Add convenience mixin `AnnotationFinderWithFieldRename` for field renames in generators
Expand Down
5 changes: 3 additions & 2 deletions packages/brick_build/lib/src/utils/shared_checker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ class SharedChecker<_SiblingModel extends Model> {
if (classElement.supertype?.typeArguments == null ||
classElement.supertype!.typeArguments.isEmpty) {
throw InvalidGenerationSourceError(
'Type argument for ${targetType.getDisplayString()} is undefined.',
'Type argument for ${targetType.getDisplayString(withNullability: true)} is undefined.',
todo:
'Define the type on class ${targetType.element}, e.g. `extends ${withoutNullability(classElement.supertype!)}<int>`',
element: targetType.element,
Expand Down Expand Up @@ -243,7 +243,8 @@ class SharedChecker<_SiblingModel extends Model> {
}

/// Print the `DartType` without nullability
static String withoutNullability(DartType type) => type.getDisplayString().replaceAll('?', '');
static String withoutNullability(DartType type) =>
type.getDisplayString(withNullability: true).replaceAll('?', '');

/// Destructs a type to determine the bottom type after going through Futures and Iterables.
///
Expand Down
2 changes: 1 addition & 1 deletion packages/brick_build/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ homepage: https://github.com/GetDutchie/brick/tree/main/packages/brick_build
issue_tracker: https://github.com/GetDutchie/brick/issues
repository: https://github.com/GetDutchie/brick

version: 3.2.0
version: 3.2.1

environment:
sdk: ">=2.18.0 <4.0.0"
Expand Down
3 changes: 2 additions & 1 deletion packages/brick_json_generators/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
## Unreleased

- (test) remove analysis options override for non-standard library prefixes
- Revert `.getDisplayString()` change due to Flutter 3.22 being restricted to analyzer <6.4.1. `meta` is pinned to `1.12` in this version of Flutter, and `analyzer >=6.5.0`, where the change was made, requires `meta >= 1.15`. This change will eventually be re-reverted.

## 3.1.0
## 3.1.1

- Apply standardized lints
- Update `analyzer` constraints to `>=6.0.0 <7.0.0`
Expand Down
4 changes: 2 additions & 2 deletions packages/brick_json_generators/lib/json_deserialize.dart
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ mixin JsonDeserialize<TModel extends Model, Annotation extends FieldSerializable
final nullableSuffix = checker.isNullable ? '?' : '';

return '''$fieldValue$nullableSuffix.map(
(d) => ${klass.displayName}.fromJson(d as ${parameterType.getDisplayString()})
(d) => ${klass.displayName}.fromJson(d as ${parameterType.getDisplayString(withNullability: true)})
)$castIterable$defaultValue''';
}

Expand Down Expand Up @@ -138,7 +138,7 @@ mixin JsonDeserialize<TModel extends Model, Annotation extends FieldSerializable
final parameterType = checker.fromJsonConstructor!.parameters.first.type;

final output =
'${klass.displayName}.fromJson($fieldValue as ${parameterType.getDisplayString()})';
'${klass.displayName}.fromJson($fieldValue as ${parameterType.getDisplayString(withNullability: true)})';
if (checker.isNullable) return '$fieldValue != null ? $output : null';
return output;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/brick_json_generators/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ homepage: https://github.com/GetDutchie/brick/tree/main/packages/brick_json_gene
issue_tracker: https://github.com/GetDutchie/brick/issues
repository: https://github.com/GetDutchie/brick

version: 3.1.0
version: 3.1.1

environment:
sdk: ">=2.18.0 <4.0.0"
Expand Down
Loading

0 comments on commit 6e14e78

Please sign in to comment.