Skip to content

Commit 4b96d41

Browse files
authored
Merge pull request #27 from tareq-halaby/tareq-halaby-patch-3
Implement SchemaInspector for database introspection
2 parents abe1535 + 1936950 commit 4b96d41

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

src/SchemaInspector.php

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SqlPowertools;
6+
7+
/**
8+
* SchemaInspector - Database Schema Introspection Utility
9+
*
10+
* Provides methods to inspect database tables, columns, indexes,
11+
* and foreign keys at runtime without hardcoding schema knowledge.
12+
*
13+
* @package SqlPowertools
14+
* @version 1.2.0
15+
*/
16+
class SchemaInspector
17+
{
18+
public function __construct(private readonly \PDO $pdo) {}
19+
20+
/**
21+
* List all table names in the current database.
22+
*/
23+
public function getTables(): array
24+
{
25+
$stmt = $this->pdo->query('SHOW TABLES');
26+
return $stmt->fetchAll(\PDO::FETCH_COLUMN);
27+
}
28+
29+
/**
30+
* Get column metadata for a given table.
31+
*/
32+
public function getColumns(string $table): array
33+
{
34+
$stmt = $this->pdo->prepare('DESCRIBE `' . $table . '`');
35+
$stmt->execute();
36+
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
37+
}
38+
39+
/**
40+
* Get index information for a given table.
41+
*/
42+
public function getIndexes(string $table): array
43+
{
44+
$stmt = $this->pdo->prepare('SHOW INDEX FROM `' . $table . '`');
45+
$stmt->execute();
46+
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
47+
}
48+
49+
/**
50+
* Check if a specific column exists on a table.
51+
*/
52+
public function columnExists(string $table, string $column): bool
53+
{
54+
$columns = array_column($this->getColumns($table), 'Field');
55+
return in_array($column, $columns, true);
56+
}
57+
58+
/**
59+
* Get the primary key column(s) of a table.
60+
*/
61+
public function getPrimaryKey(string $table): array
62+
{
63+
return array_filter(
64+
$this->getColumns($table),
65+
fn($col) => $col['Key'] === 'PRI'
66+
);
67+
}
68+
}

0 commit comments

Comments
 (0)