loadPreviousSchemas method

Future<void> loadPreviousSchemas()

Loads previous schema states from JSON files in the versions directory.

Implementation

Future<void> loadPreviousSchemas() async {
  previousSchemaStates.clear();
  final dir = Directory(_schemaVersionsDir);
  if (!await dir.exists()) {
    _logger.info(
      'Schema versions directory not found ($_schemaVersionsDir). Starting with version 1.',
    );
    currentSchemaVersion = 0; // Will become 1 on first generation
    return;
  }

  final regex = RegExp(r'schema_v(\d+)\.json$');
  int maxVersion = 0;

  try {
    final stream = dir.list(followLinks: false);
    await for (final entity in stream) {
      if (entity is File) {
        final match = regex.firstMatch(p.basename(entity.path));
        if (match != null) {
          final version = int.tryParse(match.group(1)!);
          if (version != null) {
            _logger.info(
              'Found schema file: ${entity.path} for version $version',
            );
            try {
              final content = await entity.readAsString();
              if (content.trim().isNotEmpty) {
                final List<dynamic> jsonList = jsonDecode(content);
                final tables =
                    jsonList
                        .map(
                          (item) => SupabaseTableInfo.fromJson(
                            item as Map<String, dynamic>,
                          ),
                        )
                        .toList();
                previousSchemaStates[version] = tables;
                if (version > maxVersion) {
                  maxVersion = version;
                }
              } else {
                _logger.warning(
                  'Schema file ${entity.path} is empty. Ignoring.',
                );
              }
            } catch (e, s) {
              _logger.severe(
                'Failed to load or parse schema file ${entity.path}: $e $s',
              );
            }
          }
        }
      }
    }
  } catch (e, s) {
    _logger.severe(
      'Error listing schema version files in $_schemaVersionsDir: $e $s',
    );
  }

  currentSchemaVersion = maxVersion;
  _logger.info(
    'Loaded ${previousSchemaStates.length} previous schema versions. Current version determined as: $currentSchemaVersion.',
  );
}