diff --git a/src/Migration/Destinations/Appwrite.php b/src/Migration/Destinations/Appwrite.php index 59de9b1e6f..c75cd72fea 100644 --- a/src/Migration/Destinations/Appwrite.php +++ b/src/Migration/Destinations/Appwrite.php @@ -272,7 +272,11 @@ class Appwrite extends Destination } catch (AppwriteException $e) { if ($e->getCode() === 403) { - throw new \Exception('Missing scope: ' . $scope, previous: $e); + throw new \Exception( + 'Missing scope: ' . $scope, + (int) $e->getCode() ?: Exception::CODE_FORBIDDEN, + $e + ); } throw $e; } @@ -309,7 +313,7 @@ class Appwrite extends Destination Transfer::GROUP_FUNCTIONS => $this->importFunctionResource($resource), Transfer::GROUP_MESSAGING => $this->importMessagingResource($resource), Transfer::GROUP_SITES => $this->importSiteResource($resource), - default => throw new \Exception('Invalid resource group'), + default => throw new \Exception('Invalid resource group', Exception::CODE_VALIDATION), }; } catch (\Throwable $e) { $resource->setStatus(Resource::STATUS_ERROR, $e->getMessage()); @@ -523,7 +527,7 @@ class Appwrite extends Destination Column::TYPE_VARCHAR => UtopiaDatabase::VAR_VARCHAR, Column::TYPE_MEDIUMTEXT => UtopiaDatabase::VAR_MEDIUMTEXT, Column::TYPE_LONGTEXT => UtopiaDatabase::VAR_LONGTEXT, - default => throw new \Exception('Invalid resource type '.$resource->getType()), + default => throw new \Exception('Invalid resource type '.$resource->getType(), Exception::CODE_VALIDATION), }; $database = $this->database->getDocument( @@ -743,7 +747,7 @@ class Appwrite extends Destination $resource->getFormatOptions(), $resource->getFilters(), )) { - throw new \Exception('Failed to create Column'); + throw new \Exception('Failed to create Column', Exception::CODE_INTERNAL); } } } catch (\Throwable) { @@ -1165,7 +1169,7 @@ class Appwrite extends Destination 'none' => Compression::NONE(), 'gzip' => Compression::GZIP(), 'zstd' => Compression::ZSTD(), - default => throw new \Exception('Invalid Compression: ' . $resource->getCompression()), + default => throw new \Exception('Invalid Compression: ' . $resource->getCompression(), Exception::CODE_VALIDATION), }; $response = $this->storage->createBucket( @@ -1339,7 +1343,7 @@ class Appwrite extends Destination $result = null; if (!$hash) { - throw new \Exception('Password hash is missing'); + throw new \Exception('Password hash is missing', Exception::CODE_VALIDATION); } switch ($hash->getAlgorithm()) { @@ -1483,7 +1487,7 @@ class Appwrite extends Destination 'bun-1.0' => Runtime::BUN10(), 'bun-1.1' => Runtime::BUN11(), 'go-1.23' => Runtime::GO123(), - default => throw new \Exception('Invalid Runtime: ' . $resource->getRuntime()), + default => throw new \Exception('Invalid Runtime: ' . $resource->getRuntime(), Exception::CODE_VALIDATION), }; $this->functions->create( @@ -1573,7 +1577,7 @@ class Appwrite extends Destination ); if (!\is_array($response) || !isset($response['$id'])) { - throw new \Exception('Deployment creation failed'); + throw new \Exception('Deployment creation failed', Exception::CODE_INTERNAL); } if ($deployment->getStart() === 0) { @@ -1698,7 +1702,7 @@ class Appwrite extends Destination 'flutter-3.29' => BuildRuntime::FLUTTER329(), 'flutter-3.32' => BuildRuntime::FLUTTER332(), 'flutter-3.35' => BuildRuntime::FLUTTER335(), - default => throw new \Exception('Invalid Build Runtime: ' . $resource->getBuildRuntime()), + default => throw new \Exception('Invalid Build Runtime: ' . $resource->getBuildRuntime(), Exception::CODE_VALIDATION), }; $framework = match ($resource->getFramework()) { @@ -2114,7 +2118,7 @@ class Appwrite extends Destination ); if (!\is_array($response) || !isset($response['$id'])) { - throw new \Exception('Site deployment creation failed'); + throw new \Exception('Site deployment creation failed', Exception::CODE_INTERNAL); } $deployment->setStatus(Resource::STATUS_SUCCESS); @@ -2138,7 +2142,7 @@ class Appwrite extends Destination ); if (!\is_array($response) || !isset($response['$id'])) { - throw new \Exception('Site deployment creation failed'); + throw new \Exception('Site deployment creation failed', Exception::CODE_INTERNAL); } if ($deployment->getStart() === 0) { diff --git a/src/Migration/Destinations/CSV.php b/src/Migration/Destinations/CSV.php index 8b0acd0747..790e6a0a08 100644 --- a/src/Migration/Destinations/CSV.php +++ b/src/Migration/Destinations/CSV.php @@ -6,6 +6,7 @@ use Utopia\Database\Exception\Authorization; use Utopia\Database\Exception\Conflict; use Utopia\Database\Exception\Structure; use Utopia\Migration\Destination; +use Utopia\Migration\Exception as MigrationException; use Utopia\Migration\Resource as UtopiaResource; use Utopia\Migration\Resources\Database\Row; use Utopia\Migration\Transfer; @@ -90,13 +91,13 @@ class CSV extends Destination if (!isset($handle)) { $handle = \fopen($log, 'a'); if ($handle === false) { - throw new \Exception("Failed to open file for writing: $log"); + throw new \Exception("Failed to open file for writing: $log", MigrationException::CODE_INTERNAL); } } foreach ($buffer['lines'] as $line) { if (!$this->writeCSVLine($handle, $line)) { - throw new \Exception("Failed to write CSV line to file: $log"); + throw new \Exception("Failed to write CSV line to file: $log", MigrationException::CODE_INTERNAL); } } @@ -167,7 +168,7 @@ class CSV extends Destination $destPath = $this->deviceForFiles->getPath($this->directory . '/' . $filename); if (!$this->local->exists($sourcePath)) { - throw new \Exception("No data to export for resource: $this->resourceId"); + throw new \Exception("No data to export for resource: $this->resourceId", MigrationException::CODE_NOT_FOUND); } try { @@ -177,10 +178,13 @@ class CSV extends Destination $this->deviceForFiles ); if ($result === false) { - throw new \Exception('Error transferring to ' . $this->deviceForFiles->getRoot() . '/' . $filename); + throw new \Exception( + 'Error transferring to ' . $this->deviceForFiles->getRoot() . '/' . $filename, + MigrationException::CODE_INTERNAL + ); } if (!$this->deviceForFiles->exists($destPath)) { - throw new \Exception('File not found on destination: ' . $destPath); + throw new \Exception('File not found on destination: ' . $destPath, MigrationException::CODE_NOT_FOUND); } } finally { // Clean up the temporary directory @@ -226,7 +230,7 @@ class CSV extends Destination { if (!\file_exists($path)) { if (!\mkdir($path, 0755, true)) { - throw new \Exception('Error creating directory: ' . $path); + throw new \Exception('Error creating directory: ' . $path, MigrationException::CODE_INTERNAL); } } } diff --git a/src/Migration/Destinations/JSON.php b/src/Migration/Destinations/JSON.php index 91660474ff..91016ef589 100644 --- a/src/Migration/Destinations/JSON.php +++ b/src/Migration/Destinations/JSON.php @@ -139,6 +139,7 @@ class JSON extends Destination resourceGroup: $resource->getGroup(), resourceId: $resource->getId(), message: $e->getMessage(), + code: MigrationException::CODE_VALIDATION, previous: $e, )); continue; diff --git a/src/Migration/Destinations/Local.php b/src/Migration/Destinations/Local.php index c05354ec0f..d652501d29 100644 --- a/src/Migration/Destinations/Local.php +++ b/src/Migration/Destinations/Local.php @@ -3,6 +3,7 @@ namespace Utopia\Migration\Destinations; use Utopia\Migration\Destination; +use Utopia\Migration\Exception as MigrationException; use Utopia\Migration\Resource; use Utopia\Migration\Resources\Functions\Deployment; use Utopia\Migration\Resources\Storage\File; @@ -87,7 +88,7 @@ class Local extends Destination $report = []; if (!\is_writable($this->path . '/backup.json')) { - throw new \Exception('Unable to write to file: ' . $this->path); + throw new \Exception('Unable to write to file: ' . $this->path, MigrationException::CODE_INTERNAL); } return $report; @@ -101,7 +102,10 @@ class Local extends Destination $json = \json_encode($this->data, JSON_PRETTY_PRINT); if ($json === false) { - throw new \Exception('Unable to encode data to JSON, Are you accidentally encoding binary data?'); + throw new \Exception( + 'Unable to encode data to JSON, Are you accidentally encoding binary data?', + MigrationException::CODE_VALIDATION + ); } \file_put_contents($this->path . '/backup.json', $json); diff --git a/src/Migration/Exception.php b/src/Migration/Exception.php index 86eb2e22ec..ff599a09b1 100644 --- a/src/Migration/Exception.php +++ b/src/Migration/Exception.php @@ -4,6 +4,14 @@ namespace Utopia\Migration; class Exception extends \Exception implements \JsonSerializable { + public const CODE_VALIDATION = 400; + public const CODE_UNAUTHORIZED = 401; + public const CODE_FORBIDDEN = 403; + public const CODE_NOT_FOUND = 404; + public const CODE_CONFLICT = 409; + public const CODE_RATE_LIMITED = 429; + public const CODE_INTERNAL = 500; + public string $resourceName; public string $resourceGroup; @@ -26,7 +34,7 @@ class Exception extends \Exception implements \JsonSerializable if (\is_numeric($code)) { $code = (int) $code; } else { - $code = 500; // PDOException + $code = self::CODE_INTERNAL; // PDOException } } diff --git a/src/Migration/Sources/Appwrite.php b/src/Migration/Sources/Appwrite.php index 56fcfc03a9..57624ba45b 100644 --- a/src/Migration/Sources/Appwrite.php +++ b/src/Migration/Sources/Appwrite.php @@ -115,12 +115,12 @@ class Appwrite extends Source break; case static::SOURCE_DATABASE: if (\is_null($dbForProject)) { - throw new \Exception('Database is required for database source'); + throw new \Exception('Database is required for database source', Exception::CODE_VALIDATION); } $this->database = new DatabaseReader($dbForProject); break; default: - throw new \Exception('Unknown source'); + throw new \Exception('Unknown source', Exception::CODE_VALIDATION); } } @@ -222,9 +222,9 @@ class Appwrite extends Source )['version']; } catch (\Throwable $e) { if ($e->getCode() === 403) { - throw new \Exception("Missing required scopes."); + throw new \Exception('Missing required scopes.', $e->getCode(), $e); } else { - throw new \Exception($e->getMessage(), previous: $e); + throw new \Exception($e->getMessage(), $e->getCode(), $e); } } @@ -516,7 +516,7 @@ class Appwrite extends Source Resource::TYPE_USER, Transfer::GROUP_AUTH, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } @@ -530,7 +530,7 @@ class Appwrite extends Source Resource::TYPE_TEAM, Transfer::GROUP_AUTH, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } @@ -544,7 +544,7 @@ class Appwrite extends Source Resource::TYPE_MEMBERSHIP, Transfer::GROUP_AUTH, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } @@ -684,7 +684,7 @@ class Appwrite extends Source foreach ($response['memberships'] as $membership) { $user = $cacheUsers[$membership['userId']] ?? null; if ($user === null) { - throw new \Exception('User not found'); + throw new \Exception('User not found', Exception::CODE_NOT_FOUND); } $memberships[] = new Membership( @@ -719,7 +719,7 @@ class Appwrite extends Source Resource::TYPE_DATABASE, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -737,7 +737,7 @@ class Appwrite extends Source Resource::TYPE_TABLE, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -755,7 +755,7 @@ class Appwrite extends Source Resource::TYPE_COLUMN, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -773,7 +773,7 @@ class Appwrite extends Source Resource::TYPE_INDEX, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -791,7 +791,7 @@ class Appwrite extends Source Resource::TYPE_ROW, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -1358,7 +1358,7 @@ class Appwrite extends Source Resource::TYPE_BUCKET, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -1374,7 +1374,7 @@ class Appwrite extends Source Resource::TYPE_FILE, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -1527,7 +1527,7 @@ class Appwrite extends Source Resource::TYPE_FUNCTION, Transfer::GROUP_FUNCTIONS, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } @@ -1540,7 +1540,7 @@ class Appwrite extends Source Resource::TYPE_DEPLOYMENT, Transfer::GROUP_FUNCTIONS, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } @@ -1557,7 +1557,7 @@ class Appwrite extends Source Resource::TYPE_SITE, Transfer::GROUP_SITES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } @@ -1570,7 +1570,7 @@ class Appwrite extends Source Resource::TYPE_SITE_DEPLOYMENT, Transfer::GROUP_SITES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } diff --git a/src/Migration/Sources/Appwrite/Reader/Database.php b/src/Migration/Sources/Appwrite/Reader/Database.php index bad744ce06..9927610631 100644 --- a/src/Migration/Sources/Appwrite/Reader/Database.php +++ b/src/Migration/Sources/Appwrite/Reader/Database.php @@ -130,7 +130,7 @@ class Database implements Reader resourceGroup: $resource->getGroup(), resourceId: $resource->getId(), message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ); } @@ -155,7 +155,7 @@ class Database implements Reader resourceGroup: $resource->getGroup(), resourceId: $resource->getId(), message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ); } @@ -202,7 +202,7 @@ class Database implements Reader resourceGroup: $resource->getGroup(), resourceId: $resource->getId(), message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ); } @@ -264,7 +264,7 @@ class Database implements Reader resourceGroup: $resource->getGroup(), resourceId: $resource->getId(), message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ); } @@ -310,7 +310,7 @@ class Database implements Reader resourceGroup: $resource->getGroup(), resourceId: $resource->getId(), message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ); } diff --git a/src/Migration/Sources/CSV.php b/src/Migration/Sources/CSV.php index 6d23cd7917..311b0ee7a4 100644 --- a/src/Migration/Sources/CSV.php +++ b/src/Migration/Sources/CSV.php @@ -113,7 +113,7 @@ class CSV extends Source UtopiaResource::TYPE_ROW, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -208,7 +208,7 @@ class CSV extends Source while (($row = \fgetcsv($stream, 0, $delimiter, '"', '"')) !== false) { if (\count($row) !== \count($headers)) { - throw new \Exception('CSV row does not match the number of header columns.'); + throw new \Exception('CSV row does not match the number of header columns.', Exception::CODE_VALIDATION); } $data = \array_combine($headers, $row); @@ -257,7 +257,7 @@ class CSV extends Source } if (!\is_array($arrayValues)) { - throw new \Exception("Invalid array format for column '$key': $parsedValue"); + throw new \Exception("Invalid array format for column '$key': $parsedValue", Exception::CODE_VALIDATION); } $parsedData[$key] = array_map(function ($item) use ($type) { @@ -444,7 +444,7 @@ class CSV extends Source $messages[] = "$label: '" . \implode("', '", $missingRequired) . "'"; } if (!empty($missingRequired)) { - throw new \Exception('CSV header validation failed: ' . \implode('. ', $messages)); + throw new \Exception('CSV header validation failed: ' . \implode('. ', $messages), Exception::CODE_VALIDATION); } // If there are unknown columns but no missing required columns, just log a warning @@ -487,7 +487,11 @@ class CSV extends Source } if (!$success) { - throw new \Exception('Failed to transfer CSV file from device to local storage.', previous: $e ?? null); + throw new \Exception( + 'Failed to transfer CSV file from device to local storage.', + Exception::CODE_INTERNAL, + $e ?? null + ); } $this->downloaded = true; diff --git a/src/Migration/Sources/Firebase.php b/src/Migration/Sources/Firebase.php index f98b1314b4..4495fb5ba1 100644 --- a/src/Migration/Sources/Firebase.php +++ b/src/Migration/Sources/Firebase.php @@ -145,7 +145,7 @@ class Firebase extends Source { // Check our service account is valid if (! isset($this->serviceAccount['project_id'])) { - throw new \Exception('Invalid Firebase Service Account'); + throw new \Exception('Invalid Firebase Service Account', Exception::CODE_UNAUTHORIZED); } $this->authenticate(); @@ -155,15 +155,15 @@ class Firebase extends Source $scopes = explode(' ', $scopes); if (! in_array('https://www.googleapis.com/auth/firebase', $scopes)) { - throw new \Exception('Firebase Scope Missing'); + throw new \Exception('Firebase Scope Missing', Exception::CODE_VALIDATION); } if (! in_array('https://www.googleapis.com/auth/cloud-platform', $scopes)) { - throw new \Exception('Cloud Platform Scope Missing'); + throw new \Exception('Cloud Platform Scope Missing', Exception::CODE_VALIDATION); } if (! in_array('https://www.googleapis.com/auth/datastore', $scopes)) { - throw new \Exception('Datastore Scope Missing'); + throw new \Exception('Datastore Scope Missing', Exception::CODE_VALIDATION); } return []; @@ -195,7 +195,7 @@ class Firebase extends Source Resource::TYPE_USER, Transfer::GROUP_AUTH, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -293,7 +293,7 @@ class Firebase extends Source Resource::TYPE_DATABASE, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -310,7 +310,7 @@ class Firebase extends Source Resource::TYPE_TABLE, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -469,7 +469,7 @@ class Firebase extends Source } elseif (array_key_exists('arrayValue', $field)) { return $this->calculateArrayType($column, $key, $field['arrayValue']); } else { - throw new \Exception('Unknown field type'); + throw new \Exception('Unknown field type', Exception::CODE_VALIDATION); } } @@ -592,7 +592,7 @@ class Firebase extends Source } elseif (array_key_exists('referenceValue', $field)) { //TODO: } else { - throw new \Exception('Unknown field type'); + throw new \Exception('Unknown field type', Exception::CODE_VALIDATION); } } @@ -649,7 +649,7 @@ class Firebase extends Source Resource::TYPE_BUCKET, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } @@ -663,7 +663,7 @@ class Firebase extends Source Resource::TYPE_FILE, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e )); } diff --git a/src/Migration/Sources/JSON.php b/src/Migration/Sources/JSON.php index 6c12c329e2..15e7b6aa3c 100644 --- a/src/Migration/Sources/JSON.php +++ b/src/Migration/Sources/JSON.php @@ -105,7 +105,7 @@ class JSON extends Source UtopiaResource::TYPE_ROW, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: (int) $e->getCode() ?: Exception::CODE_INTERNAL, previous: $e ) ); @@ -129,7 +129,7 @@ class JSON extends Source foreach ($items as $index => $item) { if (!\is_array($item)) { - throw new \Exception("JSON item at index $index is not an object."); + throw new \Exception("JSON item at index $index is not an object.", Exception::CODE_VALIDATION); } $rowId = $item['$id'] ?? 'unique()'; @@ -265,7 +265,11 @@ class JSON extends Source } if (!$success) { - throw new \Exception('Failed to transfer JSON file from device to local storage.', previous: $e ?? null); + throw new \Exception( + 'Failed to transfer JSON file from device to local storage.', + Exception::CODE_INTERNAL, + $e ?? null + ); } $this->downloaded = true; @@ -278,12 +282,12 @@ class JSON extends Source private function validatePermissions(mixed $permissions): array { if (!\is_array($permissions)) { - throw new \Exception('Invalid permissions format; expected an array of strings.'); + throw new \Exception('Invalid permissions format; expected an array of strings.', Exception::CODE_VALIDATION); } foreach ($permissions as $value) { if (!\is_string($value)) { - throw new \Exception('Invalid permission value; expected string.'); + throw new \Exception('Invalid permission value; expected string.', Exception::CODE_VALIDATION); } } diff --git a/src/Migration/Sources/NHost.php b/src/Migration/Sources/NHost.php index 908aa83cf0..4aac49f846 100644 --- a/src/Migration/Sources/NHost.php +++ b/src/Migration/Sources/NHost.php @@ -25,6 +25,72 @@ use Utopia\Migration\Warning; class NHost extends Source { + protected static function statusCodeFromSqlState(?string $sqlState): int + { + if ($sqlState === null || $sqlState === '') { + return Exception::CODE_INTERNAL; + } + + // Common Postgres SQLSTATE mappings → HTTP-ish status codes + // Ref: https://www.postgresql.org/docs/current/errcodes-appendix.html + return match ($sqlState) { + // AuthN/AuthZ + '28P01', // invalid_password + '28000', // invalid_authorization_specification + => Exception::CODE_UNAUTHORIZED, + + '42501', // insufficient_privilege + => Exception::CODE_FORBIDDEN, + + // Not found + '3D000', // invalid_catalog_name (db does not exist) + '42P01', // undefined_table + => Exception::CODE_NOT_FOUND, + + // Validation-ish + '42703', // undefined_column + '42601', // syntax_error + => Exception::CODE_VALIDATION, + + // Conflict + '23505', // unique_violation + => Exception::CODE_CONFLICT, + + // Resource / service constraints + '53300', // too_many_connections + => Exception::CODE_RATE_LIMITED, + + // Connection exceptions (class 08) are typically user-side config/network issues + default => \str_starts_with($sqlState, '08') + ? Exception::CODE_VALIDATION + : Exception::CODE_INTERNAL, + }; + } + + protected static function statusCodeFromThrowable(\Throwable $e): int + { + $code = $e->getCode(); + + // PDO / Postgres typically exposes SQLSTATE as the exception code (string) + if (\is_string($code)) { + return self::statusCodeFromSqlState($code); + } + + if (\is_int($code) && $code > 0) { + return $code; + } + + return Exception::CODE_INTERNAL; + } + + /** + * @param array|null $errorInfo PDOStatement::errorInfo() + */ + protected static function statusCodeFromErrorInfo(?array $errorInfo): int + { + $sqlState = $errorInfo[0] ?? null; + return self::statusCodeFromSqlState(\is_string($sqlState) ? $sqlState : null); + } /** * @var \PDO */ @@ -64,7 +130,7 @@ class NHost extends Source try { $this->pdo = new \PDO('pgsql:host='.$this->subdomain.'.db.'.$this->region.'.nhost.run'.';port='.$this->port.';dbname='.$this->databaseName, $this->username, $this->password); } catch (\PDOException $e) { - throw new \Exception('Failed to connect to database: '.$e->getMessage()); + throw new \Exception('Failed to connect to database: '.$e->getMessage(), self::statusCodeFromThrowable($e), $e); } } @@ -111,11 +177,14 @@ class NHost extends Source try { $db = $this->getDatabase(); } catch (\PDOException $e) { - throw new \Exception('Failed to connect to database. PDO Code: '.$e->getCode().' Error: '.$e->getMessage()); + throw new \Exception('Failed to connect to database. PDO Code: '.$e->getCode().' Error: '.$e->getMessage(), self::statusCodeFromThrowable($e), $e); } if (! empty($db->errorCode())) { - throw new \Exception('Failed to connect to database. PDO Code: '.$db->errorCode().(empty($db->errorInfo()[2]) ? '' : ' Error: '.$db->errorInfo()[2])); + throw new \Exception( + 'Failed to connect to database. PDO Code: '.$db->errorCode().(empty($db->errorInfo()[2]) ? '' : ' Error: '.$db->errorInfo()[2]), + self::statusCodeFromSqlState($db->errorCode()) + ); } // Auth @@ -124,7 +193,10 @@ class NHost extends Source $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access users table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access users table. Error: '.$statement->errorInfo()[2], + self::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_USER] = $statement->fetchColumn(); @@ -140,7 +212,10 @@ class NHost extends Source $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access tables table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access tables table. Error: '.$statement->errorInfo()[2], + self::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_TABLE] = $statement->fetchColumn(); @@ -151,7 +226,10 @@ class NHost extends Source $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access columns table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access columns table. Error: '.$statement->errorInfo()[2], + self::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_COLUMN] = $statement->fetchColumn(); @@ -162,7 +240,10 @@ class NHost extends Source $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access indexes table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access indexes table. Error: '.$statement->errorInfo()[2], + self::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_INDEX] = $statement->fetchColumn(); @@ -173,7 +254,10 @@ class NHost extends Source $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access tables table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access tables table. Error: '.$statement->errorInfo()[2], + self::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_ROW] = $statement->fetchColumn(); @@ -185,7 +269,10 @@ class NHost extends Source $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access buckets table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access buckets table. Error: '.$statement->errorInfo()[2], + self::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_BUCKET] = $statement->fetchColumn(); @@ -196,7 +283,10 @@ class NHost extends Source $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access files table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access files table. Error: '.$statement->errorInfo()[2], + self::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_FILE] = $statement->fetchColumn(); @@ -205,7 +295,10 @@ class NHost extends Source $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access files table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access files table. Error: '.$statement->errorInfo()[2], + self::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report['size'] = ($statement->fetchColumn()) / 1024 / 1024; // MB; @@ -227,7 +320,7 @@ class NHost extends Source Resource::TYPE_USER, Transfer::GROUP_AUTH, message: $e->getMessage(), - code: $e->getCode(), + code: self::statusCodeFromThrowable($e), previous: $e )); } @@ -293,7 +386,7 @@ class NHost extends Source Resource::TYPE_DATABASE, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: self::statusCodeFromThrowable($e), previous: $e ) ); @@ -309,7 +402,7 @@ class NHost extends Source Resource::TYPE_TABLE, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: self::statusCodeFromThrowable($e), previous: $e ) ); @@ -325,7 +418,7 @@ class NHost extends Source Resource::TYPE_COLUMN, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: self::statusCodeFromThrowable($e), previous: $e ) ); @@ -341,7 +434,7 @@ class NHost extends Source Resource::TYPE_ROW, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: self::statusCodeFromThrowable($e), previous: $e ) ); @@ -357,7 +450,7 @@ class NHost extends Source Resource::TYPE_INDEX, Transfer::GROUP_DATABASES, message: $e->getMessage(), - code: $e->getCode(), + code: self::statusCodeFromThrowable($e), previous: $e ) ); @@ -705,7 +798,7 @@ class NHost extends Source Resource::TYPE_BUCKET, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: self::statusCodeFromThrowable($e), previous: $e ) ); @@ -721,7 +814,7 @@ class NHost extends Source Resource::TYPE_FILE, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: self::statusCodeFromThrowable($e), previous: $e ) ); diff --git a/src/Migration/Sources/Supabase.php b/src/Migration/Sources/Supabase.php index 05006e19b7..8b512ab618 100644 --- a/src/Migration/Sources/Supabase.php +++ b/src/Migration/Sources/Supabase.php @@ -225,7 +225,7 @@ class Supabase extends NHost try { $this->pdo = new \PDO('pgsql:host='.$this->host.';port='.$this->port.';dbname='.$this->databaseName, $this->username, $this->password); } catch (\PDOException $e) { - throw new \Exception('Failed to connect to database: '.$e->getMessage()); + throw new \Exception('Failed to connect to database: '.$e->getMessage(), parent::statusCodeFromThrowable($e), $e); } } @@ -240,11 +240,14 @@ class Supabase extends NHost try { $this->pdo = new \PDO('pgsql:host='.$this->host.';port='.$this->port.';dbname='.$this->databaseName, $this->username, $this->password); } catch (\PDOException $e) { - throw new \Exception('Failed to connect to database. PDO Code: '.$e->getCode().' Error: '.$e->getMessage()); + throw new \Exception('Failed to connect to database. PDO Code: '.$e->getCode().' Error: '.$e->getMessage(), parent::statusCodeFromThrowable($e), $e); } if (! empty($this->pdo->errorCode())) { - throw new \Exception('Failed to connect to database. PDO Code: '.$this->pdo->errorCode().(empty($this->pdo->errorInfo()[2]) ? '' : ' Error: '.$this->pdo->errorInfo()[2])); + throw new \Exception( + 'Failed to connect to database. PDO Code: '.$this->pdo->errorCode().(empty($this->pdo->errorInfo()[2]) ? '' : ' Error: '.$this->pdo->errorInfo()[2]), + parent::statusCodeFromSqlState($this->pdo->errorCode()) + ); } // Auth @@ -253,7 +256,10 @@ class Supabase extends NHost $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access users table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access users table. Error: '.$statement->errorInfo()[2], + parent::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_USER] = $statement->fetchColumn(); @@ -269,7 +275,10 @@ class Supabase extends NHost $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access tables table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access tables table. Error: '.$statement->errorInfo()[2], + parent::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_TABLE] = $statement->fetchColumn(); @@ -280,7 +289,10 @@ class Supabase extends NHost $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access columns table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access columns table. Error: '.$statement->errorInfo()[2], + parent::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_COLUMN] = $statement->fetchColumn(); @@ -291,7 +303,10 @@ class Supabase extends NHost $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access indexes table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access indexes table. Error: '.$statement->errorInfo()[2], + parent::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_INDEX] = $statement->fetchColumn(); @@ -302,7 +317,10 @@ class Supabase extends NHost $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access tables table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access tables table. Error: '.$statement->errorInfo()[2], + parent::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_ROW] = $statement->fetchColumn(); @@ -314,7 +332,10 @@ class Supabase extends NHost $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access buckets table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access buckets table. Error: '.$statement->errorInfo()[2], + parent::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_BUCKET] = $statement->fetchColumn(); @@ -325,7 +346,10 @@ class Supabase extends NHost $statement->execute(); if ($statement->errorCode() !== '00000') { - throw new \Exception('Failed to access files table. Error: '.$statement->errorInfo()[2]); + throw new \Exception( + 'Failed to access files table. Error: '.$statement->errorInfo()[2], + parent::statusCodeFromErrorInfo($statement->errorInfo()) + ); } $report[Resource::TYPE_FILE] = $statement->fetchColumn(); @@ -357,7 +381,7 @@ class Supabase extends NHost Resource::TYPE_BUCKET, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: parent::statusCodeFromThrowable($e), previous: $e )); } @@ -431,7 +455,7 @@ class Supabase extends NHost Resource::TYPE_BUCKET, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: parent::statusCodeFromThrowable($e), previous: $e )); } @@ -445,7 +469,7 @@ class Supabase extends NHost Resource::TYPE_BUCKET, Transfer::GROUP_STORAGE, message: $e->getMessage(), - code: $e->getCode(), + code: parent::statusCodeFromThrowable($e), previous: $e )); } diff --git a/src/Migration/Target.php b/src/Migration/Target.php index 8fab14c518..8dbc5a87f2 100644 --- a/src/Migration/Target.php +++ b/src/Migration/Target.php @@ -147,16 +147,16 @@ abstract class Target } if (\curl_errno($ch)) { - throw new \Exception(\curl_error($ch)); + throw new \Exception(\curl_error($ch), Exception::CODE_INTERNAL); } \curl_close($ch); if ($responseStatus >= 400) { if (\is_array($responseBody)) { - throw new \Exception(\json_encode($responseBody)); + throw new \Exception(\json_encode($responseBody), $responseStatus); } else { - throw new \Exception($responseStatus.': '.$responseBody); + throw new \Exception($responseStatus.': '.$responseBody, $responseStatus); } }