Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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\"}")
Expand Down
6 changes: 3 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down
119 changes: 93 additions & 26 deletions packages/supabase_typegen/lib/src/dart_generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -672,7 +728,7 @@ void _writeTable(
computedFieldBindings,
relations,
relationNames,
relationKeys,
relationAliases,
decoders,
);
}
Expand Down Expand Up @@ -710,24 +766,35 @@ List<String> _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<String> _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<String?> _embedAliases(
TableDescription table,
List<_RelationMember> relations,
List<String> 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,
];
}

Expand Down Expand Up @@ -852,7 +919,7 @@ void _writeNamespace(
Map<String, _Binding> computedFieldBindings,
List<_RelationMember> relations,
List<String> relationNames,
List<String> relationKeys,
List<String?> relationAliases,
_DecoderRegistry decoders,
) {
final _TableNames(:rowType, :insertType, :updateType, :namespaceType) = names;
Expand Down Expand Up @@ -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(' );');
}
Expand Down
1 change: 1 addition & 0 deletions packages/supabase_typegen/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
117 changes: 117 additions & 0 deletions packages/supabase_typegen/test/dart_generator_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<ProfileRow,TeamRow>"
"('team!profile_team_fkey',",
),
);
expect(
compact,
contains(
"staticconstteamViaOwnerId=PostgrestToManyRelation<ProfileRow,"
"TeamRow>('team!team_owner_id_fkey',",
),
);
expect(
compact,
contains(
"staticconstprofileByOwnerId=PostgrestToOneRelation<TeamRow,"
"ProfileRow>('profile!team_owner_id_fkey',",
),
);
expect(
compact,
contains(
"staticconstprofileViaTeam=PostgrestToManyRelation<TeamRow,"
"ProfileRow>('profile!profile_team_fkey',",
),
);
});

test('a junction table makes a single key ambiguous', () {
final compact = _normalize(
generateDartCode(hostileSchema),
).replaceAll(' ', '');

expect(
compact,
contains(
"staticconstteamByTeam=PostgrestToOneRelation<BadgeRow,TeamRow>"
"('team!badge_team_fkey',",
),
);
expect(
compact,
contains(
"staticconstbadgeViaTeam=PostgrestToManyRelation<TeamRow,BadgeRow>"
"('badge!badge_team_fkey',",
),
);
expect(
compact,
contains(
"staticconstteam=PostgrestToOneRelation<TeamBadgeRow,TeamRow>"
"('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<BadgeRow,TeamRow>"
"('team',",
),
);
});

test('an embed whose key is a column name is aliased', () {
final compact = _normalize(
generateDartCode(hostileSchema),
).replaceAll(' ', '');

expect(
compact,
contains(
"staticconstprofileByProfile=PostgrestToOneRelation<BadgeRow,"
"ProfileRow>('profile',columns:[profile],referencedTable:'profile',"
"referencedColumns:[Profile.id],alias:'profile_by_profile',);",
),
);
expect(
compact,
contains(
"staticconstbadge=PostgrestToManyRelation<ProfileRow,BadgeRow>"
"('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`.
Expand Down
Loading
Loading