Skip to content

Commit

Permalink
Fluent: add table alias to INSERT (BC break)
Browse files Browse the repository at this point in the history
  • Loading branch information
forrest79 committed Jan 24, 2024
1 parent d32e12c commit e0bad85
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 46 deletions.
18 changes: 9 additions & 9 deletions docs/fluent.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ Every query is `SELECT` at first, until you call `->insert(...)`, `->update(...)
- `union($query)` (or `` / `` / ``) - connects two queries with `UNION`, `UNION ALL`, `INTERSECT` or `EXCEPT`. Query can be simple `string,` another `Query` or `Db\Sql`.


- `insert(?string $into = NULL, ?array $columns = [])` - sets query as `INSERT`. When the main table is not provided yet, you can set it or rewrite it with the `$into` parameter. If you want use `INSERT ... SELECT ...` you can provide column names in `$columns` parameter (only if column names for INSERT and SELECT differs).
- `insert(?string $into = NULL, string $alias = NULL, ?array $columns = [])` - sets query as `INSERT`. When the main table is not provided yet, you can set it or rewrite it with the `$into` parameter. If you want use `INSERT ... SELECT ...` you can provide column names in `$columns` parameter (only if column names for INSERT and SELECT differs).


- `values(array $data)` - sets data for insertion. Key is column name and value is inserted value. Value can be scalar or `Db\Sql`. Method can be called multiple times and provided data is merged.
Expand Down Expand Up @@ -303,7 +303,7 @@ $query = $connection
'phones' => Forrest79\PhPgSql\Db\Helper::createStringPgArray(['732123456', '736987654']),
]);

dump($query); // (Query) INSERT INTO users(nick, inserted_datetime, active, age, height_cm, phones) VALUES($1, now(), TRUE, $2, $3, $4) [Params: (array) ['James', 37, (NULL), '{\"732123456\",\"736987654\"}']]
dump($query); // (Query) INSERT INTO users (nick, inserted_datetime, active, age, height_cm, phones) VALUES($1, now(), TRUE, $2, $3, $4) [Params: (array) ['James', 37, (NULL), '{\"732123456\",\"736987654\"}']]

$result = $query->execute();

Expand Down Expand Up @@ -344,7 +344,7 @@ $query = $connection
['nick' => 'Zoey'],
]);

dump($query); // (Query) INSERT INTO users(nick) VALUES($1), ($2), ($3) [Params: (array) ['Luis', 'Gilbert', 'Zoey']]
dump($query); // (Query) INSERT INTO users (nick) VALUES($1), ($2), ($3) [Params: (array) ['Luis', 'Gilbert', 'Zoey']]

$insertedRows = $query->getAffectedRows();

Expand All @@ -355,7 +355,7 @@ Here are column names detected from the first row. You can also pass the columns

```php
$insertedRows = $connection
->insert('users', ['nick', 'age'])
->insert('users', columns: ['nick', 'age'])
->rows([
['Luis', 31],
['Gilbert', 18],
Expand All @@ -370,12 +370,12 @@ And of course, you can use `INSERT` - `SELECT`:

```php
$query = $connection
->insert('users', ['nick'])
->insert('users', columns: ['nick'])
->select(['name' || '\'_\'' || 'age'])
->from('departments')
->where('id', [1, 2]);

dump($query); // (Query) INSERT INTO users(nick) SELECT TRUE FROM departments WHERE id IN ($1, $2) [Params: (array) [1, 2]]
dump($query); // (Query) INSERT INTO users (nick) SELECT TRUE FROM departments WHERE id IN ($1, $2) [Params: (array) [1, 2]]

$insertedRows = $query->getAffectedRows();

Expand Down Expand Up @@ -480,17 +480,17 @@ $insertedOrUpdatedWithConstraintRows = $connection
dump($insertedOrUpdatedWithConstraintRows); // (integer) 1
```

And the last to use manully `SET` with string or also with parameters:
And the last to use manully `SET` with string (here we can use alias for `INTO` table) or also with parameters:

```php
$insertedOrUpdatedRows = $connection
->insert('users')
->insert('users', 'u')
->values([
'id' => '20',
'nick' => 'Jimmy',
])
->onConflict(['id'])
->doUpdate(['nick' => 'EXCLUDED.nick || users.id'])
->doUpdate(['nick' => 'EXCLUDED.nick || u.id'])
->getAffectedRows();

dump($insertedOrUpdatedRows); // (integer) 1
Expand Down
6 changes: 3 additions & 3 deletions docs/test-data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,20 @@ CREATE TABLE user_departments
FOREIGN KEY (department_id) REFERENCES departments (id) ON UPDATE RESTRICT ON DELETE CASCADE
);

INSERT INTO users(nick, inserted_datetime, active, age, height_cm, phones) VALUES
INSERT INTO users (nick, inserted_datetime, active, age, height_cm, phones) VALUES
('Bob', '2020-01-01 09:00:00', TRUE, 45, 178.2, ARRAY[200300, 487412]), -- ID: 1
('Brandon', '2020-01-02 12:05:00', TRUE, 24, 180.4, NULL), -- ID: 2
('Steve', '2020-01-02 12:05:00', FALSE, 41, 168.0, NULL), -- ID: 3
('Monica', '2020-01-03 13:10:00', TRUE, 36, 175.7, NULL), -- ID: 4
('Ingrid', '2020-01-04 14:15:00', TRUE, 18, 168.2, ARRAY[805305]); -- ID: 5

INSERT INTO departments(name, rooms, active) VALUES
INSERT INTO departments (name, rooms, active) VALUES
('IT', ARRAY['A103', 'B201', 'B202'], TRUE), -- ID: 1
('HR', ARRAY['A101', 'A102'], TRUE), -- ID: 2
('Sales', ARRAY['B210'], TRUE), -- ID: 3
('Drivers', ARRAY[]::text[], FALSE); -- ID: 4

INSERT INTO user_departments(user_id, department_id) VALUES
INSERT INTO user_departments (user_id, department_id) VALUES
(1, 1), -- ID: 1
(2, 1), -- ID: 2
(5, 1), -- ID: 3
Expand Down
4 changes: 2 additions & 2 deletions src/Fluent/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,9 @@ public function except(string|Query|Db\Sql $query): QueryExecute
* @param list<string>|NULL $columns
* @throws Exceptions\QueryException
*/
public function insert(string|NULL $into = NULL, array|NULL $columns = []): QueryExecute
public function insert(string|NULL $into = NULL, string|NULL $alias = NULL, array|NULL $columns = []): QueryExecute
{
return $this->createQuery()->insert($into, $columns);
return $this->createQuery()->insert($into, $alias, $columns);
}


Expand Down
4 changes: 2 additions & 2 deletions src/Fluent/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -559,14 +559,14 @@ private function addCombine(string $type, string|self|Db\Sql $query): static
* @param list<string>|NULL $columns
* @throws Exceptions\QueryException
*/
public function insert(string|NULL $into = NULL, array|NULL $columns = []): static
public function insert(string|NULL $into = NULL, string|NULL $alias = NULL, array|NULL $columns = []): static
{
$this->resetQuery();

$this->queryType = self::QUERY_INSERT;

if ($into !== NULL) {
$this->table($into);
$this->table($into, $alias);
}

$this->params[self::PARAM_INSERT_COLUMNS] = $columns;
Expand Down
2 changes: 1 addition & 1 deletion src/Fluent/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ private function createInsert(array $queryParams, array &$params): string
}

return $insert
. ($columns === ['*'] ? '' : '(' . \implode(', ', $columns) . ')')
. ($columns === ['*'] ? '' : ' (' . \implode(', ', $columns) . ')')
. $data
. $onConflict
. $this->getPrefixSuffix($queryParams, Query::PARAM_SUFFIX, $params)
Expand Down
2 changes: 1 addition & 1 deletion src/Fluent/Sql.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ function except(string|Query|Db\Sql $query): Query;
/**
* @param list<string>|NULL $columns
*/
function insert(string|NULL $into = NULL, array|NULL $columns = []): Query;
function insert(string|NULL $into = NULL, string|NULL $alias = NULL, array|NULL $columns = []): Query;


/**
Expand Down
2 changes: 1 addition & 1 deletion tests/Integration/QueryExecuteFetchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ public function testAffectedRows(): void
');

$query = $this->connection
->insert('test', ['name'])
->insert('test', columns: ['name'])
->select(['\'name\' || generate_series FROM generate_series(3, 1, -1)']);

Tester\Assert::same(3, $query->getAffectedRows());
Expand Down
14 changes: 7 additions & 7 deletions tests/Unit/FluentConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ public function testInsert(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column) VALUES($1)', $query->getSql());
Tester\Assert::same('INSERT INTO table (column) VALUES($1)', $query->getSql());
Tester\Assert::same([1], $query->getParams());
}

Expand All @@ -461,7 +461,7 @@ public function testValues(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column) VALUES($1)', $query->getSql());
Tester\Assert::same('INSERT INTO table (column) VALUES($1)', $query->getSql());
Tester\Assert::same([1], $query->getParams());
}

Expand All @@ -477,7 +477,7 @@ public function testRows(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column) VALUES($1), ($2)', $query->getSql());
Tester\Assert::same('INSERT INTO table (column) VALUES($1), ($2)', $query->getSql());
Tester\Assert::same([1, 2], $query->getParams());
}

Expand All @@ -495,7 +495,7 @@ public function testOnConflict(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, info) VALUES($1, $2) ON CONFLICT DO NOTHING', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, info) VALUES($1, $2) ON CONFLICT DO NOTHING', $query->getSql());
Tester\Assert::same(['Bob', 'Text'], $query->getParams());
}

Expand All @@ -513,7 +513,7 @@ public function testDoUpdate(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info', $query->getSql());
Tester\Assert::same(['Bob', 'Text'], $query->getParams());
}

Expand All @@ -531,7 +531,7 @@ public function testDoNothing(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, info) VALUES($1, $2) ON CONFLICT DO NOTHING', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, info) VALUES($1, $2) ON CONFLICT DO NOTHING', $query->getSql());
Tester\Assert::same(['Bob', 'Text'], $query->getParams());
}

Expand Down Expand Up @@ -583,7 +583,7 @@ public function testReturning(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column) VALUES($1) RETURNING column', $query->getSql());
Tester\Assert::same('INSERT INTO table (column) VALUES($1) RETURNING column', $query->getSql());
Tester\Assert::same([1], $query->getParams());
}

Expand Down
40 changes: 20 additions & 20 deletions tests/Unit/FluentQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ public function testInsertRow(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column, column_from, column_fluent_query, column_query) VALUES($1, 3, (SELECT \'test_fluent\' WHERE 4 = $2), (SELECT \'test\' WHERE 5 = $3)) RETURNING column', $query->getSql());
Tester\Assert::same('INSERT INTO table (column, column_from, column_fluent_query, column_query) VALUES($1, 3, (SELECT \'test_fluent\' WHERE 4 = $2), (SELECT \'test\' WHERE 5 = $3)) RETURNING column', $query->getSql());
Tester\Assert::same([1, 4, 5], $query->getParams());
}

Expand All @@ -707,7 +707,7 @@ public function testInsertMergeData(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column2, column3, column1) VALUES($1, $2, $3)', $query->getSql());
Tester\Assert::same('INSERT INTO table (column2, column3, column1) VALUES($1, $2, $3)', $query->getSql());
Tester\Assert::same([2, 1, 3], $query->getParams());
}

Expand All @@ -728,7 +728,7 @@ public function testInsertRows(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column) VALUES($1), ($2), ($3), (4), ((SELECT \'test_fluent\' WHERE 6 = $4)), ((SELECT \'test\' WHERE 7 = $5)) RETURNING column', $query->getSql());
Tester\Assert::same('INSERT INTO table (column) VALUES($1), ($2), ($3), (4), ((SELECT \'test_fluent\' WHERE 6 = $4)), ((SELECT \'test\' WHERE 7 = $5)) RETURNING column', $query->getSql());
Tester\Assert::same([1, 2, 3, 6, 7], $query->getParams());
}

Expand All @@ -748,22 +748,22 @@ public function testInsertRowsMergeData(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column) VALUES($1), ($2), ($3), ($4)', $query->getSql());
Tester\Assert::same('INSERT INTO table (column) VALUES($1), ($2), ($3), ($4)', $query->getSql());
Tester\Assert::same([1, 2, 3, 4], $query->getParams());
}


public function testInsertSelect(): void
{
$query = $this->query()
->insert('table', ['name'])
->insert('table', columns: ['name'])
->select(['column'])
->from('table2', 't2')
->returning(['name'])
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name) SELECT column FROM table2 AS t2 RETURNING name', $query->getSql());
Tester\Assert::same('INSERT INTO table (name) SELECT column FROM table2 AS t2 RETURNING name', $query->getSql());
Tester\Assert::same([], $query->getParams());
}

Expand All @@ -778,7 +778,7 @@ public function testInsertSelectDetectColumnsFromSelect(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column, name) SELECT column, column2 AS "name" FROM table2 AS t2 RETURNING column', $query->getSql());
Tester\Assert::same('INSERT INTO table (column, name) SELECT column, column2 AS "name" FROM table2 AS t2 RETURNING column', $query->getSql());
Tester\Assert::same([], $query->getParams());
}

Expand Down Expand Up @@ -810,7 +810,7 @@ public function testInsertOnConflictDoUpdate(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info', $query->getSql());
Tester\Assert::same(['Bob', 'Text'], $query->getParams());
}

Expand All @@ -829,7 +829,7 @@ public function testInsertOnConflictWithWhereDoUpdate(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, age, info) VALUES($1, $2, $3) ON CONFLICT (name, age) WHERE age < $4 DO UPDATE SET info = EXCLUDED.info', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, age, info) VALUES($1, $2, $3) ON CONFLICT (name, age) WHERE age < $4 DO UPDATE SET info = EXCLUDED.info', $query->getSql());
Tester\Assert::same(['Bob', 20, 'Text', 30], $query->getParams());
}

Expand All @@ -848,7 +848,7 @@ public function testInsertOnConflictConstraintDoUpdate(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, age, info) VALUES($1, $2, $3) ON CONFLICT ON CONSTRAINT name_ukey DO UPDATE SET info = EXCLUDED.info', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, age, info) VALUES($1, $2, $3) ON CONFLICT ON CONSTRAINT name_ukey DO UPDATE SET info = EXCLUDED.info', $query->getSql());
Tester\Assert::same(['Bob', 20, 'Text'], $query->getParams());
}

Expand All @@ -873,17 +873,17 @@ public function testInsertOnConflictConstraintWithWhereDoUpdate(): void
public function testInsertOnConflictDoUpdateWithComplexSet(): void
{
$query = $this->query()
->insert('table')
->insert('table', 't')
->values([
'name' => 'Bob',
'info' => 'Text',
])
->onConflict(['name'])
->doUpdate(['info', 'name' => 'EXCLUDED.name || table.age'])
->doUpdate(['info', 'name' => 'EXCLUDED.name || t.age'])
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info, name = EXCLUDED.name || table.age', $query->getSql());
Tester\Assert::same('INSERT INTO table AS t (name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info, name = EXCLUDED.name || t.age', $query->getSql());
Tester\Assert::same(['Bob', 'Text'], $query->getParams());
}

Expand All @@ -901,7 +901,7 @@ public function testInsertOnConflictDoUpdateWithExpressionSet(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info, name = EXCLUDED.name || $3', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info, name = EXCLUDED.name || $3', $query->getSql());
Tester\Assert::same(['Bob', 'Text', 'Jimmy'], $query->getParams());
}

Expand All @@ -920,7 +920,7 @@ public function testInsertOnConflictDoUpdateWithWhere(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, age, info) VALUES($1, $2, $3) ON CONFLICT (name, age) DO UPDATE SET info = EXCLUDED.info WHERE age < $4', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, age, info) VALUES($1, $2, $3) ON CONFLICT (name, age) DO UPDATE SET info = EXCLUDED.info WHERE age < $4', $query->getSql());
Tester\Assert::same(['Bob', 20, 'Text', 30], $query->getParams());
}

Expand All @@ -938,7 +938,7 @@ public function testInsertOnConflictDoNothing(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, info) VALUES($1, $2) ON CONFLICT DO NOTHING', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, info) VALUES($1, $2) ON CONFLICT DO NOTHING', $query->getSql());
Tester\Assert::same(['Bob', 'Text'], $query->getParams());
}

Expand All @@ -957,7 +957,7 @@ public function testInsertOnConflictWithReturning(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info RETURNING id', $query->getSql());
Tester\Assert::same('INSERT INTO table (name, info) VALUES($1, $2) ON CONFLICT (name) DO UPDATE SET info = EXCLUDED.info RETURNING id', $query->getSql());
Tester\Assert::same(['Bob', 'Text'], $query->getParams());
}

Expand Down Expand Up @@ -1405,7 +1405,7 @@ public function testWithSuffix(): void
public function testWithNotMaterialized(): void
{
$query = $this->query()
->with('w', 'SELECT * FROM big_table', NULL, TRUE)
->with('w', 'SELECT * FROM big_table', notMaterialized: TRUE)
->select(['*'])
->from('w', 'w1')
->join('w', 'w2', 'w1.key = w2.ref')
Expand Down Expand Up @@ -1541,7 +1541,7 @@ public function testSuffixWithReturning(): void
->createSqlQuery()
->createQuery();

Tester\Assert::same('INSERT INTO table(column) VALUES($1) ON CONFLICT (column) DO NOTHING RETURNING column', $query->getSql());
Tester\Assert::same('INSERT INTO table (column) VALUES($1) ON CONFLICT (column) DO NOTHING RETURNING column', $query->getSql());
Tester\Assert::same(['value'], $query->getParams());

$query = $this->query()
Expand Down Expand Up @@ -1697,7 +1697,7 @@ public function testHas(): void
Tester\Assert::true($query->has($query::PARAM_PREFIX));
Tester\Assert::true($query->has($query::PARAM_SUFFIX));

$query = $this->query()->insert('table', ['column'])->select(['1'])->returning(['column']);
$query = $this->query()->insert('table', columns: ['column'])->select(['1'])->returning(['column']);

Tester\Assert::true($query->has($query::PARAM_INSERT_COLUMNS));
Tester\Assert::true($query->has($query::PARAM_RETURNING));
Expand Down

0 comments on commit e0bad85

Please sign in to comment.