Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions docs/book/sql-ddl/constraints.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,8 @@ The `Index` class is in the `PhpDb\Sql\Ddl\Index` namespace.
```php title="Basic Index Creation"
use PhpDb\Sql\Ddl\Index\Index;

// Single column index
$index = new Index('username', 'idx_username');
// Simple - name is optional
$index = new Index('username');
$table->addConstraint($index);

// With explicit name
Expand All @@ -299,9 +299,13 @@ $table->addConstraint($index);
**Generated SQL:**

```sql
INDEX "idx_username" ("username")
INDEX ("username")
INDEX "idx_user_email"("email")
```

Without a name the index renders as a bare `INDEX (...)` clause and the database
generates the index name. Passing `null` or an empty string has the same effect.

### Composite Indexes

Index multiple columns together:
Expand Down
6 changes: 4 additions & 2 deletions src/Sql/Ddl/Index/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ public function __construct(array|string|null $columns, ?string $name = null, ar
#[Override]
public function getExpressionData(): array
{
$values = [new Identifier($this->name)];
$unnamed = '' === $this->name;
$values = $unnamed ? [] : [new Identifier($this->name)];
$spec = $unnamed ? str_replace('%s(', replace: '(', subject: $this->specification) : $this->specification;
$specParts = [];

foreach ($this->columns as $i => $column) {
Expand All @@ -52,7 +54,7 @@ public function getExpressionData(): array
$specParts[] = $specPart;
}

$spec = str_replace('...', implode(', ', $specParts), $this->specification);
$spec = str_replace('...', implode(', ', $specParts), $spec);

if (null !== $this->type) {
$spec .= ' USING %s';
Expand Down
164 changes: 164 additions & 0 deletions test/unit/Sql/Ddl/Index/IndexTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,78 @@

use PhpDb\Sql\Argument\Identifier;
use PhpDb\Sql\Argument\Literal;
use PhpDb\Sql\Ddl\AlterTable;
use PhpDb\Sql\Ddl\CreateTable;
use PhpDb\Sql\Ddl\Index\Index;
use PhpDbTest\TestAsset\TrustingSql92Platform;
use PHPUnit\Framework\Attributes\CoversMethod;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

use function array_map;

#[CoversMethod(Index::class, '__construct')]
#[CoversMethod(Index::class, 'setType')]
#[CoversMethod(Index::class, 'getType')]
#[CoversMethod(Index::class, 'getExpressionData')]
#[Group('unit')]
final class IndexTest extends TestCase
{
/**
* Unnamed indexes, with the expression spec and the SQL fragment each renders to.
*
* @return array<string, array{Index, string, list<string>, string}>
*/
public static function unnamedIndexProvider(): array
{
return [
'name omitted, single column' => [
new Index('foo'),
'INDEX (%s)',
['foo'],
'INDEX ("foo")',
],
'null name, single column' => [
new Index('foo', null),
'INDEX (%s)',
['foo'],
'INDEX ("foo")',
],
'empty name, single column' => [
new Index('foo', ''),
'INDEX (%s)',
['foo'],
'INDEX ("foo")',
],
'null name, single column with length' => [
new Index('foo', null, [10]),
'INDEX (%s(10))',
['foo'],
'INDEX ("foo"(10))',
],
'null name, multiple columns' => [
new Index(['foo', 'bar']),
'INDEX (%s, %s)',
['foo', 'bar'],
'INDEX ("foo", "bar")',
],
'empty name, multiple columns with lengths' => [
new Index(['foo', 'bar'], '', [10, 5]),
'INDEX (%s(10), %s(5))',
['foo', 'bar'],
'INDEX ("foo"(10), "bar"(5))',
],
'null name, multiple columns, one length' => [
new Index(['foo', 'bar'], null, [10]),
'INDEX (%s(10), %s)',
['foo', 'bar'],
'INDEX ("foo"(10), "bar")',
],
];
}

#[Test]
public function getExpressionData(): void
{
Expand All @@ -34,6 +95,26 @@ public function getExpressionData(): void
);
}

/**
* @param list<string> $columns
*/
#[Test]
#[DataProvider('unnamedIndexProvider')]
public function getExpressionDataOmitsNameWhenUnnamed(
Index $index,
string $expectedSpec,
array $columns,
string $expectedSql,
): void {
$expressionData = $index->getExpressionData();

static::assertSame($expectedSpec, $expressionData['spec']);
static::assertEquals(
array_map(static fn(string $column): Identifier => new Identifier($column), $columns),
$expressionData['values'],
);
}

#[Test]
public function getExpressionDataWithBtreeType(): void
{
Expand Down Expand Up @@ -108,6 +189,25 @@ public function getExpressionDataWithLengthUnmatched(): void
);
}

#[Test]
public function getExpressionDataWithoutNameKeepsLengthsAndType(): void
{
$index = new Index(['foo', 'bar'], null, [10]);
$index->setType('BTREE');

$expressionData = $index->getExpressionData();

static::assertSame('INDEX (%s(10), %s) USING %s', $expressionData['spec']);
static::assertEquals(
[
new Identifier('foo'),
new Identifier('bar'),
new Literal('BTREE'),
],
$expressionData['values'],
);
}

#[Test]
public function getExpressionDataWithTypeAndLengths(): void
{
Expand All @@ -128,6 +228,70 @@ public function getExpressionDataWithTypeAndLengths(): void
);
}

#[Test]
public function rendersNamedIndexInAlterTableAdd(): void
{
$alterTable = new AlterTable('t');
$alterTable->addConstraint(new Index('foo', 'my_idx'));

static::assertSame(
"ALTER TABLE \"t\"\n ADD INDEX \"my_idx\"(\"foo\")",
$alterTable->getSqlString(new TrustingSql92Platform()),
);
}

#[Test]
public function rendersNamedIndexInCreateTable(): void
{
$createTable = new CreateTable('t');
$createTable->addConstraint(new Index('foo', 'my_idx', [10]));

static::assertSame(
"CREATE TABLE \"t\" ( \n INDEX \"my_idx\"(\"foo\"(10)) \n)",
$createTable->getSqlString(new TrustingSql92Platform()),
);
}

/**
* @param list<string> $columns
*/
#[Test]
#[DataProvider('unnamedIndexProvider')]
public function rendersUnnamedIndexInAlterTableAdd(
Index $index,
string $expectedSpec,
array $columns,
string $expectedSql,
): void {
$alterTable = new AlterTable('t');
$alterTable->addConstraint($index);

static::assertSame(
"ALTER TABLE \"t\"\n ADD {$expectedSql}",
$alterTable->getSqlString(new TrustingSql92Platform()),
);
}

/**
* @param list<string> $columns
*/
#[Test]
#[DataProvider('unnamedIndexProvider')]
public function rendersUnnamedIndexInCreateTable(
Index $index,
string $expectedSpec,
array $columns,
string $expectedSql,
): void {
$createTable = new CreateTable('t');
$createTable->addConstraint($index);

static::assertSame(
"CREATE TABLE \"t\" ( \n {$expectedSql} \n)",
$createTable->getSqlString(new TrustingSql92Platform()),
);
}

#[Test]
public function setTypeAndGetType(): void
{
Expand Down
Loading