diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 09fc04c74..00bd35aac 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -72,11 +72,11 @@ jobs: continue fi case "$package" in - postgrest|supabase|supabase_auth|supabase_realtime|supabase_storage) backend=true ;; + postgrest|supabase|supabase_auth|supabase_realtime|supabase_storage|supabase_typegen) backend=true ;; *) backend=false ;; esac case "$package" in - postgrest|supabase|supabase_auth|supabase_realtime|supabase_storage) concurrency="1" ;; + postgrest|supabase|supabase_auth|supabase_realtime|supabase_storage|supabase_typegen) concurrency="1" ;; *) concurrency="0" ;; esac entries+=("{\"name\":\"$package\",\"backend\":$backend,\"concurrency\":\"$concurrency\"}") diff --git a/AGENTS.md b/AGENTS.md index 900ff6d5b..886ba3196 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,9 +53,9 @@ melos format ### Testing -Most packages have unit tests. The `postgrest`, `supabase_auth`, `supabase_realtime`, and `supabase_storage` packages run against a local Supabase stack started with the Supabase CLI. This requires Docker and the [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started) installed. +Most packages have unit tests. The `postgrest`, `supabase`, `supabase_auth`, `supabase_realtime`, `supabase_storage`, and `supabase_typegen` packages run against a local Supabase stack started with the Supabase CLI. This requires Docker and the [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started) installed. -**For packages requiring a backend (postgrest, supabase_auth, supabase_realtime, supabase_storage):** +**For packages requiring a backend (postgrest, supabase, supabase_auth, supabase_realtime, supabase_storage, supabase_typegen):** ```bash # 1. Start the local Supabase stack from the repository root @@ -69,7 +69,7 @@ dart test -j 1 supabase stop ``` -The single `supabase/` config at the repository root serves every package: its migrations and `seed.sql` create the schemas, functions, and test data all four packages rely on. The stack binds ports 14420 to 14429 (gateway on `http://127.0.0.1:14421`, database on `127.0.0.1:14422`), off the CLI defaults so it can run alongside another local Supabase project and below Linux's default ephemeral port range so an outgoing connection cannot claim a port the stack still needs to bind. +The single `supabase/` config at the repository root serves every package: its migrations and `seed.sql` create the schemas, functions, and test data these packages rely on. The stack binds ports 14420 to 14429 (gateway on `http://127.0.0.1:14421`, database on `127.0.0.1:14422`), off the CLI defaults so it can run alongside another local Supabase project and below Linux's default ephemeral port range so an outgoing connection cannot claim a port the stack still needs to bind. The `-j 1` flag runs tests sequentially (not concurrently), which is required since tests share the same backend. diff --git a/packages/supabase_typegen/lib/src/dart_generator.dart b/packages/supabase_typegen/lib/src/dart_generator.dart index 9babe8b92..637a15093 100644 --- a/packages/supabase_typegen/lib/src/dart_generator.dart +++ b/packages/supabase_typegen/lib/src/dart_generator.dart @@ -129,13 +129,20 @@ String generateDartCode( typeNames.taken, ), }; + final relationshipCounts = _relationshipCounts(database); for (final table in tables) { _writeTable( buffer, table, tableNames[(table.schema, table.name)]!, tableMembers[(table.schema, table.name)]!, - _relationMembers(table, database, tableNames, tableMembers), + _relationMembers( + table, + database, + tableNames, + tableMembers, + relationshipCounts, + ), typeNames.taken, enumTypeNames, decoders, @@ -435,8 +442,9 @@ class _RelationMember { /// relationship. String get key => isComputed ? embedName : referencedTable; - /// Whether another key joins the same two tables, so the embed carries a - /// hint and is aliased to the member name to come back under its own key. + /// Whether PostgREST sees another relationship between the same two + /// tables, so the embed carries a hint. A hinted embed is always aliased; + /// one whose [key] is a column or computed field name is aliased too. final bool ambiguous; /// The column constants of this table the relation joins on. @@ -472,6 +480,7 @@ List<_RelationMember> _relationMembers( DatabaseDescription database, Map<(String, String), _TableNames> tableNames, Map<(String, String), _TableMembers> tableMembers, + Map<_TablePair, int> relationshipCounts, ) { final members = <_RelationMember>[]; for (final relationship in database.relationships) { @@ -499,14 +508,9 @@ List<_RelationMember> _relationMembers( // holds. final byColumns = 'By${pascalCase(columns)}'; final viaColumns = 'Via${pascalCase(columns)}'; - // Several keys between the same two tables make the plain table name - // ambiguous for PostgREST, so the embed carries the hint. - final ambiguous = database.relationships.any( - (other) => - other != relationship && - (other.sourceSchema, other.sourceTable) == sourceKey && - (other.targetSchema, other.targetTable) == targetKey, - ); + // Several relationships between the same two tables make the plain + // table name ambiguous for PostgREST, so the embed carries the hint. + final ambiguous = relationshipCounts[_tablePair(sourceKey, targetKey)]! > 1; if (sourceKey == (table.schema, table.name)) { final targetName = memberIdentifier(relationship.targetTable); @@ -576,6 +580,58 @@ List<_RelationMember> _relationMembers( return members; } +/// Two tables in a fixed order, so both directions share one key. +typedef _TablePair = ((String, String), (String, String)); + +_TablePair _tablePair((String, String) first, (String, String) second) { + final schemaOrder = first.$1.compareTo(second.$1); + final inOrder = + schemaOrder < 0 || + (schemaOrder == 0 && first.$2.compareTo(second.$2) <= 0); + return inOrder ? (first, second) : (second, first); +} + +/// The number of relationships PostgREST sees between each pair of tables: +/// the foreign keys in either direction, and the many-to-many relationships +/// through a junction table whose primary key covers a foreign key to each +/// of the two. +Map<_TablePair, int> _relationshipCounts(DatabaseDescription database) { + final counts = <_TablePair, int>{}; + void count(_TablePair pair) => + counts.update(pair, (count) => count + 1, ifAbsent: () => 1); + for (final relationship in database.relationships) { + count( + _tablePair( + (relationship.sourceSchema, relationship.sourceTable), + (relationship.targetSchema, relationship.targetTable), + ), + ); + } + for (final junction in database.tables) { + final primaryKey = junction.primaryKey.toSet(); + final keys = [ + for (final relationship in database.relationships) + if (relationship.sourceSchema == junction.schema && + relationship.sourceTable == junction.name && + relationship.targetSchema == junction.schema && + relationship.targetTable != junction.name && + primaryKey.containsAll(relationship.sourceColumns)) + relationship, + ]; + for (final (index, first) in keys.indexed) { + for (final second in keys.skip(index + 1)) { + count( + _tablePair( + (first.targetSchema, first.targetTable), + (second.targetSchema, second.targetTable), + ), + ); + } + } + } + return counts; +} + /// The column constants of [columns] in the namespace of [table]. /// /// A key over a column the document does not list for its table is a @@ -618,7 +674,7 @@ void _writeTable( field.name: _bindingFor(_computedFieldShape(field), enumTypeNames), }; final relationNames = _relationNames(typeNames, members, relations); - final relationKeys = _embedKeys(relations, relationNames); + final relationAliases = _embedAliases(table, relations, relationNames); _writeRow( buffer, @@ -672,7 +728,7 @@ void _writeTable( computedFieldBindings, relations, relationNames, - relationKeys, + relationAliases, decoders, ); } @@ -710,24 +766,35 @@ List _relationNames( ]; } -/// The keys the embedded rows of [relations] come back under: the table name -/// for a plain embed, the function name for a computed relationship and, for -/// a hinted one, an alias made of the member name in snake case, kept apart -/// from every other key of the table. -List _embedKeys( +/// The aliases of [relations], or `null` for a relation that comes back under +/// its plain key: the table name for a foreign key embed, the function name +/// for a computed relationship. +/// +/// A hinted embed is aliased to its member name in snake case, and so is an +/// embed whose plain key is also the name of a column or computed field of +/// [table], which would otherwise come back under the same key. Aliases are +/// kept apart from every other key of the table. +List _embedAliases( + TableDescription table, List<_RelationMember> relations, List relationNames, ) { + final fieldNames = { + for (final column in table.columns) column.name, + for (final field in table.computedFields) field.name, + }; + bool needsAlias(_RelationMember relation) => + relation.ambiguous || fieldNames.contains(relation.key); final used = { + ...fieldNames, for (final relation in relations) - if (!relation.ambiguous) relation.key, + if (!needsAlias(relation)) relation.key, }; return [ for (final (index, relation) in relations.indexed) - if (relation.ambiguous) - _claimAlias(used, snakeCase(relationNames[index])) - else - relation.key, + needsAlias(relation) + ? _claimAlias(used, snakeCase(relationNames[index])) + : null, ]; } @@ -852,7 +919,7 @@ void _writeNamespace( Map computedFieldBindings, List<_RelationMember> relations, List relationNames, - List relationKeys, + List relationAliases, _DecoderRegistry decoders, ) { final _TableNames(:rowType, :insertType, :updateType, :namespaceType) = names; @@ -935,8 +1002,8 @@ void _writeNamespace( ' referencedColumns: [${relation.referencedColumns.join(', ')}],', ); } - if (relation.ambiguous) { - buffer.writeln(' alias: ${_stringLiteral(relationKeys[index])},'); + if (relationAliases[index] case final alias?) { + buffer.writeln(' alias: ${_stringLiteral(alias)},'); } buffer.writeln(' );'); } diff --git a/packages/supabase_typegen/pubspec.yaml b/packages/supabase_typegen/pubspec.yaml index a11f941e1..5e74c4b4c 100644 --- a/packages/supabase_typegen/pubspec.yaml +++ b/packages/supabase_typegen/pubspec.yaml @@ -26,6 +26,7 @@ dependencies: dev_dependencies: postgrest: 3.0.0-dev.12 + supabase_common: 3.0.0-dev.8 supabase_lints: ^0.1.2 supabase_test: 0.5.2 test: ^1.25.0 diff --git a/packages/supabase_typegen/test/dart_generator_test.dart b/packages/supabase_typegen/test/dart_generator_test.dart index 0dd7d3b99..a178463a0 100644 --- a/packages/supabase_typegen/test/dart_generator_test.dart +++ b/packages/supabase_typegen/test/dart_generator_test.dart @@ -610,6 +610,123 @@ void main() { ); }); + test('keys in opposite directions both carry the hint', () { + final compact = _normalize( + generateDartCode(hostileSchema), + ).replaceAll(' ', ''); + + expect( + compact, + contains( + "staticconstteamByTeam=PostgrestToOneRelation" + "('team!profile_team_fkey',", + ), + ); + expect( + compact, + contains( + "staticconstteamViaOwnerId=PostgrestToManyRelation('team!team_owner_id_fkey',", + ), + ); + expect( + compact, + contains( + "staticconstprofileByOwnerId=PostgrestToOneRelation('profile!team_owner_id_fkey',", + ), + ); + expect( + compact, + contains( + "staticconstprofileViaTeam=PostgrestToManyRelation('profile!profile_team_fkey',", + ), + ); + }); + + test('a junction table makes a single key ambiguous', () { + final compact = _normalize( + generateDartCode(hostileSchema), + ).replaceAll(' ', ''); + + expect( + compact, + contains( + "staticconstteamByTeam=PostgrestToOneRelation" + "('team!badge_team_fkey',", + ), + ); + expect( + compact, + contains( + "staticconstbadgeViaTeam=PostgrestToManyRelation" + "('badge!badge_team_fkey',", + ), + ); + expect( + compact, + contains( + "staticconstteam=PostgrestToOneRelation" + "('team',", + ), + ); + }); + + test('a junction table needs its primary key to cover both keys', () { + final withoutJunction = DatabaseDescription( + schemaNames: hostileSchema.schemaNames, + tables: [ + for (final table in hostileSchema.tables) + if (table.name == 'team_badge') + TableDescription( + schema: table.schema, + name: table.name, + primaryKey: const ['team_id'], + columns: table.columns, + ) + else + table, + ], + enums: hostileSchema.enums, + relationships: hostileSchema.relationships, + ); + final compact = _normalize( + generateDartCode(withoutJunction), + ).replaceAll(' ', ''); + + expect( + compact, + contains( + "staticconstteamByTeam=PostgrestToOneRelation" + "('team',", + ), + ); + }); + + test('an embed whose key is a column name is aliased', () { + final compact = _normalize( + generateDartCode(hostileSchema), + ).replaceAll(' ', ''); + + expect( + compact, + contains( + "staticconstprofileByProfile=PostgrestToOneRelation('profile',columns:[profile],referencedTable:'profile'," + "referencedColumns:[Profile.id],alias:'profile_by_profile',);", + ), + ); + expect( + compact, + contains( + "staticconstbadge=PostgrestToManyRelation" + "('badge',columns:[id],referencedTable:'badge'," + "referencedColumns:[Badge.profile],);", + ), + ); + }); + test('aliases of relations that share a member name stay distinct', () { // Two constraints over the same columns claim `mapByMood` and // `mapByMood$`, which snake case alone would both turn into `map_by_mood`. diff --git a/packages/supabase_typegen/test/generated_embeds_integration_test.dart b/packages/supabase_typegen/test/generated_embeds_integration_test.dart new file mode 100644 index 000000000..47a396651 --- /dev/null +++ b/packages/supabase_typegen/test/generated_embeds_integration_test.dart @@ -0,0 +1,161 @@ +// The typed table access API under test is annotated @experimental. +// ignore_for_file: experimental_member_use + +import 'package:postgrest/postgrest.dart'; +import 'package:supabase_common/testing.dart'; +import 'package:test/test.dart'; + +import 'goldens/hostile_schema.dart'; + +/// Embeds the relations generated in the hostile golden against the tables +/// of the same shape the local stack defines in +/// `supabase/migrations/20240101000005_embed_disambiguation.sql`. +void main() { + late PostgrestClient client; + + setUp(() { + client = PostgrestClient( + localStackRestUrl, + headers: { + 'apikey': localStackServiceRoleKey, + 'Authorization': 'Bearer $localStackServiceRoleKey', + }, + ); + }); + + tearDown(() async { + await client.dispose(); + }); + + test('embeds of keys in opposite directions resolve separately', () async { + final profiles = await client + .table(Profile.table) + .selectOnly([ + Profile.id, + Profile.team, + Profile.teamByTeam.select([Team.name]), + Profile.teamViaOwnerId.select([Team.name]), + ]) + .order(Profile.id); + + expect( + [for (final profile in profiles) profile.read(Profile.team)], + [ + 1, + 1, + null, + ], + ); + expect( + [ + for (final profile in profiles) + profile.read(Profile.teamByTeam)?.read(Team.name), + ], + ['Rockets', 'Rockets', null], + ); + expect( + [ + for (final profile in profiles) + [ + for (final team in profile.read(Profile.teamViaOwnerId)) + team.read(Team.name), + ], + ], + [ + ['Comets'], + ['Rockets'], + [], + ], + ); + }); + + test('the other side of opposite keys resolves separately', () async { + final teams = await client + .table(Team.table) + .selectOnly([ + Team.profileViaTeam.select([Profile.name]), + Team.profileByOwnerId.select([Profile.name]), + ]) + .order(Team.id); + + expect( + [ + for (final team in teams) + [ + for (final profile in team.read(Team.profileViaTeam)) + profile.read(Profile.name), + ]..sort(), + ], + [ + ['Ada', 'Grace'], + [], + ], + ); + expect( + [ + for (final team in teams) + team.read(Team.profileByOwnerId)?.read(Profile.name), + ], + ['Grace', 'Ada'], + ); + }); + + test('an embed named like a column keeps the column readable', () async { + final badges = await client + .table(Badge.table) + .selectOnly([ + Badge.profile, + Badge.profileByProfile.select([Profile.name]), + ]) + .order(Badge.id); + + expect([for (final badge in badges) badge.read(Badge.profile)], [1, 1]); + expect( + [ + for (final badge in badges) + badge.read(Badge.profileByProfile)?.read(Profile.name), + ], + ['Ada', 'Ada'], + ); + }); + + test('a key next to a junction table resolves', () async { + final badges = await client + .table(Badge.table) + .selectOnly([ + Badge.team, + Badge.teamByTeam.select([Team.name]), + ]) + .order(Badge.id); + + expect([for (final badge in badges) badge.read(Badge.team)], [1, null]); + expect( + [ + for (final badge in badges) + badge.read(Badge.teamByTeam)?.read(Team.name), + ], + ['Rockets', null], + ); + + final teams = await client + .table(Team.table) + .selectOnly([ + Team.badgeViaTeam.select([Badge.name]), + ]) + .order(Team.id); + + expect( + [ + for (final team in teams) + [ + for (final badge in team.read(Team.badgeViaTeam)) + badge.read(Badge.name), + ], + ], + [ + ['Founder'], + [], + ], + ); + }); +} diff --git a/packages/supabase_typegen/test/goldens/hostile_fixture.dart b/packages/supabase_typegen/test/goldens/hostile_fixture.dart index 11d15af8f..b2c1bff62 100644 --- a/packages/supabase_typegen/test/goldens/hostile_fixture.dart +++ b/packages/supabase_typegen/test/goldens/hostile_fixture.dart @@ -599,6 +599,137 @@ const DatabaseDescription hostileSchema = DatabaseDescription( ), ], ), + // Joined to profile by keys in both directions, and loaded by the + // embedding integration test from the local stack. + TableDescription( + schema: 'public', + name: 'team', + primaryKey: ['id'], + columns: [ + ColumnDescription( + name: 'id', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: false, + hasDefault: true, + isNullable: false, + ), + ColumnDescription( + name: 'name', + postgresFormat: 'text', + typeKind: ColumnTypeKind.text, + isRequired: true, + hasDefault: false, + isNullable: false, + ), + ColumnDescription( + name: 'owner_id', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: false, + hasDefault: false, + isNullable: true, + ), + ], + ), + // Its key into team is a column named like the table it references. + TableDescription( + schema: 'public', + name: 'profile', + primaryKey: ['id'], + columns: [ + ColumnDescription( + name: 'id', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: false, + hasDefault: true, + isNullable: false, + ), + ColumnDescription( + name: 'name', + postgresFormat: 'text', + typeKind: ColumnTypeKind.text, + isRequired: true, + hasDefault: false, + isNullable: false, + ), + ColumnDescription( + name: 'team', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: false, + hasDefault: false, + isNullable: true, + ), + ], + ), + // A single key into profile, through a column named like the table, and + // a key into team next to the junction table between the two. + TableDescription( + schema: 'public', + name: 'badge', + primaryKey: ['id'], + columns: [ + ColumnDescription( + name: 'id', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: false, + hasDefault: true, + isNullable: false, + ), + ColumnDescription( + name: 'name', + postgresFormat: 'text', + typeKind: ColumnTypeKind.text, + isRequired: true, + hasDefault: false, + isNullable: false, + ), + ColumnDescription( + name: 'profile', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: true, + hasDefault: false, + isNullable: false, + ), + ColumnDescription( + name: 'team', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: false, + hasDefault: false, + isNullable: true, + ), + ], + ), + // A junction table between team and badge, whose primary key covers both + // keys. + TableDescription( + schema: 'public', + name: 'team_badge', + primaryKey: ['team_id', 'badge_id'], + columns: [ + ColumnDescription( + name: 'team_id', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: true, + hasDefault: false, + isNullable: false, + ), + ColumnDescription( + name: 'badge_id', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: true, + hasDefault: false, + isNullable: false, + ), + ], + ), ], relationships: [ // A self reference: PostgREST cannot embed it, so no member is generated. @@ -642,6 +773,65 @@ const DatabaseDescription hostileSchema = DatabaseDescription( targetColumns: ['list'], isOneToOne: true, ), + // Keys in opposite directions between two tables: the plain table name + // is ambiguous either way, and the embed key of the first is a column. + RelationshipDescription( + foreignKeyName: 'profile_team_fkey', + sourceSchema: 'public', + sourceTable: 'profile', + sourceColumns: ['team'], + targetSchema: 'public', + targetTable: 'team', + targetColumns: ['id'], + ), + RelationshipDescription( + foreignKeyName: 'team_owner_id_fkey', + sourceSchema: 'public', + sourceTable: 'team', + sourceColumns: ['owner_id'], + targetSchema: 'public', + targetTable: 'profile', + targetColumns: ['id'], + ), + // The only key between the two tables, but its embed key is a column. + RelationshipDescription( + foreignKeyName: 'badge_profile_fkey', + sourceSchema: 'public', + sourceTable: 'badge', + sourceColumns: ['profile'], + targetSchema: 'public', + targetTable: 'profile', + targetColumns: ['id'], + ), + // A single key, but the junction table makes a second relationship + // between badge and team. + RelationshipDescription( + foreignKeyName: 'badge_team_fkey', + sourceSchema: 'public', + sourceTable: 'badge', + sourceColumns: ['team'], + targetSchema: 'public', + targetTable: 'team', + targetColumns: ['id'], + ), + RelationshipDescription( + foreignKeyName: 'team_badge_team_id_fkey', + sourceSchema: 'public', + sourceTable: 'team_badge', + sourceColumns: ['team_id'], + targetSchema: 'public', + targetTable: 'team', + targetColumns: ['id'], + ), + RelationshipDescription( + foreignKeyName: 'team_badge_badge_id_fkey', + sourceSchema: 'public', + sourceTable: 'team_badge', + sourceColumns: ['badge_id'], + targetSchema: 'public', + targetTable: 'badge', + targetColumns: ['id'], + ), ], functions: [ // Named like the method a call of `client.rpc` goes through. diff --git a/packages/supabase_typegen/test/goldens/hostile_schema.dart b/packages/supabase_typegen/test/goldens/hostile_schema.dart index 4b4e2b5d5..7ea414c7d 100644 --- a/packages/supabase_typegen/test/goldens/hostile_schema.dart +++ b/packages/supabase_typegen/test/goldens/hostile_schema.dart @@ -1,4 +1,4 @@ -// Generated by supabase_typegen 0.5.2 from GeneratorMetadata version 1. +// Generated by supabase_typegen 0.6.0 from GeneratorMetadata version 1. // Do not edit by hand. // // Source schemas: evil multiline "schema" name, private, public @@ -1408,6 +1408,327 @@ class PrivateAchievementItemProgressTbl { PostgrestColumn('name'); } +/// A row of the `team` table, as `select()` reads it with every column. +extension type const TeamRow(Map _json) implements Object { + int get id => _json['id'] as int; + String get name => _json['name'] as String; + int? get ownerId => _json['owner_id'] as int?; + + /// The row as decoded from the response. + Map toJson() => _json; +} + +/// Values for inserting a row into `team`. Columns that are nullable, identity, +/// or covered by a database default are optional; passing `null` omits the +/// column so the database default applies. Columns the database always +/// generates itself are left out entirely. Use the `set…ToNull` methods to +/// insert SQL NULL explicitly. +extension type const TeamInsert._(Map _json) + implements Object { + TeamInsert({int? id, required String name, int? ownerId}) + : this._({'id': ?id, 'name': name, 'owner_id': ?ownerId}); + + /// Returns a copy with `owner_id` set to SQL NULL, overriding any database + /// default. + TeamInsert setOwnerIdToNull() => TeamInsert._({..._json, 'owner_id': null}); +} + +/// Values for updating rows of `team`. All columns are optional; passing `null` +/// omits the column, leaving it unchanged. Use the `set…ToNull` methods to +/// write SQL NULL explicitly. +extension type const TeamUpdate._(Map _json) + implements Object { + TeamUpdate({int? id, String? name, int? ownerId}) + : this._({'id': ?id, 'name': ?name, 'owner_id': ?ownerId}); + + /// Returns a copy with `owner_id` set to SQL NULL, overriding any database + /// default. + TeamUpdate setOwnerIdToNull() => TeamUpdate._({..._json, 'owner_id': null}); +} + +/// Typed access to the `team` table. +class Team { + const Team._(); + + /// Table definition for [PostgrestClient.table]. + static const table = PostgrestTable( + 'team', + TeamRow.new, + schema: 'public', + primaryKey: [id], + relations: [profileViaTeam, profileByOwnerId, badgeViaTeam, teamBadge], + ); + + static const id = PostgrestColumn('id'); + static const name = PostgrestColumn('name'); + static const ownerId = PostgrestNullableColumn('owner_id'); + + /// The `profile` rows referencing this row through `team`. + static const profileViaTeam = PostgrestToManyRelation( + 'profile!profile_team_fkey', + columns: [id], + referencedTable: 'profile', + referencedColumns: [Profile.team], + alias: 'profile_via_team', + ); + + /// The `profile` row referenced by `owner_id`. + static const profileByOwnerId = PostgrestToOneRelation( + 'profile!team_owner_id_fkey', + columns: [ownerId], + referencedTable: 'profile', + referencedColumns: [Profile.id], + alias: 'profile_by_owner_id', + ); + + /// The `badge` rows referencing this row through `team`. + static const badgeViaTeam = PostgrestToManyRelation( + 'badge!badge_team_fkey', + columns: [id], + referencedTable: 'badge', + referencedColumns: [Badge.team], + alias: 'badge_via_team', + ); + + /// The `team_badge` rows referencing this row through `team_id`. + static const teamBadge = PostgrestToManyRelation( + 'team_badge', + columns: [id], + referencedTable: 'team_badge', + referencedColumns: [TeamBadge.teamId], + ); +} + +/// A row of the `profile` table, as `select()` reads it with every column. +extension type const ProfileRow(Map _json) implements Object { + int get id => _json['id'] as int; + String get name => _json['name'] as String; + int? get team => _json['team'] as int?; + + /// The row as decoded from the response. + Map toJson() => _json; +} + +/// Values for inserting a row into `profile`. Columns that are nullable, +/// identity, or covered by a database default are optional; passing `null` +/// omits the column so the database default applies. Columns the database +/// always generates itself are left out entirely. Use the `set…ToNull` methods +/// to insert SQL NULL explicitly. +extension type const ProfileInsert._(Map _json) + implements Object { + ProfileInsert({int? id, required String name, int? team}) + : this._({'id': ?id, 'name': name, 'team': ?team}); + + /// Returns a copy with `team` set to SQL NULL, overriding any database + /// default. + ProfileInsert setTeamToNull() => ProfileInsert._({..._json, 'team': null}); +} + +/// Values for updating rows of `profile`. All columns are optional; passing +/// `null` omits the column, leaving it unchanged. Use the `set…ToNull` methods +/// to write SQL NULL explicitly. +extension type const ProfileUpdate._(Map _json) + implements Object { + ProfileUpdate({int? id, String? name, int? team}) + : this._({'id': ?id, 'name': ?name, 'team': ?team}); + + /// Returns a copy with `team` set to SQL NULL, overriding any database + /// default. + ProfileUpdate setTeamToNull() => ProfileUpdate._({..._json, 'team': null}); +} + +/// Typed access to the `profile` table. +class Profile { + const Profile._(); + + /// Table definition for [PostgrestClient.table]. + static const table = PostgrestTable( + 'profile', + ProfileRow.new, + schema: 'public', + primaryKey: [id], + relations: [teamByTeam, teamViaOwnerId, badge], + ); + + static const id = PostgrestColumn('id'); + static const name = PostgrestColumn('name'); + static const team = PostgrestNullableColumn('team'); + + /// The `team` row referenced by `team`. + static const teamByTeam = PostgrestToOneRelation( + 'team!profile_team_fkey', + columns: [team], + referencedTable: 'team', + referencedColumns: [Team.id], + alias: 'team_by_team', + ); + + /// The `team` rows referencing this row through `owner_id`. + static const teamViaOwnerId = PostgrestToManyRelation( + 'team!team_owner_id_fkey', + columns: [id], + referencedTable: 'team', + referencedColumns: [Team.ownerId], + alias: 'team_via_owner_id', + ); + + /// The `badge` rows referencing this row through `profile`. + static const badge = PostgrestToManyRelation( + 'badge', + columns: [id], + referencedTable: 'badge', + referencedColumns: [Badge.profile], + ); +} + +/// A row of the `badge` table, as `select()` reads it with every column. +extension type const BadgeRow(Map _json) implements Object { + int get id => _json['id'] as int; + String get name => _json['name'] as String; + int get profile => _json['profile'] as int; + int? get team => _json['team'] as int?; + + /// The row as decoded from the response. + Map toJson() => _json; +} + +/// Values for inserting a row into `badge`. Columns that are nullable, +/// identity, or covered by a database default are optional; passing `null` +/// omits the column so the database default applies. Columns the database +/// always generates itself are left out entirely. Use the `set…ToNull` methods +/// to insert SQL NULL explicitly. +extension type const BadgeInsert._(Map _json) + implements Object { + BadgeInsert({int? id, required String name, required int profile, int? team}) + : this._({'id': ?id, 'name': name, 'profile': profile, 'team': ?team}); + + /// Returns a copy with `team` set to SQL NULL, overriding any database + /// default. + BadgeInsert setTeamToNull() => BadgeInsert._({..._json, 'team': null}); +} + +/// Values for updating rows of `badge`. All columns are optional; passing +/// `null` omits the column, leaving it unchanged. Use the `set…ToNull` methods +/// to write SQL NULL explicitly. +extension type const BadgeUpdate._(Map _json) + implements Object { + BadgeUpdate({int? id, String? name, int? profile, int? team}) + : this._({'id': ?id, 'name': ?name, 'profile': ?profile, 'team': ?team}); + + /// Returns a copy with `team` set to SQL NULL, overriding any database + /// default. + BadgeUpdate setTeamToNull() => BadgeUpdate._({..._json, 'team': null}); +} + +/// Typed access to the `badge` table. +class Badge { + const Badge._(); + + /// Table definition for [PostgrestClient.table]. + static const table = PostgrestTable( + 'badge', + BadgeRow.new, + schema: 'public', + primaryKey: [id], + relations: [profileByProfile, teamByTeam, teamBadge], + ); + + static const id = PostgrestColumn('id'); + static const name = PostgrestColumn('name'); + static const profile = PostgrestColumn('profile'); + static const team = PostgrestNullableColumn('team'); + + /// The `profile` row referenced by `profile`. + static const profileByProfile = PostgrestToOneRelation( + 'profile', + columns: [profile], + referencedTable: 'profile', + referencedColumns: [Profile.id], + alias: 'profile_by_profile', + ); + + /// The `team` row referenced by `team`. + static const teamByTeam = PostgrestToOneRelation( + 'team!badge_team_fkey', + columns: [team], + referencedTable: 'team', + referencedColumns: [Team.id], + alias: 'team_by_team', + ); + + /// The `team_badge` rows referencing this row through `badge_id`. + static const teamBadge = PostgrestToManyRelation( + 'team_badge', + columns: [id], + referencedTable: 'team_badge', + referencedColumns: [TeamBadge.badgeId], + ); +} + +/// A row of the `team_badge` table, as `select()` reads it with every column. +extension type const TeamBadgeRow(Map _json) + implements Object { + int get teamId => _json['team_id'] as int; + int get badgeId => _json['badge_id'] as int; + + /// The row as decoded from the response. + Map toJson() => _json; +} + +/// Values for inserting a row into `team_badge`. Columns that are nullable, +/// identity, or covered by a database default are optional; passing `null` +/// omits the column so the database default applies. Columns the database +/// always generates itself are left out entirely. Use the `set…ToNull` methods +/// to insert SQL NULL explicitly. +extension type const TeamBadgeInsert._(Map _json) + implements Object { + TeamBadgeInsert({required int teamId, required int badgeId}) + : this._({'team_id': teamId, 'badge_id': badgeId}); +} + +/// Values for updating rows of `team_badge`. All columns are optional; passing +/// `null` omits the column, leaving it unchanged. Use the `set…ToNull` methods +/// to write SQL NULL explicitly. +extension type const TeamBadgeUpdate._(Map _json) + implements Object { + TeamBadgeUpdate({int? teamId, int? badgeId}) + : this._({'team_id': ?teamId, 'badge_id': ?badgeId}); +} + +/// Typed access to the `team_badge` table. +class TeamBadge { + const TeamBadge._(); + + /// Table definition for [PostgrestClient.table]. + static const table = + PostgrestTable( + 'team_badge', + TeamBadgeRow.new, + schema: 'public', + primaryKey: [teamId, badgeId], + relations: [team, badge], + ); + + static const teamId = PostgrestColumn('team_id'); + static const badgeId = PostgrestColumn('badge_id'); + + /// The `team` row referenced by `team_id`. + static const team = PostgrestToOneRelation( + 'team', + columns: [teamId], + referencedTable: 'team', + referencedColumns: [Team.id], + ); + + /// The `badge` row referenced by `badge_id`. + static const badge = PostgrestToOneRelation( + 'badge', + columns: [badgeId], + referencedTable: 'badge', + referencedColumns: [Badge.id], + ); +} + /// A row returned by the `class` function. extension type const ClassRow(Map _json) implements Object { String$? get string => switch (_json['string']) { diff --git a/supabase/migrations/20240101000005_embed_disambiguation.sql b/supabase/migrations/20240101000005_embed_disambiguation.sql new file mode 100644 index 000000000..97e731663 --- /dev/null +++ b/supabase/migrations/20240101000005_embed_disambiguation.sql @@ -0,0 +1,34 @@ +-- Tables joined by more than one relationship and through columns named like +-- the tables they reference, for the supabase_typegen test that embeds them +-- through the members generated for the same tables in its hostile golden. + +create table public.team ( + id bigint generated by default as identity primary key, + name text not null, + owner_id bigint +); + +create table public.profile ( + id bigint generated by default as identity primary key, + name text not null, + team bigint references public.team (id) +); + +alter table public.team + add constraint team_owner_id_fkey + foreign key (owner_id) references public.profile (id); + +create table public.badge ( + id bigint generated by default as identity primary key, + name text not null, + profile bigint not null references public.profile (id), + team bigint references public.team (id) +); + +-- A junction table: next to badge.team, a second relationship between badge +-- and team. +create table public.team_badge ( + team_id bigint not null references public.team (id), + badge_id bigint not null references public.badge (id), + primary key (team_id, badge_id) +); diff --git a/supabase/seed.sql b/supabase/seed.sql index bb7548f9e..73d8d52b4 100644 --- a/supabase/seed.sql +++ b/supabase/seed.sql @@ -51,6 +51,38 @@ values insert into public.addresses (username, location) values ('supabot', 'SRID=4326;POINT(-71.10044 42.373695)'); +-- Tables of supabase/migrations/20240101000005_embed_disambiguation.sql. +insert into public.team (name) values ('Rockets'); +insert into public.team (name) values ('Comets'); + +insert into public.profile (name, team) +values ('Ada', (select id from public.team where name = 'Rockets')); +insert into public.profile (name, team) +values ('Grace', (select id from public.team where name = 'Rockets')); +insert into public.profile (name, team) values ('Linus', null); + +update public.team +set owner_id = (select id from public.profile where name = 'Grace') +where name = 'Rockets'; +update public.team +set owner_id = (select id from public.profile where name = 'Ada') +where name = 'Comets'; + +insert into public.badge (name, profile, team) +values ( + 'Founder', + (select id from public.profile where name = 'Ada'), + (select id from public.team where name = 'Rockets') +); +insert into public.badge (name, profile, team) +values ('Mentor', (select id from public.profile where name = 'Ada'), null); + +insert into public.team_badge (team_id, badge_id) +values ( + (select id from public.team where name = 'Comets'), + (select id from public.badge where name = 'Founder') +); + -- --------------------------------------------------------------------------- -- supabase_storage dummy data (ported from infra/storage_client/postgres/dummy-data.sql) -- The storage tests authenticate with the service_role key, which bypasses RLS,