fix(migrations): support pgsql in 2026_01_05_000011 foreign key and index check

This commit is contained in:
michele 2026-09-11 20:04:57 +02:00
parent 2904623671
commit cfc60600e6

View File

@ -52,11 +52,17 @@ public function up(): void
->nullOnDelete();
}
if (Schema::hasColumn('contabilita_fatture_fornitori', 'movimento_pagamento_id')) {
if (
Schema::hasColumn('contabilita_fatture_fornitori', 'movimento_pagamento_id')
&& ! $this->indexExists('contabilita_fatture_fornitori', 'cff_mov_pag_idx')
) {
$table->index(['movimento_pagamento_id'], 'cff_mov_pag_idx');
}
if (Schema::hasColumn('contabilita_fatture_fornitori', 'movimento_versamento_ra_id')) {
if (
Schema::hasColumn('contabilita_fatture_fornitori', 'movimento_versamento_ra_id')
&& ! $this->indexExists('contabilita_fatture_fornitori', 'cff_mov_ra_idx')
) {
$table->index(['movimento_versamento_ra_id'], 'cff_mov_ra_idx');
}
});
@ -116,14 +122,53 @@ private function foreignKeyExists(string $table, string $fkName): bool
{
try {
$conn = Schema::getConnection();
if ($conn->getDriverName() === 'sqlite') {
return false;
}
if ($conn->getDriverName() === 'pgsql') {
$row = $conn->selectOne(
"SELECT 1 AS ok FROM information_schema.table_constraints WHERE constraint_type = 'FOREIGN KEY' AND table_name = ? AND constraint_name = ? LIMIT 1",
[$table, $fkName]
);
return (bool) ($row?->ok ?? false);
}
$db = $conn->getDatabaseName();
$row = $conn->selectOne(
'SELECT 1 AS ok FROM information_schema.referential_constraints WHERE constraint_schema = ? AND table_name = ? AND constraint_name = ? LIMIT 1',
'SELECT 1 AS ok FROM information_schema.table_constraints WHERE constraint_schema = ? AND table_name = ? AND constraint_name = ? LIMIT 1',
[$db, $table, $fkName],
);
return (bool) ($row->ok ?? false);
return (bool) ($row?->ok ?? false);
} catch (Throwable) {
return false;
}
}
private function indexExists(string $table, string $indexName): bool
{
try {
$conn = Schema::getConnection();
if ($conn->getDriverName() === 'sqlite') {
$indexes = collect($conn->select("PRAGMA index_list({$table})"));
return $indexes->pluck('name')->contains($indexName);
}
if ($conn->getDriverName() === 'pgsql') {
$row = $conn->selectOne(
"SELECT 1 AS ok FROM pg_indexes WHERE tablename = ? AND indexname = ? LIMIT 1",
[$table, $indexName]
);
return (bool) ($row?->ok ?? false);
}
$row = $conn->selectOne(
'SELECT 1 AS ok FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ? LIMIT 1',
[$table, $indexName],
);
return (bool) ($row?->ok ?? false);
} catch (Throwable) {
return false;
}