diff --git a/packages/supabase_typegen/README.md b/packages/supabase_typegen/README.md index 103bf11e5..a88b2a6cc 100644 --- a/packages/supabase_typegen/README.md +++ b/packages/supabase_typegen/README.md @@ -1,10 +1,104 @@ # supabase_typegen -> [!WARNING] -> This is a placeholder release that reserves the package name on pub.dev. The -> code generator is still under development and this version does nothing yet. +Generates typed Supabase table definitions from your database schema, so +query results never expose raw `Map` data. -A command-line code generator that turns a Supabase database schema into typed -Dart table definitions for use with the Supabase client packages. +For every table the generator emits: -The generator implementation will land in a future release. +- a zero-cost row extension type over the decoded JSON map with typed getters, +- `Insert` and `Update` value types that enforce required columns at the + construction site, +- a `PostgrestTable` definition and `TableColumn` tokens for compile-time + checked filters, +- Dart enums for Postgres enums, with wire-name mapping. + +## Usage + +The easiest way is through the Supabase CLI, which handles the database +connection and runs this package for you. Add `supabase_typegen` as a dev +dependency of your project, then: + +```sh +supabase gen types --lang dart --local > lib/supabase_schema.g.dart +``` + +Any of the CLI's connection flags work (`--local`, `--linked`, `--db-url`, +`--project-id`). + +To run the package yourself, dump the schema metadata first and pass it with +`--input` (a path, or `-` for stdin): + +```sh +supabase gen types --lang json --local > schema.json +dart run supabase_typegen --input schema.json \ + --output lib/supabase_schema.g.dart +``` + +The document is the `GeneratorMetadata` introspection contract of +[`@supabase/postgrest-typegen`](https://github.com/supabase/pg-toolbelt), +which is also what postgres-meta's own type generators consume. Until CLI +support for `--lang dart` and `--lang json` ships, the same document comes +from serializing that package's `introspect()` result. + +## Committing schema.json + +The SQL in your `supabase/` directory stays the single source of truth: the +CLI applies your migrations to the local database and the metadata document +is introspected from the result. `schema.json` is derived output, the same +category as the generated Dart file, so committing it is optional and the +recommended one-liner never writes it at all. + +Committing a snapshot can still be worthwhile: + +- it diffs nicely in review, so a migration's effect on the API surface is + visible next to the SQL that caused it, +- the generator can re-run from it offline, without Docker or a database, + which keeps CI checks and codegen fast and hermetic, +- a stale generated file is detectable by regenerating from the snapshot and + comparing. + +If you commit it, treat it like a lockfile: regenerate it in the same change +as every migration, and never edit it by hand. When the snapshot and the +migrations disagree, the migrations win; regenerate the snapshot. + +Use `--schema` to generate for a schema other than `public`, and `--import` +to change which library the generated file imports `PostgrestTable` and +`TableColumn` from. + +The metadata comes from the database catalog, so nullability, database +defaults, and identity columns are exact: a `NOT NULL` column with a default +reads as non-nullable but stays optional on insert, and `GENERATED ALWAYS` +columns appear in the row type but not in the insert and update types. + +## Generated code in action + +```dart +final books = await client.table(Books.table) + .select() + .where(Books.mood.eq(Mood.happy)) + .order(Books.createdAt, ascending: false); // List + +await client.table(Books.table).insert( + BooksInsert(title: 'A typed row', tags: ['dart']), +); +``` + +## Known limitations + +- Passing `null` to an `Insert`/`Update` parameter omits the column. To write + SQL NULL explicitly, use the generated `set…ToNull` methods, for example + `BooksUpdate(inPrint: false).setPriceToNull()`; they only exist for + nullable columns, so nulling a `NOT NULL` column is a compile error. +- Array elements are assumed non-null (`text[]` maps to `List`), + matching the supabase-js type generator; arrays containing SQL NULL + elements throw when the element is read. Enum array columns degrade to + `List`. +- `timestamptz` values are written back in UTC, naive `timestamp` values as + local wall time, and `date` values date-only, so calendar dates never + shift with the client timezone. +- The metadata identifies a column's enum type only by its bare name. When + two schemas define enums with the same name, columns using the enum from + the other schema resolve to the generated schema's enum, so keep enum + names unique across schemas. +- Foreign key relationship getters and typed functions (rpc) are not + generated yet. diff --git a/packages/supabase_typegen/bin/supabase_typegen.dart b/packages/supabase_typegen/bin/supabase_typegen.dart new file mode 100644 index 000000000..eeb740e11 --- /dev/null +++ b/packages/supabase_typegen/bin/supabase_typegen.dart @@ -0,0 +1,131 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:args/args.dart'; +import 'package:supabase_typegen/supabase_typegen.dart'; + +final _argParser = ArgParser() + ..addOption( + 'input', + abbr: 'i', + help: + 'Path of the GeneratorMetadata document, or - to ' + 'read it from stdin. Produce it with ' + '`supabase gen types --lang json`.', + ) + ..addOption( + 'schema', + defaultsTo: 'public', + help: 'The database schema to generate types for.', + ) + ..addOption( + 'output', + abbr: 'o', + defaultsTo: 'lib/supabase_schema.g.dart', + help: 'Path of the generated Dart file, or - to write the code to stdout.', + ) + ..addOption( + 'import', + defaultsTo: 'package:postgrest/postgrest.dart', + help: + 'The import the generated file uses for PostgrestTable and ' + 'TableColumn.', + ) + ..addFlag('help', abbr: 'h', negatable: false, help: 'Show this usage.'); + +Future main(List arguments) async { + // The value returned from main is ignored by the Dart VM, so the exit + // code has to be set explicitly. + exitCode = await _run(arguments); +} + +Future _run(List arguments) async { + final ArgResults options; + try { + options = _argParser.parse(arguments); + } on FormatException catch (error) { + stderr + ..writeln(error.message) + ..writeln(_argParser.usage); + return 64; + } + + if (options.flag('help')) { + stdout + ..writeln( + 'Generates typed Supabase table definitions from the schema ' + 'metadata that postgres-meta emits.', + ) + ..writeln() + ..writeln('Usage: dart run supabase_typegen --input schema.json') + ..writeln(_argParser.usage); + return 0; + } + + final input = options.option('input'); + if (input == null) { + stderr.writeln( + '--input is required: the path of a GeneratorMetadata ' + 'document, or - to read it from stdin. Produce it with ' + '`supabase gen types --lang json`.', + ); + return 64; + } + + final String contents; + if (input == '-') { + contents = await utf8.decodeStream(stdin); + } else { + final inputFile = File(input); + if (!inputFile.existsSync()) { + stderr.writeln('The input file $input does not exist.'); + return 66; + } + contents = inputFile.readAsStringSync(); + } + + final schemaName = options.option('schema')!; + final SchemaDescription schema; + try { + schema = parseGeneratorMetadata( + jsonDecode(contents) as Map, + schemaName: schemaName, + ); + } on FormatException catch (error) { + stderr.writeln('Could not parse $input: ${error.message}'); + return 65; + } on TypeError { + stderr.writeln( + 'The document in $input is not a GeneratorMetadata document. ' + 'Produce it with `supabase gen types --lang json`.', + ); + return 65; + } + + final code = generateDartCode(schema, importUri: options.option('import')!); + + final output = options.option('output')!; + final String generatedInto; + if (output == '-') { + stdout.write(code); + generatedInto = 'stdout'; + } else { + final outputFile = File(output); + outputFile.parent.createSync(recursive: true); + outputFile.writeAsStringSync(code); + generatedInto = outputFile.path; + } + + final emittedTables = schema.tables + .where((table) => table.columns.isNotEmpty) + .length; + final skippedTables = schema.tables.length - emittedTables; + final summarySink = output == '-' ? stderr : stdout; + summarySink.writeln( + 'Generated $generatedInto with $emittedTables tables and ' + '${schema.enums.length} enums from schema "$schemaName".' + '${skippedTables == 0 ? '' : ' Skipped $skippedTables tables ' + 'without columns.'}', + ); + return 0; +} diff --git a/packages/supabase_typegen/lib/src/dart_generator.dart b/packages/supabase_typegen/lib/src/dart_generator.dart new file mode 100644 index 000000000..ddf769620 --- /dev/null +++ b/packages/supabase_typegen/lib/src/dart_generator.dart @@ -0,0 +1,499 @@ +import 'package:dart_style/dart_style.dart'; + +import 'identifiers.dart'; +import 'schema_description.dart'; + +class _Binding { + const _Binding(this.dartType, this.kind); + + /// The non-nullable Dart type of the column. + final String dartType; + final ColumnTypeKind kind; +} + +/// Generates a Dart source file with typed table definitions, row extension +/// types, insert and update value types, column tokens and Postgres enums for +/// [schema]. +/// +/// The generated code depends only on the library at [importUri], which must +/// export the typed table access API of `package:postgrest` (`PostgrestTable` +/// and `TableColumn`). +String generateDartCode( + SchemaDescription schema, { + String importUri = 'package:postgrest/postgrest.dart', +}) { + final usesDateColumns = schema.tables.any( + (table) => table.columns.any( + (column) => column.typeKind == ColumnTypeKind.date, + ), + ); + final buffer = StringBuffer() + ..writeln('// Generated by supabase_typegen. Do not edit by hand.') + ..writeln('//') + ..writeln('// Source schema: ${schema.schemaName}') + ..writeln() + ..writeln('// The typed table access API is still experimental.') + ..writeln('// ignore_for_file: experimental_member_use') + ..writeln() + ..writeln("import '$importUri';") + ..writeln(); + + final typeNames = _TypeNameRegistry(); + final enumTypeNames = {}; + + for (final enumDescription in schema.enums) { + final typeName = typeNames.claim(pascalCase(enumDescription.name)); + enumTypeNames[enumDescription.qualifiedName] = typeName; + _writeEnum(buffer, enumDescription, typeName); + } + + for (final table in schema.tables) { + if (table.columns.isEmpty) continue; + _writeTable(buffer, table, typeNames, enumTypeNames); + } + + if (usesDateColumns) { + buffer + ..writeln('String _dateString(DateTime date) =>') + ..writeln(" '\${date.year.toString().padLeft(4, '0')}-'") + ..writeln(" '\${date.month.toString().padLeft(2, '0')}-'") + ..writeln(" '\${date.day.toString().padLeft(2, '0')}';") + ..writeln(); + } + + return DartFormatter( + languageVersion: DartFormatter.latestLanguageVersion, + ).format(buffer.toString()); +} + +/// Hands out unique top level type names, suffixing `$` on collisions. +class _TypeNameRegistry { + final _used = {}; + + String claim(String name) { + var candidate = name; + while (!_used.add(candidate)) { + candidate = '$candidate\$'; + } + return candidate; + } +} + +void _writeEnum( + StringBuffer buffer, + EnumDescription enumDescription, + String typeName, +) { + final valueNames = _uniqueMemberNames( + enumDescription.values, + reserved: { + typeName, + 'index', + 'name', + 'values', + 'wireName', + 'fromWire', + 'toString', + 'hashCode', + 'runtimeType', + 'noSuchMethod', + }, + ); + + buffer + ..writeln('/// Postgres enum `${enumDescription.qualifiedName}`.') + ..writeln('enum $typeName {'); + for (final value in enumDescription.values) { + buffer.writeln(" ${valueNames[value]}(${_stringLiteral(value)}),"); + } + buffer + ..writeln(';') + ..writeln() + ..writeln(' const $typeName(this.wireName);') + ..writeln() + ..writeln(' /// The value as stored in the database.') + ..writeln(' final String wireName;') + ..writeln() + ..writeln(' /// Parses the database representation of the enum.') + ..writeln(' static $typeName fromWire(String wireName) =>') + ..writeln(' values.firstWhere(') + ..writeln(' (value) => value.wireName == wireName,') + ..writeln(' orElse: () => throw ArgumentError.value(') + ..writeln(' wireName,') + ..writeln(" 'wireName',") + ..writeln(" 'No $typeName value with this wire name',") + ..writeln(' ),') + ..writeln(' );') + ..writeln() + ..writeln(' @override') + ..writeln(' String toString() => wireName;') + ..writeln('}') + ..writeln(); +} + +void _writeTable( + StringBuffer buffer, + TableDescription table, + _TypeNameRegistry typeNames, + Map enumTypeNames, +) { + final baseName = pascalCase(table.name); + final rowType = typeNames.claim('${baseName}Row'); + final insertType = typeNames.claim('${baseName}Insert'); + final updateType = typeNames.claim('${baseName}Update'); + final namespaceType = typeNames.claim(baseName); + + final memberNames = _uniqueMemberNames( + [for (final column in table.columns) column.name], + reserved: {rowType, insertType, updateType}, + ); + final bindings = { + for (final column in table.columns) + column.name: _bindingFor(column, enumTypeNames), + }; + + _writeRow(buffer, table, rowType, memberNames, bindings); + _writeValues( + buffer, + table, + insertType, + memberNames, + bindings, + requireRequiredColumns: true, + docLine: + 'Values for inserting a row into `${table.name}`. 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.', + ); + _writeValues( + buffer, + table, + updateType, + memberNames, + bindings, + requireRequiredColumns: false, + docLine: + 'Values for updating rows of `${table.name}`. All columns are ' + 'optional; passing `null` omits the column, leaving it unchanged. ' + 'Use the `set…ToNull` methods to write SQL NULL explicitly.', + ); + _writeNamespace(buffer, table, namespaceType, rowType, memberNames, bindings); +} + +void _writeRow( + StringBuffer buffer, + TableDescription table, + String rowType, + Map memberNames, + Map bindings, +) { + buffer.writeln('/// A row of the `${table.name}` table.'); + _writeDocComment(buffer, table.comment); + buffer + ..writeln('extension type const $rowType(Map _json)') + ..writeln(' implements Map {'); + for (final column in table.columns) { + final binding = bindings[column.name]!; + _writeDocComment(buffer, column.comment, indent: ' '); + buffer.writeln( + ' ${_getterType(column, binding)} get ${memberNames[column.name]} => ' + '${_readExpression(column, binding)};', + ); + } + buffer + ..writeln('}') + ..writeln(); +} + +void _writeValues( + StringBuffer buffer, + TableDescription table, + String typeName, + Map memberNames, + Map bindings, { + required bool requireRequiredColumns, + required String docLine, +}) { + bool isRequired(ColumnDescription column) => + requireRequiredColumns && column.isRequired; + final writableColumns = [ + for (final column in table.columns) + if (!column.isReadOnly) column, + ]; + + _writeDocComment(buffer, docLine); + buffer + ..writeln('extension type const $typeName._(Map _json)') + ..writeln(' implements Map {'); + if (writableColumns.isEmpty) { + // A named parameter list cannot be empty, so a table whose columns are + // all read-only gets a parameterless constructor. + buffer.writeln(' $typeName() : this._({});'); + } else { + buffer.writeln(' $typeName({'); + for (final column in writableColumns) { + final binding = bindings[column.name]!; + final name = memberNames[column.name]!; + if (isRequired(column)) { + buffer.writeln(' required ${binding.dartType} $name,'); + } else { + buffer.writeln(' ${binding.dartType}? $name,'); + } + } + buffer.writeln(' }) : this._({'); + for (final column in writableColumns) { + final binding = bindings[column.name]!; + final name = memberNames[column.name]!; + final key = _stringLiteral(column.name); + if (isRequired(column)) { + buffer.writeln( + ' $key: ${_writeExpression(name, binding, nullable: false)},', + ); + } else { + buffer.writeln( + ' $key: ?${_writeExpression(name, binding, nullable: true)},', + ); + } + } + buffer.writeln(' });'); + } + for (final column in writableColumns) { + if (!column.isNullable) continue; + final name = memberNames[column.name]!; + final methodName = 'set${name[0].toUpperCase()}${name.substring(1)}ToNull'; + buffer.writeln(); + _writeDocComment( + buffer, + 'Returns a copy with `${column.name}` set to SQL NULL, overriding any ' + 'database default.', + indent: ' ', + ); + buffer.writeln( + ' $typeName $methodName() => ' + '$typeName._({..._json, ${_stringLiteral(column.name)}: null});', + ); + } + buffer + ..writeln('}') + ..writeln(); +} + +void _writeNamespace( + StringBuffer buffer, + TableDescription table, + String namespaceType, + String rowType, + Map memberNames, + Map bindings, +) { + final columnNames = _uniqueMemberNames( + [for (final column in table.columns) column.name], + reserved: {'table', namespaceType}, + existing: memberNames, + ); + + buffer + ..writeln('/// Typed access to the `${table.name}` table.') + ..writeln('class $namespaceType {') + ..writeln(' const $namespaceType._();') + ..writeln() + ..writeln(' /// Table definition for [PostgrestClient.table].') + ..writeln( + ' static const table = PostgrestTable' + '(${_stringLiteral(table.name)}, $rowType.new);', + ) + ..writeln(); + for (final column in table.columns) { + final binding = bindings[column.name]!; + buffer.writeln( + ' static const ${columnNames[column.name]} = ' + 'TableColumn<${binding.dartType}>(${_stringLiteral(column.name)});', + ); + } + buffer + ..writeln('}') + ..writeln(); +} + +_Binding _bindingFor( + ColumnDescription column, + Map enumTypeNames, +) => switch (column.typeKind) { + ColumnTypeKind.enumType => _Binding( + enumTypeNames[column.postgresFormat]!, + ColumnTypeKind.enumType, + ), + ColumnTypeKind.array => _Binding( + 'List<${_elementDartType(column.elementTypeKind)}>', + ColumnTypeKind.array, + ), + ColumnTypeKind.integer => const _Binding('int', ColumnTypeKind.integer), + ColumnTypeKind.floating => const _Binding('double', ColumnTypeKind.floating), + ColumnTypeKind.numeric => const _Binding('num', ColumnTypeKind.numeric), + ColumnTypeKind.boolean => const _Binding('bool', ColumnTypeKind.boolean), + ColumnTypeKind.date => const _Binding('DateTime', ColumnTypeKind.date), + ColumnTypeKind.timestamp => const _Binding( + 'DateTime', + ColumnTypeKind.timestamp, + ), + ColumnTypeKind.timestampWithTimeZone => const _Binding( + 'DateTime', + ColumnTypeKind.timestampWithTimeZone, + ), + ColumnTypeKind.text => const _Binding('String', ColumnTypeKind.text), + ColumnTypeKind.json || + ColumnTypeKind.unknown => const _Binding('Object', ColumnTypeKind.json), +}; + +String _elementDartType(ColumnTypeKind? elementTypeKind) => + switch (elementTypeKind) { + ColumnTypeKind.integer => 'int', + ColumnTypeKind.floating => 'double', + ColumnTypeKind.numeric => 'num', + ColumnTypeKind.boolean => 'bool', + ColumnTypeKind.text => 'String', + ColumnTypeKind.date || + ColumnTypeKind.timestamp || + ColumnTypeKind.timestampWithTimeZone || + ColumnTypeKind.json || + ColumnTypeKind.enumType || + ColumnTypeKind.array || + ColumnTypeKind.unknown || + null => 'Object', + }; + +String _getterType(ColumnDescription column, _Binding binding) { + if (binding.kind == ColumnTypeKind.json) return 'Object?'; + return column.isNullable ? '${binding.dartType}?' : binding.dartType; +} + +String _readExpression(ColumnDescription column, _Binding binding) { + final access = "_json[${_stringLiteral(column.name)}]"; + final nullable = column.isNullable; + return switch (binding.kind) { + ColumnTypeKind.integer || + ColumnTypeKind.numeric || + ColumnTypeKind.boolean || + ColumnTypeKind.text => + '$access as ${binding.dartType}${nullable ? '?' : ''}', + ColumnTypeKind.floating => + nullable + ? '($access as num?)?.toDouble()' + : '($access as num).toDouble()', + ColumnTypeKind.array => + nullable + ? '($access as List?)?.cast()' + : '($access as List).cast()', + ColumnTypeKind.date || + ColumnTypeKind.timestamp || + ColumnTypeKind.timestampWithTimeZone => + nullable + ? _nullableSwitch(access, 'DateTime.parse(value as String)') + : 'DateTime.parse($access as String)', + ColumnTypeKind.enumType => + nullable + ? _nullableSwitch( + access, + '${binding.dartType}.fromWire(value as String)', + ) + : '${binding.dartType}.fromWire($access as String)', + ColumnTypeKind.json || ColumnTypeKind.unknown => '$access as Object?', + }; +} + +String _nullableSwitch(String access, String conversion) => + 'switch ($access) { null => null, final Object value => $conversion }'; + +String _writeExpression( + String parameterName, + _Binding binding, { + required bool nullable, +}) { + final access = nullable ? '$parameterName?' : parameterName; + return switch (binding.kind) { + ColumnTypeKind.date => + nullable + ? 'switch ($parameterName) ' + '{ null => null, final value => _dateString(value) }' + : '_dateString($parameterName)', + ColumnTypeKind.timestamp => '$access.toIso8601String()', + ColumnTypeKind.timestampWithTimeZone => + nullable + ? '$access.toUtc().toIso8601String()' + : '$parameterName.toUtc().toIso8601String()', + ColumnTypeKind.enumType => '$access.wireName', + ColumnTypeKind.integer || + ColumnTypeKind.floating || + ColumnTypeKind.numeric || + ColumnTypeKind.boolean || + ColumnTypeKind.text || + ColumnTypeKind.array || + ColumnTypeKind.json || + ColumnTypeKind.unknown => parameterName, + }; +} + +/// Maps raw database names to unique Dart member identifiers. +/// +/// [reserved] seeds identifiers that must not be produced. When [existing] is +/// given, names are kept identical to it where possible so that, for example, +/// column tokens and row getters share their spelling. +Map _uniqueMemberNames( + List names, { + Set reserved = const {}, + Map? existing, +}) { + final used = {...reserved}; + final result = {}; + for (final name in names) { + var candidate = existing?[name] ?? memberIdentifier(name); + while (!used.add(candidate)) { + candidate = '$candidate\$'; + } + result[name] = candidate; + } + return result; +} + +void _writeDocComment( + StringBuffer buffer, + String? comment, { + String indent = '', +}) { + if (comment == null) return; + final width = 80 - indent.length - '/// '.length; + for (final line in comment.trim().split('\n')) { + for (final wrapped in _wrap(line.trim(), width)) { + buffer.writeln('$indent/// $wrapped'); + } + } +} + +/// Greedily wraps [text] into lines of at most [width] characters, keeping +/// words longer than [width] on their own line. +Iterable _wrap(String text, int width) sync* { + final words = text.split(' ').where((word) => word.isNotEmpty); + final line = StringBuffer(); + for (final word in words) { + if (line.isNotEmpty && line.length + 1 + word.length > width) { + yield line.toString(); + line.clear(); + } + if (line.isNotEmpty) line.write(' '); + line.write(word); + } + if (line.isNotEmpty) yield line.toString(); +} + +String _stringLiteral(String value) { + final escaped = value + .replaceAll(r'\', r'\\') + .replaceAll("'", r"\'") + .replaceAll(r'$', r'\$') + .replaceAll('\n', r'\n') + .replaceAll('\r', r'\r') + .replaceAll('\t', r'\t'); + return "'$escaped'"; +} diff --git a/packages/supabase_typegen/lib/src/generator_metadata_parser.dart b/packages/supabase_typegen/lib/src/generator_metadata_parser.dart new file mode 100644 index 000000000..136c60a51 --- /dev/null +++ b/packages/supabase_typegen/lib/src/generator_metadata_parser.dart @@ -0,0 +1,234 @@ +import 'schema_description.dart'; + +const _integerFormats = {'int2', 'int4', 'int8', 'oid'}; +const _floatingFormats = {'float4', 'float8'}; + +/// Types that PostgREST serializes as JSON strings. +const _textFormats = { + 'text', + 'citext', + 'varchar', + 'bpchar', + 'char', + 'name', + 'uuid', + 'time', + 'timetz', + 'interval', + 'bytea', + 'inet', + 'cidr', + 'macaddr', + 'macaddr8', + 'money', + 'xml', + 'bit', + 'varbit', + 'tsvector', + 'tsquery', +}; +const _jsonFormats = {'json', 'jsonb'}; + +/// Derives the [ColumnTypeKind] from the postgres-meta [format] of a column, +/// for example `int8`, `timestamptz` or `_text` for a `text[]` array. This is +/// the single place where type names are compared as strings; everything +/// downstream works with the enum. +ColumnTypeKind _typeKind(String format, {required bool isEnum}) { + if (format.startsWith('_')) return ColumnTypeKind.array; + if (isEnum) return ColumnTypeKind.enumType; + if (_integerFormats.contains(format)) return ColumnTypeKind.integer; + if (_floatingFormats.contains(format)) return ColumnTypeKind.floating; + if (format == 'numeric') return ColumnTypeKind.numeric; + if (format == 'bool') return ColumnTypeKind.boolean; + if (format == 'date') return ColumnTypeKind.date; + if (format == 'timestamp') return ColumnTypeKind.timestamp; + if (format == 'timestamptz') return ColumnTypeKind.timestampWithTimeZone; + if (_textFormats.contains(format)) return ColumnTypeKind.text; + if (_jsonFormats.contains(format)) return ColumnTypeKind.json; + return ColumnTypeKind.unknown; +} + +/// The kind of the elements of an array column, where enum elements are +/// carried as their wire strings. +ColumnTypeKind _elementTypeKind(String elementFormat, {required bool isEnum}) { + final kind = _typeKind(elementFormat, isEnum: isEnum); + return kind == ColumnTypeKind.enumType ? ColumnTypeKind.text : kind; +} + +/// Parses a `GeneratorMetadata` document, the introspection contract shared +/// by `@supabase/postgrest-typegen` and postgres-meta +/// (`supabase gen types --lang json`), into a [SchemaDescription] for +/// [schemaName]. +/// +/// Throws a [FormatException] when the document does not have the +/// `GeneratorMetadata` shape. +SchemaDescription parseGeneratorMetadata( + Map document, { + String schemaName = 'public', +}) { + if (document['tables'] is! List || + document['columns'] is! List) { + throw const FormatException( + 'Not a GeneratorMetadata document: expected the introspection contract ' + 'of @supabase/postgrest-typegen, with "tables" and "columns" lists.', + ); + } + + final relations = [ + for (final key in ['tables', 'foreignTables', 'views', 'materializedViews']) + ...?(document[key] as List?)?.cast>(), + ].where((relation) => relation['schema'] == schemaName); + + final columnsByRelationId = >>{}; + for (final column + in (document['columns'] as List? ?? const []) + .cast>()) { + columnsByRelationId + .putIfAbsent(column['table_id'] as int, () => []) + .add(column); + } + for (final columns in columnsByRelationId.values) { + columns.sort( + (a, b) => (a['ordinal_position'] as int).compareTo( + b['ordinal_position'] as int, + ), + ); + } + + final foreignKeysByColumn = _foreignKeysByColumn(document, schemaName); + final enumTypes = _enumTypes(document, schemaName); + + final tables = []; + final enumsByQualifiedName = {}; + + for (final relation in relations) { + final relationName = relation['name'] as String; + + final columns = []; + for (final column + in columnsByRelationId[relation['id'] as int] ?? const []) { + final name = column['name'] as String; + final format = column['format'] as String; + final enumValues = (column['enums'] as List? ?? const []) + .cast(); + final isEnum = enumValues.isNotEmpty; + final typeKind = _typeKind(format, isEnum: isEnum); + final isArray = typeKind == ColumnTypeKind.array; + + var postgresFormat = format; + if (isEnum && !isArray) { + final enumDescription = _enumDescription(format, enumValues, enumTypes); + postgresFormat = enumDescription.qualifiedName; + enumsByQualifiedName.putIfAbsent( + enumDescription.qualifiedName, + () => enumDescription, + ); + } + + final hasDefault = + column['default_value'] != null || + column['is_identity'] as bool || + column['is_generated'] as bool; + final isNullable = column['is_nullable'] as bool; + + columns.add( + ColumnDescription( + name: name, + postgresFormat: postgresFormat, + typeKind: typeKind, + elementTypeKind: isArray + ? _elementTypeKind(format.substring(1), isEnum: isEnum) + : null, + enumValues: isEnum ? enumValues : null, + isRequired: !isNullable && !hasDefault, + hasDefault: hasDefault, + isNullable: isNullable, + isReadOnly: + column['identity_generation'] == 'ALWAYS' || + column['is_generated'] as bool, + comment: column['comment'] as String?, + foreignKey: foreignKeysByColumn[(relationName, name)], + ), + ); + } + + tables.add( + TableDescription( + name: relationName, + comment: relation['comment'] as String?, + columns: columns, + ), + ); + } + + tables.sort((a, b) => a.name.compareTo(b.name)); + final enums = enumsByQualifiedName.values.toList() + ..sort((a, b) => a.qualifiedName.compareTo(b.qualifiedName)); + + return SchemaDescription( + schemaName: schemaName, + tables: tables, + enums: enums, + ); +} + +/// Maps `(table, column)` pairs of [schemaName] to their foreign key targets, +/// pairing the source and referenced columns of each relationship by index. +Map<(String, String), ForeignKeyDescription> _foreignKeysByColumn( + Map document, + String schemaName, +) { + final foreignKeys = <(String, String), ForeignKeyDescription>{}; + for (final relationship + in (document['relationships'] as List? ?? const []) + .cast>()) { + if (relationship['schema'] != schemaName) continue; + final table = relationship['relation'] as String; + final columns = (relationship['columns'] as List).cast(); + final referencedColumns = + (relationship['referenced_columns'] as List).cast(); + for (var i = 0; i < columns.length; i++) { + foreignKeys.putIfAbsent( + (table, columns[i]), + () => ForeignKeyDescription( + table: relationship['referenced_relation'] as String, + column: referencedColumns[i], + ), + ); + } + } + return foreignKeys; +} + +/// Maps enum type names to `(schema, values)`, preferring types of +/// [schemaName] when the same name exists in several schemas. +Map)> _enumTypes( + Map document, + String schemaName, +) { + final enumTypes = )>{}; + for (final type + in (document['types'] as List? ?? const []) + .cast>()) { + final values = (type['enums'] as List? ?? const []).cast(); + if (values.isEmpty) continue; + final name = type['name'] as String; + final schema = type['schema'] as String; + if (schema == schemaName || !enumTypes.containsKey(name)) { + enumTypes[name] = (schema, values); + } + } + return enumTypes; +} + +EnumDescription _enumDescription( + String format, + List columnEnumValues, + Map)> enumTypes, +) { + final type = enumTypes[format]; + return EnumDescription( + qualifiedName: type == null ? format : '${type.$1}.$format', + values: type == null ? columnEnumValues : type.$2, + ); +} diff --git a/packages/supabase_typegen/lib/src/identifiers.dart b/packages/supabase_typegen/lib/src/identifiers.dart new file mode 100644 index 000000000..0c8dcb8b9 --- /dev/null +++ b/packages/supabase_typegen/lib/src/identifiers.dart @@ -0,0 +1,135 @@ +const _reservedWords = { + 'abstract', + 'as', + 'assert', + 'async', + 'await', + 'base', + 'break', + 'case', + 'catch', + 'class', + 'const', + 'continue', + 'covariant', + 'default', + 'deferred', + 'do', + 'dynamic', + 'else', + 'enum', + 'export', + 'extends', + 'extension', + 'external', + 'factory', + 'false', + 'final', + 'finally', + 'for', + 'get', + 'hide', + 'if', + 'implements', + 'import', + 'in', + 'interface', + 'is', + 'late', + 'library', + 'mixin', + 'new', + 'null', + 'of', + 'on', + 'operator', + 'part', + 'required', + 'rethrow', + 'return', + 'sealed', + 'set', + 'show', + 'static', + 'super', + 'switch', + 'sync', + 'this', + 'throw', + 'true', + 'try', + 'type', + 'typedef', + 'var', + 'void', + 'when', + 'while', + 'with', + 'yield', +}; + +/// Members that already exist on `Map`, which generated row +/// extension types implement, so column getters cannot use these names. +const _mapMembers = { + 'addAll', + 'addEntries', + 'cast', + 'clear', + 'containsKey', + 'containsValue', + 'entries', + 'forEach', + 'hashCode', + 'isEmpty', + 'isNotEmpty', + 'keys', + 'length', + 'map', + 'noSuchMethod', + 'putIfAbsent', + 'remove', + 'removeWhere', + 'runtimeType', + 'toString', + 'update', + 'updateAll', + 'values', +}; + +final _wordSeparator = RegExp('[^a-zA-Z0-9]+'); +final _camelHumpBoundary = RegExp('(?<=[a-z0-9])(?=[A-Z])'); + +List _words(String name) => [ + for (final part in name.split(_wordSeparator)) + ...part.split(_camelHumpBoundary), +].where((word) => word.isNotEmpty).toList(); + +/// Converts [name] to PascalCase, for example `author_stats` to +/// `AuthorStats`. +String pascalCase(String name) { + final words = _words(name); + if (words.isEmpty) return r'$'; + final pascal = [ + for (final word in words) + word[0].toUpperCase() + word.substring(1).toLowerCase(), + ].join(); + return pascal.startsWith(RegExp('[0-9]')) ? '\$$pascal' : pascal; +} + +/// Converts [name] to camelCase, for example `created_at` to `createdAt`. +String camelCase(String name) { + final pascal = pascalCase(name); + return pascal[0].toLowerCase() + pascal.substring(1); +} + +/// Converts [name] to a valid Dart member identifier in camelCase. +/// +/// Reserved words and members that would collide with `Map` +/// get a `$` suffix, for example `class` becomes `class$`. +String memberIdentifier(String name) { + final identifier = camelCase(name); + if (_reservedWords.contains(identifier) || _mapMembers.contains(identifier)) { + return '$identifier\$'; + } + return identifier; +} diff --git a/packages/supabase_typegen/lib/src/schema_description.dart b/packages/supabase_typegen/lib/src/schema_description.dart new file mode 100644 index 000000000..d8a3b5a77 --- /dev/null +++ b/packages/supabase_typegen/lib/src/schema_description.dart @@ -0,0 +1,161 @@ +/// The Dart-relevant type of a column, derived from the Postgres type at +/// parse time so that later stages never have to compare type name strings. +enum ColumnTypeKind { + /// Whole number types such as `smallint`, `integer` and `bigint`. + integer, + + /// Floating point types such as `real` and `double precision`. + floating, + + /// Arbitrary precision types such as `numeric`, mapped to `num` since the + /// decoded JSON value may be either an integer or a double. + numeric, + + /// The `boolean` type. + boolean, + + /// The `date` type, mapped to `DateTime` and written back date-only so + /// the calendar date never shifts with the client timezone. + date, + + /// Timestamps without a timezone, mapped to `DateTime` and written back as + /// the local wall time. + timestamp, + + /// Timestamps with a timezone, mapped to `DateTime` and written back in + /// UTC. + timestampWithTimeZone, + + /// Types carried as text, such as `text`, `uuid` and `character varying`. + text, + + /// The `json` and `jsonb` types, mapped to `Object?`. + json, + + /// A Postgres enum type. + enumType, + + /// An array type; the element type is in + /// [ColumnDescription.elementTypeKind]. + array, + + /// A type without a specific mapping, treated like [json]. + unknown, +} + +/// Description of a single database schema, the input to the code generator. +class SchemaDescription { + const SchemaDescription({ + required this.schemaName, + required this.tables, + required this.enums, + }); + + /// Name of the database schema, for example `public`. + final String schemaName; + + /// Tables and views of the schema, sorted by name. + final List tables; + + /// Postgres enums referenced by the tables, sorted by name. + final List enums; +} + +/// Description of a table or view. +class TableDescription { + const TableDescription({ + required this.name, + required this.columns, + this.comment, + }); + + /// Name of the table in the database. + final String name; + + /// The table comment, when one is set. + final String? comment; + + /// Columns of the table, in database order. + final List columns; +} + +/// Description of a single table column. +class ColumnDescription { + const ColumnDescription({ + required this.name, + required this.postgresFormat, + required this.typeKind, + required this.isRequired, + required this.hasDefault, + required this.isNullable, + this.isReadOnly = false, + this.elementTypeKind, + this.enumValues, + this.foreignKey, + this.comment, + }); + + /// Name of the column in the database. + final String name; + + /// The Postgres type, for example `int8`, `_text` or `public.mood`. + final String postgresFormat; + + /// The kind of Dart type the column maps to. + final ColumnTypeKind typeKind; + + /// The kind of Dart type of the array elements for [ColumnTypeKind.array] + /// columns. + final ColumnTypeKind? elementTypeKind; + + /// The values of the Postgres enum for enum columns. + final List? enumValues; + + /// Whether the column is `NOT NULL` without a database default, which makes + /// it required on insert. + final bool isRequired; + + /// Whether the column has a database default. + final bool hasDefault; + + /// The column comment, when one is set. + final String? comment; + + /// The referenced table and column for foreign key columns. + final ForeignKeyDescription? foreignKey; + + /// Whether the column can be `null` in query results. + final bool isNullable; + + /// Whether the column can never be written, because it is a + /// `GENERATED ALWAYS` identity or a generated column. Read-only columns + /// appear in the row type but not in the insert and update value types. + final bool isReadOnly; +} + +/// The target of a foreign key column. +class ForeignKeyDescription { + const ForeignKeyDescription({required this.table, required this.column}); + + /// The referenced table. + final String table; + + /// The referenced column. + final String column; +} + +/// Description of a Postgres enum type. +class EnumDescription { + const EnumDescription({required this.qualifiedName, required this.values}); + + /// The schema-qualified name of the enum, for example `public.mood`. + final String qualifiedName; + + /// The values of the enum, in declaration order. + final List values; + + /// The enum name without the schema qualifier. + String get name => qualifiedName.contains('.') + ? qualifiedName.split('.').last + : qualifiedName; +} diff --git a/packages/supabase_typegen/lib/supabase_typegen.dart b/packages/supabase_typegen/lib/supabase_typegen.dart index 4b0d261bf..aeb9b9e2d 100644 --- a/packages/supabase_typegen/lib/supabase_typegen.dart +++ b/packages/supabase_typegen/lib/supabase_typegen.dart @@ -1,6 +1,8 @@ -/// Command-line code generator that turns a Supabase database schema into -/// typed Dart table definitions. -/// -/// This is a placeholder release that reserves the package name. The generator -/// implementation is not available yet. +/// Generates typed Supabase table definitions, row extension types and +/// column tokens from a database schema. library; + +export 'src/dart_generator.dart'; +export 'src/identifiers.dart'; +export 'src/generator_metadata_parser.dart'; +export 'src/schema_description.dart'; diff --git a/packages/supabase_typegen/pubspec.yaml b/packages/supabase_typegen/pubspec.yaml index 7fe7b8966..228705f95 100644 --- a/packages/supabase_typegen/pubspec.yaml +++ b/packages/supabase_typegen/pubspec.yaml @@ -14,6 +14,15 @@ environment: resolution: workspace +executables: + supabase_typegen: + +dependencies: + args: ^2.7.0 + dart_style: ^3.1.0 + dev_dependencies: + http: ^1.6.0 + postgrest: ^2.9.0 supabase_lints: ^0.1.1 test: ^1.25.0 diff --git a/packages/supabase_typegen/test/dart_generator_test.dart b/packages/supabase_typegen/test/dart_generator_test.dart new file mode 100644 index 000000000..7a9573780 --- /dev/null +++ b/packages/supabase_typegen/test/dart_generator_test.dart @@ -0,0 +1,104 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:supabase_typegen/supabase_typegen.dart'; +import 'package:test/test.dart'; + +final _whitespace = RegExp(r'\s+'); + +/// Collapses whitespace so the comparison is stable across formatter +/// versions; `tool/regenerate_goldens.dart` refreshes the golden. +String _normalize(String code) => code.replaceAll(_whitespace, ' ').trim(); + +void main() { + late SchemaDescription schema; + + setUpAll(() { + final document = + jsonDecode( + File( + 'test/fixtures/generator_metadata.json', + ).readAsStringSync(), + ) + as Map; + schema = parseGeneratorMetadata(document); + }); + + test('matches the golden output', () { + final golden = File('test/goldens/supabase_schema.dart').readAsStringSync(); + + expect( + _normalize(generateDartCode(schema)), + _normalize(golden), + reason: + 'The generator output changed. Regenerate the golden with ' + '`dart run tool/regenerate_goldens.dart` and review the diff.', + ); + }); + + test('respects a custom import', () { + final code = generateDartCode( + schema, + importUri: 'package:supabase_flutter/supabase_flutter.dart', + ); + + expect( + code, + contains("import 'package:supabase_flutter/supabase_flutter.dart';"), + ); + }); + + test('marks not null columns without default as required on insert', () { + final code = generateDartCode(schema); + + expect(code, contains('required String title')); + expect(code, contains('int? id')); + }); + + test('not null columns with a default read non-nullable', () { + final code = generateDartCode(schema); + + expect(code, contains("bool get inPrint => _json['in_print'] as bool;")); + expect( + code, + contains( + "DateTime get createdAt => " + "DateTime.parse(_json['created_at'] as String);", + ), + ); + }); + + test('always generated columns are excluded from insert and update', () { + final code = generateDartCode(schema); + + expect(code, contains('AuthorsInsert({required String name})')); + expect(code, contains('AuthorsUpdate({String? name})')); + expect(code, contains("TableColumn('id')")); + }); + + test('tables whose columns are all read-only get parameterless ' + 'insert and update constructors', () { + final table = TableDescription( + name: 'counters', + comment: null, + columns: [ + ColumnDescription( + name: 'id', + postgresFormat: 'int8', + typeKind: ColumnTypeKind.integer, + isRequired: false, + hasDefault: true, + isNullable: false, + isReadOnly: true, + ), + ], + ); + final code = generateDartCode( + SchemaDescription(schemaName: 'public', tables: [table], enums: []), + ); + + expect(code, contains('CountersInsert() : this._({});')); + expect(code, contains('CountersUpdate() : this._({});')); + expect(code, contains("int get id => _json['id'] as int;")); + }); +} diff --git a/packages/supabase_typegen/test/fixtures/generator_metadata.json b/packages/supabase_typegen/test/fixtures/generator_metadata.json new file mode 100644 index 000000000..e4286148c --- /dev/null +++ b/packages/supabase_typegen/test/fixtures/generator_metadata.json @@ -0,0 +1,447 @@ +{ + "schemas": [ + { + "id": 2200, + "name": "public", + "owner": "postgres" + } + ], + "tables": [ + { + "id": 16385, + "schema": "public", + "name": "books", + "rls_enabled": true, + "rls_forced": false, + "replica_identity": "DEFAULT", + "bytes": 8192, + "size": "8192 bytes", + "live_rows_estimate": 0, + "dead_rows_estimate": 0, + "comment": "Books available in the library" + }, + { + "id": 16401, + "schema": "public", + "name": "authors", + "rls_enabled": true, + "rls_forced": false, + "replica_identity": "DEFAULT", + "bytes": 8192, + "size": "8192 bytes", + "live_rows_estimate": 0, + "dead_rows_estimate": 0, + "comment": null + } + ], + "foreignTables": [], + "views": [ + { + "id": 16420, + "schema": "public", + "name": "author_stats", + "is_updatable": false, + "comment": "Aggregated statistics per author" + } + ], + "materializedViews": [], + "columns": [ + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.1", + "ordinal_position": 1, + "name": "id", + "default_value": null, + "data_type": "bigint", + "format": "int8", + "is_identity": true, + "identity_generation": "BY DEFAULT", + "is_generated": false, + "is_nullable": false, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.2", + "ordinal_position": 2, + "name": "title", + "default_value": null, + "data_type": "text", + "format": "text", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": false, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.3", + "ordinal_position": 3, + "name": "author_id", + "default_value": null, + "data_type": "bigint", + "format": "int8", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": false, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.4", + "ordinal_position": 4, + "name": "price", + "default_value": null, + "data_type": "numeric", + "format": "numeric", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.5", + "ordinal_position": 5, + "name": "rating", + "default_value": null, + "data_type": "double precision", + "format": "float8", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.6", + "ordinal_position": 6, + "name": "in_print", + "default_value": "true", + "data_type": "boolean", + "format": "bool", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": false, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.7", + "ordinal_position": 7, + "name": "mood", + "default_value": null, + "data_type": "USER-DEFINED", + "format": "mood", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [ + "happy", + "very happy", + "sad" + ], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.8", + "ordinal_position": 8, + "name": "tags", + "default_value": null, + "data_type": "ARRAY", + "format": "_text", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.9", + "ordinal_position": 9, + "name": "page_counts", + "default_value": null, + "data_type": "ARRAY", + "format": "_int4", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.10", + "ordinal_position": 10, + "name": "metadata", + "default_value": null, + "data_type": "jsonb", + "format": "jsonb", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.11", + "ordinal_position": 11, + "name": "cover_uuid", + "default_value": null, + "data_type": "uuid", + "format": "uuid", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.12", + "ordinal_position": 12, + "name": "published_on", + "default_value": null, + "data_type": "date", + "format": "date", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.13", + "ordinal_position": 13, + "name": "created_at", + "default_value": "now()", + "data_type": "timestamp with time zone", + "format": "timestamptz", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": false, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": "When the row was created" + }, + { + "table_id": 16385, + "schema": "public", + "table": "books", + "id": "16385.14", + "ordinal_position": 14, + "name": "updated_at", + "default_value": null, + "data_type": "timestamp without time zone", + "format": "timestamp", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16401, + "schema": "public", + "table": "authors", + "id": "16401.1", + "ordinal_position": 1, + "name": "id", + "default_value": null, + "data_type": "bigint", + "format": "int8", + "is_identity": true, + "identity_generation": "ALWAYS", + "is_generated": false, + "is_nullable": false, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16401, + "schema": "public", + "table": "authors", + "id": "16401.2", + "ordinal_position": 2, + "name": "name", + "default_value": null, + "data_type": "text", + "format": "text", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": false, + "is_updatable": true, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16420, + "schema": "public", + "table": "author_stats", + "id": "16420.1", + "ordinal_position": 1, + "name": "author_id", + "default_value": null, + "data_type": "bigint", + "format": "int8", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": false, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + }, + { + "table_id": 16420, + "schema": "public", + "table": "author_stats", + "id": "16420.2", + "ordinal_position": 2, + "name": "book_count", + "default_value": null, + "data_type": "bigint", + "format": "int8", + "is_identity": false, + "identity_generation": null, + "is_generated": false, + "is_nullable": true, + "is_updatable": false, + "is_unique": false, + "enums": [], + "check": null, + "comment": null + } + ], + "relationships": [ + { + "foreign_key_name": "books_author_id_fkey", + "schema": "public", + "relation": "books", + "columns": [ + "author_id" + ], + "is_one_to_one": false, + "referenced_schema": "public", + "referenced_relation": "authors", + "referenced_columns": [ + "id" + ] + } + ], + "functions": [], + "types": [ + { + "id": 16390, + "name": "mood", + "schema": "public", + "format": "mood", + "enums": [ + "happy", + "very happy", + "sad" + ], + "attributes": [], + "comment": null, + "type_relation_id": null + } + ] +} diff --git a/packages/supabase_typegen/test/generated_schema_behavior_test.dart b/packages/supabase_typegen/test/generated_schema_behavior_test.dart new file mode 100644 index 000000000..31ada9d93 --- /dev/null +++ b/packages/supabase_typegen/test/generated_schema_behavior_test.dart @@ -0,0 +1,193 @@ +// The typed table access API under test is annotated @experimental. +// ignore_for_file: experimental_member_use + +import 'dart:convert'; + +import 'package:http/http.dart'; +import 'package:postgrest/postgrest.dart'; +import 'package:test/test.dart'; + +import 'goldens/supabase_schema.dart'; + +class MockHttpClient extends BaseClient { + String responseBody = '[]'; + BaseRequest? lastRequest; + String? lastRequestBody; + + @override + Future send(BaseRequest request) async { + lastRequest = request; + lastRequestBody = utf8.decode(await request.finalize().toBytes()); + return StreamedResponse( + Stream.value(utf8.encode(responseBody)), + 200, + headers: {'content-type': 'application/json'}, + request: request, + ); + } +} + +void main() { + late MockHttpClient httpClient; + late PostgrestClient client; + + setUp(() { + httpClient = MockHttpClient(); + client = PostgrestClient( + 'http://localhost/rest/v1', + httpClient: httpClient, + ); + }); + + tearDown(() async { + await client.dispose(); + }); + + test('select returns typed rows with converted values', () async { + httpClient.responseBody = jsonEncode([ + { + 'id': 1, + 'title': 'A typed row', + 'author_id': 7, + 'price': 12.5, + 'rating': 4, + 'in_print': true, + 'mood': 'very happy', + 'tags': ['dart', 'types'], + 'metadata': {'reprint': true}, + 'created_at': '2026-07-23T10:00:00Z', + 'published_on': null, + }, + ]); + + final List books = await client.table(Books.table).select(); + + final book = books.single; + expect(book.id, 1); + expect(book.title, 'A typed row'); + expect(book.rating, 4.0); + expect(book.inPrint, isTrue); + expect(book.mood, Mood.veryHappy); + expect(book.tags, ['dart', 'types']); + expect(book.metadata, {'reprint': true}); + expect(book.createdAt, DateTime.utc(2026, 7, 23, 10)); + expect(book.publishedOn == null, isTrue); + }); + + test('enum column tokens filter with the wire name', () async { + await client.table(Books.table).select().where(Books.mood.eq(Mood.happy)); + + expect( + httpClient.lastRequest!.url.queryParameters['mood'], + 'eq.happy', + ); + }); + + test('insert sends converted values and omits absent columns', () async { + httpClient.responseBody = ''; + + await client + .table(Books.table) + .insert( + BooksInsert( + title: 'A typed row', + authorId: 7, + mood: Mood.happy, + createdAt: DateTime.utc(2026, 7, 23, 10), + ), + ); + + final sent = + jsonDecode(httpClient.lastRequestBody!) as Map; + expect(sent, { + 'title': 'A typed row', + 'author_id': 7, + 'mood': 'happy', + 'created_at': '2026-07-23T10:00:00.000Z', + }); + }); + + test( + 'timestamps are sent as UTC instants and dates keep their day', + () async { + httpClient.responseBody = ''; + + await client + .table(Books.table) + .insert( + BooksInsert( + title: 'A typed row', + authorId: 7, + createdAt: DateTime(2026, 7, 23, 10), // local wall time + publishedOn: DateTime(2026, 7, 23, 23, 30), + ), + ); + + final sent = + jsonDecode(httpClient.lastRequestBody!) as Map; + expect( + sent['created_at'], + DateTime(2026, 7, 23, 10).toUtc().toIso8601String(), + ); + expect(sent['published_on'], '2026-07-23'); + }, + ); + + test('unknown enum wire values throw a descriptive error', () { + expect( + () => Mood.fromWire('grumpy'), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('No Mood value'), + ), + ), + ); + }); + + test('update sends only the provided columns', () async { + httpClient.responseBody = ''; + + await client + .table(Books.table) + .update(BooksUpdate(inPrint: false)) + .where(Books.id.eq(1)); + + expect(jsonDecode(httpClient.lastRequestBody!), {'in_print': false}); + expect(httpClient.lastRequest!.url.queryParameters['id'], 'eq.1'); + }); + + test('setXToNull writes SQL NULL explicitly', () async { + httpClient.responseBody = ''; + + final update = BooksUpdate(inPrint: false); + await client + .table(Books.table) + .update(update.setPriceToNull().setMoodToNull()) + .where(Books.id.eq(1)); + + expect(jsonDecode(httpClient.lastRequestBody!), { + 'in_print': false, + 'price': null, + 'mood': null, + }); + expect( + update.containsKey('price'), + isFalse, + reason: 'setPriceToNull returns a copy and must not mutate', + ); + + await client + .table(Books.table) + .insert( + BooksInsert(title: 'x', authorId: 7).setPublishedOnToNull(), + ); + + expect(jsonDecode(httpClient.lastRequestBody!), { + 'title': 'x', + 'author_id': 7, + 'published_on': null, + }); + }); +} diff --git a/packages/supabase_typegen/test/generator_metadata_parser_test.dart b/packages/supabase_typegen/test/generator_metadata_parser_test.dart new file mode 100644 index 000000000..324d475c3 --- /dev/null +++ b/packages/supabase_typegen/test/generator_metadata_parser_test.dart @@ -0,0 +1,214 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:supabase_typegen/supabase_typegen.dart'; +import 'package:test/test.dart'; + +void main() { + late Map document; + late SchemaDescription schema; + + setUpAll(() { + document = + jsonDecode( + File( + 'test/fixtures/generator_metadata.json', + ).readAsStringSync(), + ) + as Map; + schema = parseGeneratorMetadata(document); + }); + + test('rejects documents without the GeneratorMetadata shape', () { + expect( + () => parseGeneratorMetadata({'swagger': '2.0', 'definitions': {}}), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('GeneratorMetadata'), + ), + ), + ); + }); + + test('parses tables and views sorted by name', () { + expect(schema.tables.map((table) => table.name), [ + 'author_stats', + 'authors', + 'books', + ]); + }); + + test('parses table and view comments', () { + final books = schema.tables.singleWhere((table) => table.name == 'books'); + expect(books.comment, 'Books available in the library'); + + final authorStats = schema.tables.singleWhere( + (table) => table.name == 'author_stats', + ); + expect(authorStats.comment, 'Aggregated statistics per author'); + }); + + test('parses requiredness, defaults and nullability', () { + final books = schema.tables.singleWhere((table) => table.name == 'books'); + final id = books.columns.singleWhere((column) => column.name == 'id'); + expect(id.isRequired, isFalse); + expect(id.hasDefault, isTrue); + expect(id.isNullable, isFalse); + expect(id.isReadOnly, isFalse); + + final title = books.columns.singleWhere((column) => column.name == 'title'); + expect(title.isRequired, isTrue); + expect(title.isNullable, isFalse); + + final price = books.columns.singleWhere((column) => column.name == 'price'); + expect(price.isRequired, isFalse); + expect(price.isNullable, isTrue); + }); + + test('not null columns with a database default are non-nullable reads ' + 'but optional writes', () { + final books = schema.tables.singleWhere((table) => table.name == 'books'); + final inPrint = books.columns.singleWhere( + (column) => column.name == 'in_print', + ); + expect(inPrint.isNullable, isFalse); + expect(inPrint.isRequired, isFalse); + expect(inPrint.hasDefault, isTrue); + + final createdAt = books.columns.singleWhere( + (column) => column.name == 'created_at', + ); + expect(createdAt.isNullable, isFalse); + expect(createdAt.isRequired, isFalse); + }); + + test('always generated identity columns are read-only', () { + final authors = schema.tables.singleWhere( + (table) => table.name == 'authors', + ); + final id = authors.columns.singleWhere((column) => column.name == 'id'); + expect(id.isReadOnly, isTrue); + expect(id.isRequired, isFalse); + expect(id.isNullable, isFalse); + }); + + test('parses foreign keys from the relationships', () { + final books = schema.tables.singleWhere((table) => table.name == 'books'); + final authorId = books.columns.singleWhere( + (column) => column.name == 'author_id', + ); + expect(authorId.foreignKey?.table, 'authors'); + expect(authorId.foreignKey?.column, 'id'); + }); + + test('derives type kinds from formats', () { + final books = schema.tables.singleWhere((table) => table.name == 'books'); + ColumnTypeKind kindOf(String name) => + books.columns.singleWhere((column) => column.name == name).typeKind; + + expect(kindOf('id'), ColumnTypeKind.integer); + expect(kindOf('title'), ColumnTypeKind.text); + expect(kindOf('price'), ColumnTypeKind.numeric); + expect(kindOf('rating'), ColumnTypeKind.floating); + expect(kindOf('in_print'), ColumnTypeKind.boolean); + expect(kindOf('mood'), ColumnTypeKind.enumType); + expect(kindOf('metadata'), ColumnTypeKind.json); + expect(kindOf('created_at'), ColumnTypeKind.timestampWithTimeZone); + expect(kindOf('updated_at'), ColumnTypeKind.timestamp); + expect(kindOf('published_on'), ColumnTypeKind.date); + expect(kindOf('cover_uuid'), ColumnTypeKind.text); + }); + + test('types that PostgREST serializes as strings read as text', () { + Map columnOf(String format) => { + 'table_id': 1, + 'schema': 'public', + 'table': 'servers', + 'id': '1.1', + 'ordinal_position': 1, + 'name': 'value', + 'default_value': null, + 'data_type': format, + 'format': format, + 'is_identity': false, + 'identity_generation': null, + 'is_generated': false, + 'is_nullable': true, + 'is_updatable': true, + 'is_unique': false, + 'enums': [], + 'check': null, + 'comment': null, + }; + + for (final format in ['inet', 'cidr', 'macaddr', 'money', 'xml', 'name']) { + final parsed = parseGeneratorMetadata({ + 'tables': [ + { + 'id': 1, + 'schema': 'public', + 'name': 'servers', + 'comment': null, + }, + ], + 'columns': [columnOf(format)], + }); + expect( + parsed.tables.single.columns.single.typeKind, + ColumnTypeKind.text, + reason: '$format should map to text', + ); + } + }); + + test('collects Postgres enums with their schema qualification', () { + expect(schema.enums, hasLength(1)); + final mood = schema.enums.single; + expect(mood.qualifiedName, 'public.mood'); + expect(mood.name, 'mood'); + expect(mood.values, ['happy', 'very happy', 'sad']); + + final books = schema.tables.singleWhere((table) => table.name == 'books'); + final moodColumn = books.columns.singleWhere( + (column) => column.name == 'mood', + ); + expect(moodColumn.postgresFormat, 'public.mood'); + }); + + test('parses array columns', () { + final books = schema.tables.singleWhere((table) => table.name == 'books'); + final tags = books.columns.singleWhere((column) => column.name == 'tags'); + expect(tags.postgresFormat, '_text'); + expect(tags.typeKind, ColumnTypeKind.array); + expect(tags.elementTypeKind, ColumnTypeKind.text); + + final pageCounts = books.columns.singleWhere( + (column) => column.name == 'page_counts', + ); + expect(pageCounts.elementTypeKind, ColumnTypeKind.integer); + }); + + test('keeps column comments', () { + final books = schema.tables.singleWhere((table) => table.name == 'books'); + final id = books.columns.singleWhere((column) => column.name == 'id'); + expect(id.comment, isNull); + + final createdAt = books.columns.singleWhere( + (column) => column.name == 'created_at', + ); + expect(createdAt.comment, 'When the row was created'); + }); + + test('view columns come through like table columns', () { + final authorStats = schema.tables.singleWhere( + (table) => table.name == 'author_stats', + ); + expect(authorStats.columns.map((column) => column.name), [ + 'author_id', + 'book_count', + ]); + expect(authorStats.columns.first.isNullable, isTrue); + }); +} diff --git a/packages/supabase_typegen/test/goldens/supabase_schema.dart b/packages/supabase_typegen/test/goldens/supabase_schema.dart new file mode 100644 index 000000000..de46fcc15 --- /dev/null +++ b/packages/supabase_typegen/test/goldens/supabase_schema.dart @@ -0,0 +1,353 @@ +// Generated by supabase_typegen. Do not edit by hand. +// +// Source schema: public + +// The typed table access API is still experimental. +// ignore_for_file: experimental_member_use + +import 'package:postgrest/postgrest.dart'; + +/// Postgres enum `public.mood`. +enum Mood { + happy('happy'), + veryHappy('very happy'), + sad('sad'); + + const Mood(this.wireName); + + /// The value as stored in the database. + final String wireName; + + /// Parses the database representation of the enum. + static Mood fromWire(String wireName) => values.firstWhere( + (value) => value.wireName == wireName, + orElse: () => throw ArgumentError.value( + wireName, + 'wireName', + 'No Mood value with this wire name', + ), + ); + + @override + String toString() => wireName; +} + +/// A row of the `author_stats` table. +/// Aggregated statistics per author +extension type const AuthorStatsRow(Map _json) + implements Map { + int? get authorId => _json['author_id'] as int?; + int? get bookCount => _json['book_count'] as int?; +} + +/// Values for inserting a row into `author_stats`. 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 AuthorStatsInsert._(Map _json) + implements Map { + AuthorStatsInsert({int? authorId, int? bookCount}) + : this._({'author_id': ?authorId, 'book_count': ?bookCount}); + + /// Returns a copy with `author_id` set to SQL NULL, overriding any database + /// default. + AuthorStatsInsert setAuthorIdToNull() => + AuthorStatsInsert._({..._json, 'author_id': null}); + + /// Returns a copy with `book_count` set to SQL NULL, overriding any database + /// default. + AuthorStatsInsert setBookCountToNull() => + AuthorStatsInsert._({..._json, 'book_count': null}); +} + +/// Values for updating rows of `author_stats`. 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 AuthorStatsUpdate._(Map _json) + implements Map { + AuthorStatsUpdate({int? authorId, int? bookCount}) + : this._({'author_id': ?authorId, 'book_count': ?bookCount}); + + /// Returns a copy with `author_id` set to SQL NULL, overriding any database + /// default. + AuthorStatsUpdate setAuthorIdToNull() => + AuthorStatsUpdate._({..._json, 'author_id': null}); + + /// Returns a copy with `book_count` set to SQL NULL, overriding any database + /// default. + AuthorStatsUpdate setBookCountToNull() => + AuthorStatsUpdate._({..._json, 'book_count': null}); +} + +/// Typed access to the `author_stats` table. +class AuthorStats { + const AuthorStats._(); + + /// Table definition for [PostgrestClient.table]. + static const table = PostgrestTable('author_stats', AuthorStatsRow.new); + + static const authorId = TableColumn('author_id'); + static const bookCount = TableColumn('book_count'); +} + +/// A row of the `authors` table. +extension type const AuthorsRow(Map _json) + implements Map { + int get id => _json['id'] as int; + String get name => _json['name'] as String; +} + +/// Values for inserting a row into `authors`. 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 AuthorsInsert._(Map _json) + implements Map { + AuthorsInsert({required String name}) : this._({'name': name}); +} + +/// Values for updating rows of `authors`. 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 AuthorsUpdate._(Map _json) + implements Map { + AuthorsUpdate({String? name}) : this._({'name': ?name}); +} + +/// Typed access to the `authors` table. +class Authors { + const Authors._(); + + /// Table definition for [PostgrestClient.table]. + static const table = PostgrestTable('authors', AuthorsRow.new); + + static const id = TableColumn('id'); + static const name = TableColumn('name'); +} + +/// A row of the `books` table. +/// Books available in the library +extension type const BooksRow(Map _json) + implements Map { + int get id => _json['id'] as int; + String get title => _json['title'] as String; + int get authorId => _json['author_id'] as int; + num? get price => _json['price'] as num?; + double? get rating => (_json['rating'] as num?)?.toDouble(); + bool get inPrint => _json['in_print'] as bool; + Mood? get mood => switch (_json['mood']) { + null => null, + final Object value => Mood.fromWire(value as String), + }; + List? get tags => (_json['tags'] as List?)?.cast(); + List? get pageCounts => (_json['page_counts'] as List?)?.cast(); + Object? get metadata => _json['metadata'] as Object?; + String? get coverUuid => _json['cover_uuid'] as String?; + DateTime? get publishedOn => switch (_json['published_on']) { + null => null, + final Object value => DateTime.parse(value as String), + }; + + /// When the row was created + DateTime get createdAt => DateTime.parse(_json['created_at'] as String); + DateTime? get updatedAt => switch (_json['updated_at']) { + null => null, + final Object value => DateTime.parse(value as String), + }; +} + +/// Values for inserting a row into `books`. 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 BooksInsert._(Map _json) + implements Map { + BooksInsert({ + int? id, + required String title, + required int authorId, + num? price, + double? rating, + bool? inPrint, + Mood? mood, + List? tags, + List? pageCounts, + Object? metadata, + String? coverUuid, + DateTime? publishedOn, + DateTime? createdAt, + DateTime? updatedAt, + }) : this._({ + 'id': ?id, + 'title': title, + 'author_id': authorId, + 'price': ?price, + 'rating': ?rating, + 'in_print': ?inPrint, + 'mood': ?mood?.wireName, + 'tags': ?tags, + 'page_counts': ?pageCounts, + 'metadata': ?metadata, + 'cover_uuid': ?coverUuid, + 'published_on': ?switch (publishedOn) { + null => null, + final value => _dateString(value), + }, + 'created_at': ?createdAt?.toUtc().toIso8601String(), + 'updated_at': ?updatedAt?.toIso8601String(), + }); + + /// Returns a copy with `price` set to SQL NULL, overriding any database + /// default. + BooksInsert setPriceToNull() => BooksInsert._({..._json, 'price': null}); + + /// Returns a copy with `rating` set to SQL NULL, overriding any database + /// default. + BooksInsert setRatingToNull() => BooksInsert._({..._json, 'rating': null}); + + /// Returns a copy with `mood` set to SQL NULL, overriding any database + /// default. + BooksInsert setMoodToNull() => BooksInsert._({..._json, 'mood': null}); + + /// Returns a copy with `tags` set to SQL NULL, overriding any database + /// default. + BooksInsert setTagsToNull() => BooksInsert._({..._json, 'tags': null}); + + /// Returns a copy with `page_counts` set to SQL NULL, overriding any database + /// default. + BooksInsert setPageCountsToNull() => + BooksInsert._({..._json, 'page_counts': null}); + + /// Returns a copy with `metadata` set to SQL NULL, overriding any database + /// default. + BooksInsert setMetadataToNull() => + BooksInsert._({..._json, 'metadata': null}); + + /// Returns a copy with `cover_uuid` set to SQL NULL, overriding any database + /// default. + BooksInsert setCoverUuidToNull() => + BooksInsert._({..._json, 'cover_uuid': null}); + + /// Returns a copy with `published_on` set to SQL NULL, overriding any + /// database default. + BooksInsert setPublishedOnToNull() => + BooksInsert._({..._json, 'published_on': null}); + + /// Returns a copy with `updated_at` set to SQL NULL, overriding any database + /// default. + BooksInsert setUpdatedAtToNull() => + BooksInsert._({..._json, 'updated_at': null}); +} + +/// Values for updating rows of `books`. 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 BooksUpdate._(Map _json) + implements Map { + BooksUpdate({ + int? id, + String? title, + int? authorId, + num? price, + double? rating, + bool? inPrint, + Mood? mood, + List? tags, + List? pageCounts, + Object? metadata, + String? coverUuid, + DateTime? publishedOn, + DateTime? createdAt, + DateTime? updatedAt, + }) : this._({ + 'id': ?id, + 'title': ?title, + 'author_id': ?authorId, + 'price': ?price, + 'rating': ?rating, + 'in_print': ?inPrint, + 'mood': ?mood?.wireName, + 'tags': ?tags, + 'page_counts': ?pageCounts, + 'metadata': ?metadata, + 'cover_uuid': ?coverUuid, + 'published_on': ?switch (publishedOn) { + null => null, + final value => _dateString(value), + }, + 'created_at': ?createdAt?.toUtc().toIso8601String(), + 'updated_at': ?updatedAt?.toIso8601String(), + }); + + /// Returns a copy with `price` set to SQL NULL, overriding any database + /// default. + BooksUpdate setPriceToNull() => BooksUpdate._({..._json, 'price': null}); + + /// Returns a copy with `rating` set to SQL NULL, overriding any database + /// default. + BooksUpdate setRatingToNull() => BooksUpdate._({..._json, 'rating': null}); + + /// Returns a copy with `mood` set to SQL NULL, overriding any database + /// default. + BooksUpdate setMoodToNull() => BooksUpdate._({..._json, 'mood': null}); + + /// Returns a copy with `tags` set to SQL NULL, overriding any database + /// default. + BooksUpdate setTagsToNull() => BooksUpdate._({..._json, 'tags': null}); + + /// Returns a copy with `page_counts` set to SQL NULL, overriding any database + /// default. + BooksUpdate setPageCountsToNull() => + BooksUpdate._({..._json, 'page_counts': null}); + + /// Returns a copy with `metadata` set to SQL NULL, overriding any database + /// default. + BooksUpdate setMetadataToNull() => + BooksUpdate._({..._json, 'metadata': null}); + + /// Returns a copy with `cover_uuid` set to SQL NULL, overriding any database + /// default. + BooksUpdate setCoverUuidToNull() => + BooksUpdate._({..._json, 'cover_uuid': null}); + + /// Returns a copy with `published_on` set to SQL NULL, overriding any + /// database default. + BooksUpdate setPublishedOnToNull() => + BooksUpdate._({..._json, 'published_on': null}); + + /// Returns a copy with `updated_at` set to SQL NULL, overriding any database + /// default. + BooksUpdate setUpdatedAtToNull() => + BooksUpdate._({..._json, 'updated_at': null}); +} + +/// Typed access to the `books` table. +class Books { + const Books._(); + + /// Table definition for [PostgrestClient.table]. + static const table = PostgrestTable('books', BooksRow.new); + + static const id = TableColumn('id'); + static const title = TableColumn('title'); + static const authorId = TableColumn('author_id'); + static const price = TableColumn('price'); + static const rating = TableColumn('rating'); + static const inPrint = TableColumn('in_print'); + static const mood = TableColumn('mood'); + static const tags = TableColumn>('tags'); + static const pageCounts = TableColumn>('page_counts'); + static const metadata = TableColumn('metadata'); + static const coverUuid = TableColumn('cover_uuid'); + static const publishedOn = TableColumn('published_on'); + static const createdAt = TableColumn('created_at'); + static const updatedAt = TableColumn('updated_at'); +} + +String _dateString(DateTime date) => + '${date.year.toString().padLeft(4, '0')}-' + '${date.month.toString().padLeft(2, '0')}-' + '${date.day.toString().padLeft(2, '0')}'; diff --git a/packages/supabase_typegen/test/identifiers_test.dart b/packages/supabase_typegen/test/identifiers_test.dart new file mode 100644 index 000000000..5755922e9 --- /dev/null +++ b/packages/supabase_typegen/test/identifiers_test.dart @@ -0,0 +1,46 @@ +import 'package:supabase_typegen/supabase_typegen.dart'; +import 'package:test/test.dart'; + +void main() { + group('pascalCase', () { + test('converts snake case names', () { + expect(pascalCase('author_stats'), 'AuthorStats'); + expect(pascalCase('books'), 'Books'); + expect(pascalCase('user-profiles'), 'UserProfiles'); + }); + + test('keeps existing camel humps', () { + expect(pascalCase('UserProfiles'), 'UserProfiles'); + expect(pascalCase('userId'), 'UserId'); + expect(camelCase('userId'), 'userId'); + }); + + test('prefixes names starting with a digit', () { + expect(pascalCase('2fa_codes'), r'$2faCodes'); + }); + }); + + group('camelCase', () { + test('converts snake case names', () { + expect(camelCase('created_at'), 'createdAt'); + expect(camelCase('id'), 'id'); + }); + }); + + group('memberIdentifier', () { + test('suffixes reserved words', () { + expect(memberIdentifier('class'), r'class$'); + expect(memberIdentifier('in'), r'in$'); + }); + + test('suffixes Map member names', () { + expect(memberIdentifier('length'), r'length$'); + expect(memberIdentifier('keys'), r'keys$'); + }); + + test('keeps regular names untouched', () { + expect(memberIdentifier('title'), 'title'); + expect(memberIdentifier('author_id'), 'authorId'); + }); + }); +} diff --git a/packages/supabase_typegen/test/supabase_typegen_test.dart b/packages/supabase_typegen/test/supabase_typegen_test.dart deleted file mode 100644 index 7ff71c15d..000000000 --- a/packages/supabase_typegen/test/supabase_typegen_test.dart +++ /dev/null @@ -1,7 +0,0 @@ -import 'package:test/test.dart'; - -void main() { - test('supabase_typegen placeholder', () { - expect(true, isTrue); - }); -} diff --git a/packages/supabase_typegen/tool/regenerate_goldens.dart b/packages/supabase_typegen/tool/regenerate_goldens.dart new file mode 100644 index 000000000..aa1f77cbf --- /dev/null +++ b/packages/supabase_typegen/tool/regenerate_goldens.dart @@ -0,0 +1,19 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:supabase_typegen/supabase_typegen.dart'; + +/// Regenerates the golden files under `test/goldens` from the fixtures. +/// +/// Run from the package root with `dart run tool/regenerate_goldens.dart`. +void main() { + final document = + jsonDecode( + File('test/fixtures/generator_metadata.json').readAsStringSync(), + ) + as Map; + final schema = parseGeneratorMetadata(document); + File( + 'test/goldens/supabase_schema.dart', + ).writeAsStringSync(generateDartCode(schema)); +}