Passed
Push — master ( cfe060...447357 )
by Alexander
03:18
created

QueryBuilderTest   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 418
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 252
c 0
b 0
f 0
dl 0
loc 418
rs 10
wmc 15
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql\Tests;
6
7
use Yiisoft\Db\Expression\ArrayExpression;
8
use Yiisoft\Db\Expression\Expression;
9
use Yiisoft\Db\Expression\JsonExpression;
10
use Yiisoft\Db\Query\Query;
11
use Yiisoft\Db\Pgsql\Schema\Schema;
12
use Yiisoft\Db\Tests\TraversableObject;
13
use Yiisoft\Db\Tests\QueryBuilderTest as AbstractQueryBuilderTest;
14
15
class QueryBuilderTest extends AbstractQueryBuilderTest
16
{
17
    protected ?string $driverName = 'pgsql';
18
19
    public function columnTypes(): array
20
    {
21
        $columns = [
22
            [
23
                Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT TRUE',
24
                $this->boolean()->notNull()->defaultValue(true),
25
                'boolean NOT NULL DEFAULT TRUE',
26
            ],
27
            [
28
                Schema::TYPE_CHAR . ' CHECK (value LIKE \'test%\')',
29
                $this->char()->check('value LIKE \'test%\''),
30
                'char(1) CHECK (value LIKE \'test%\')',
31
            ],
32
            [
33
                Schema::TYPE_CHAR . '(6) CHECK (value LIKE \'test%\')',
34
                $this->char(6)->check('value LIKE \'test%\''),
35
                'char(6) CHECK (value LIKE \'test%\')',
36
            ],
37
            [
38
                Schema::TYPE_CHAR . '(6)',
39
                $this->char(6)->unsigned(),
40
                'char(6)',
41
            ],
42
            [
43
                Schema::TYPE_INTEGER . '(8)',
44
                $this->integer(8)->unsigned(),
45
                'integer',
46
            ],
47
            [
48
                Schema::TYPE_TIMESTAMP . '(4)',
49
                $this->timestamp(4),
50
                'timestamp(4)',
51
            ],
52
            [
53
                Schema::TYPE_JSON,
54
                $this->json(),
55
                "jsonb",
56
            ],
57
        ];
58
59
        return array_merge(parent::columnTypes(), $columns);
60
    }
61
62
    public function conditionProvider(): array
63
    {
64
        $db = $this->createConnection();
65
66
        return array_merge(parent::conditionProvider(), [
67
            /**
68
             * adding conditions for ILIKE i.e. case insensitive LIKE.
69
             *
70
             * {@see http://www.postgresql.org/docs/8.3/static/functions-matching.html#FUNCTIONS-LIKE}
71
             */
72
73
            /** empty values */
74
            [['ilike', 'name', []], '0=1', []],
75
            [['not ilike', 'name', []], '', []],
76
            [['or ilike', 'name', []], '0=1', []],
77
            [['or not ilike', 'name', []], '', []],
78
79
            /** simple ilike */
80
            [['ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%']],
81
            [['not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%']],
82
            [['or ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%']],
83
            [['or not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%']],
84
85
            /** ilike for many values */
86
            [['ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 AND "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']],
87
            [['not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 AND "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']],
88
            [['or ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 OR "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']],
89
            [['or not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 OR "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']],
90
91
            /** array condition corner cases */
92
            [['@>', 'id', new ArrayExpression([1])], '"id" @> ARRAY[:qp0]', [':qp0' => 1]],
93
            'scalar can not be converted to array #1' => [['@>', 'id', new ArrayExpression(1)], '"id" @> ARRAY[]', []],
94
            ['scalar can not be converted to array #2' => ['@>', 'id', new ArrayExpression(false)], '"id" @> ARRAY[]', []],
95
            [['&&', 'price', new ArrayExpression([12, 14], 'float')], '"price" && ARRAY[:qp0, :qp1]::float[]', [':qp0' => 12, ':qp1' => 14]],
96
            [['@>', 'id', new ArrayExpression([2, 3])], '"id" @> ARRAY[:qp0, :qp1]', [':qp0' => 2, ':qp1' => 3]],
97
            'array of arrays' => [['@>', 'id', new ArrayExpression([[1,2], [3,4]], 'float', 2)], '"id" @> ARRAY[ARRAY[:qp0, :qp1]::float[], ARRAY[:qp2, :qp3]::float[]\\]::float[][]', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3, ':qp3' => 4]],
98
            [['@>', 'id', new ArrayExpression([])], '"id" @> ARRAY[]', []],
99
            'array can contain nulls' => [['@>', 'id', new ArrayExpression([null])], '"id" @> ARRAY[:qp0]', [':qp0' => null]],
100
            'traversable objects are supported' => [['@>', 'id', new ArrayExpression(new TraversableObject([1, 2, 3]))], '[[id]] @> ARRAY[:qp0, :qp1, :qp2]', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]],
101
            [['@>', 'time', new ArrayExpression([new Expression('now()')])], '[[time]] @> ARRAY[now()]', []],
102
            [['@>', 'id', new ArrayExpression((new Query($db))->select('id')->from('users')->where(['active' => 1]))], '[[id]] @> ARRAY(SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]],
103
            [['@>', 'id', new ArrayExpression([(new Query($db))->select('id')->from('users')->where(['active' => 1])], 'integer')], '[[id]] @> ARRAY[ARRAY(SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)::integer[]]::integer[]', [':qp0' => 1]],
104
105
            /** json conditions */
106
            [['=', 'jsoncol', new JsonExpression(['lang' => 'uk', 'country' => 'UA'])], '[[jsoncol]] = :qp0', [':qp0' => '{"lang":"uk","country":"UA"}']],
107
            [['=', 'jsoncol', new JsonExpression([false])], '[[jsoncol]] = :qp0', [':qp0' => '[false]']],
108
            [['=', 'prices', new JsonExpression(['seeds' => 15, 'apples' => 25], 'jsonb')], '[[prices]] = :qp0::jsonb', [':qp0' => '{"seeds":15,"apples":25}']],
109
            'nested json' => [
110
                ['=', 'data', new JsonExpression(['user' => ['login' => 'silverfire', 'password' => 'c4ny0ur34d17?'], 'props' => ['mood' => 'good']])],
111
                '"data" = :qp0', [':qp0' => '{"user":{"login":"silverfire","password":"c4ny0ur34d17?"},"props":{"mood":"good"}}']
112
            ],
113
            'null value' => [['=', 'jsoncol', new JsonExpression(null)], '"jsoncol" = :qp0', [':qp0' => 'null']],
114
            'null as array value' => [['=', 'jsoncol', new JsonExpression([null])], '"jsoncol" = :qp0', [':qp0' => '[null]']],
115
            'null as object value' => [['=', 'jsoncol', new JsonExpression(['nil' => null])], '"jsoncol" = :qp0', [':qp0' => '{"nil":null}']],
116
117
            'query' => [['=', 'jsoncol', new JsonExpression((new Query($db))->select('params')->from('user')->where(['id' => 1]))], '[[jsoncol]] = (SELECT [[params]] FROM [[user]] WHERE [[id]]=:qp0)', [':qp0' => 1]],
118
            'query with type' => [['=', 'jsoncol', new JsonExpression((new Query($db))->select('params')->from('user')->where(['id' => 1]), 'jsonb')], '[[jsoncol]] = (SELECT [[params]] FROM [[user]] WHERE [[id]]=:qp0)::jsonb', [':qp0' => 1]],
119
120
            'array of json expressions' => [
121
                ['=', 'colname', new ArrayExpression([new JsonExpression(['a' => null, 'b' => 123, 'c' => [4, 5]]), new JsonExpression([true])])],
122
                '"colname" = ARRAY[:qp0, :qp1]',
123
                [':qp0' => '{"a":null,"b":123,"c":[4,5]}', ':qp1' => '[true]']
124
            ],
125
            'Items in ArrayExpression of type json should be casted to Json' => [
126
                ['=', 'colname', new ArrayExpression([['a' => null, 'b' => 123, 'c' => [4, 5]], [true]], 'json')],
127
                '"colname" = ARRAY[:qp0, :qp1]::json[]',
128
                [':qp0' => '{"a":null,"b":123,"c":[4,5]}', ':qp1' => '[true]']
129
            ],
130
            'Two dimension array of text' => [
131
                ['=', 'colname', new ArrayExpression([['text1', 'text2'], ['text3', 'text4'], [null, 'text5']], 'text', 2)],
132
                '"colname" = ARRAY[ARRAY[:qp0, :qp1]::text[], ARRAY[:qp2, :qp3]::text[], ARRAY[:qp4, :qp5]::text[]]::text[][]',
133
                [':qp0' => 'text1', ':qp1' => 'text2', ':qp2' => 'text3', ':qp3' => 'text4', ':qp4' => null, ':qp5' => 'text5'],
134
            ],
135
            'Three dimension array of booleans' => [
136
                ['=', 'colname', new ArrayExpression([[[true], [false, null]], [[false], [true], [false]], [['t', 'f']]], 'bool', 3)],
137
                '"colname" = ARRAY[ARRAY[ARRAY[:qp0]::bool[], ARRAY[:qp1, :qp2]::bool[]]::bool[][], ARRAY[ARRAY[:qp3]::bool[], ARRAY[:qp4]::bool[], ARRAY[:qp5]::bool[]]::bool[][], ARRAY[ARRAY[:qp6, :qp7]::bool[]]::bool[][]]::bool[][][]',
138
                [':qp0' => true, ':qp1' => false, ':qp2' => null, ':qp3' => false, ':qp4' => true, ':qp5' => false, ':qp6' => 't', ':qp7' => 'f'],
139
            ],
140
141
            /** Checks to verity that operators work correctly */
142
            [['@>', 'id', new ArrayExpression([1])], '"id" @> ARRAY[:qp0]', [':qp0' => 1]],
143
            [['<@', 'id', new ArrayExpression([1])], '"id" <@ ARRAY[:qp0]', [':qp0' => 1]],
144
            [['=', 'id',  new ArrayExpression([1])], '"id" = ARRAY[:qp0]', [':qp0' => 1]],
145
            [['<>', 'id', new ArrayExpression([1])], '"id" <> ARRAY[:qp0]', [':qp0' => 1]],
146
            [['>', 'id',  new ArrayExpression([1])], '"id" > ARRAY[:qp0]', [':qp0' => 1]],
147
            [['<', 'id',  new ArrayExpression([1])], '"id" < ARRAY[:qp0]', [':qp0' => 1]],
148
            [['>=', 'id', new ArrayExpression([1])], '"id" >= ARRAY[:qp0]', [':qp0' => 1]],
149
            [['<=', 'id', new ArrayExpression([1])], '"id" <= ARRAY[:qp0]', [':qp0' => 1]],
150
            [['&&', 'id', new ArrayExpression([1])], '"id" && ARRAY[:qp0]', [':qp0' => 1]],
151
        ]);
152
    }
153
154
    public function testAlterColumn(): void
155
    {
156
        $qb = $this->getQueryBuilder();
157
158
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" DROP NOT NULL';
159
        $sql = $qb->alterColumn('foo1', 'bar', 'varchar(255)');
160
        $this->assertEquals($expected, $sql);
161
162
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" SET NOT null';
163
        $sql = $qb->alterColumn('foo1', 'bar', 'SET NOT null');
164
        $this->assertEquals($expected, $sql);
165
166
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" drop default';
167
        $sql = $qb->alterColumn('foo1', 'bar', 'drop default');
168
        $this->assertEquals($expected, $sql);
169
170
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" reset xyz';
171
        $sql = $qb->alterColumn('foo1', 'bar', 'reset xyz');
172
        $this->assertEquals($expected, $sql);
173
174
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" DROP NOT NULL';
175
176
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255));
177
        $this->assertEquals($expected, $sql);
178
179
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" SET NOT NULL';
180
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255)->notNull());
181
        $this->assertEquals($expected, $sql);
182
183
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" DROP NOT NULL, ADD CONSTRAINT foo1_bar_check CHECK (char_length(bar) > 5)';
184
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255)->check('char_length(bar) > 5'));
185
        $this->assertEquals($expected, $sql);
186
187
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" SET DEFAULT \'\', ALTER COLUMN "bar" DROP NOT NULL';
188
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255)->defaultValue(''));
189
        $this->assertEquals($expected, $sql);
190
191
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" SET DEFAULT \'AbCdE\', ALTER COLUMN "bar" DROP NOT NULL';
192
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255)->defaultValue('AbCdE'));
193
        $this->assertEquals($expected, $sql);
194
195
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE timestamp(0), ALTER COLUMN "bar" SET DEFAULT CURRENT_TIMESTAMP, ALTER COLUMN "bar" DROP NOT NULL';
196
        $sql = $qb->alterColumn('foo1', 'bar', $this->timestamp()->defaultExpression('CURRENT_TIMESTAMP'));
197
        $this->assertEquals($expected, $sql);
198
199
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(30), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" DROP NOT NULL, ADD UNIQUE ("bar")';
200
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(30)->unique());
201
        $this->assertEquals($expected, $sql);
202
    }
203
204
    public function indexesProvider(): array
205
    {
206
        $result = parent::indexesProvider();
207
        $result['drop'][0] = 'DROP INDEX [[CN_constraints_2_single]]';
208
209
        return $result;
210
    }
211
212
    public function defaultValuesProvider(): void
213
    {
214
        $this->markTestSkipped('Adding/dropping default constraints is not supported in PostgreSQL.');
215
    }
216
217
    public function testCommentColumn(): void
218
    {
219
        $qb = $this->getQueryBuilder();
220
221
        $expected = "COMMENT ON COLUMN [[comment]].[[text]] IS 'This is my column.'";
222
        $sql = $qb->addCommentOnColumn('comment', 'text', 'This is my column.');
223
        $this->assertEquals($this->replaceQuotes($expected), $sql);
224
225
        $expected = 'COMMENT ON COLUMN [[comment]].[[text]] IS NULL';
226
        $sql = $qb->dropCommentFromColumn('comment', 'text');
227
        $this->assertEquals($this->replaceQuotes($expected), $sql);
228
    }
229
230
    public function testCommentTable(): void
231
    {
232
        $qb = $this->getQueryBuilder();
233
234
        $expected = "COMMENT ON TABLE [[comment]] IS 'This is my table.'";
235
        $sql = $qb->addCommentOnTable('comment', 'This is my table.');
236
        $this->assertEquals($this->replaceQuotes($expected), $sql);
237
238
        $expected = 'COMMENT ON TABLE [[comment]] IS NULL';
239
        $sql = $qb->dropCommentFromTable('comment');
240
        $this->assertEquals($this->replaceQuotes($expected), $sql);
241
    }
242
243
    public function batchInsertProvider(): array
244
    {
245
        $data = parent::batchInsertProvider();
246
247
        $data['escape-danger-chars']['expected'] = "INSERT INTO \"customer\" (\"address\") VALUES ('SQL-danger chars are escaped: ''); --')";
248
        $data['bool-false, bool2-null']['expected'] = 'INSERT INTO "type" ("bool_col", "bool_col2") VALUES (FALSE, NULL)';
249
        $data['bool-false, time-now()']['expected'] = 'INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (FALSE, now())';
250
251
        return $data;
252
    }
253
254
    public function testResetSequence(): void
255
    {
256
        $qb = $this->getQueryBuilder();
257
258
        $expected = "SELECT SETVAL('\"item_id_seq\"',(SELECT COALESCE(MAX(\"id\"),0) FROM \"item\")+1,false)";
259
        $sql = $qb->resetSequence('item');
260
        $this->assertEquals($expected, $sql);
261
262
        $expected = "SELECT SETVAL('\"item_id_seq\"',4,false)";
263
        $sql = $qb->resetSequence('item', 4);
264
        $this->assertEquals($expected, $sql);
265
    }
266
267
    public function testResetSequencePostgres12(): void
268
    {
269
        if (version_compare($this->getConnection(false)->getServerVersion(), '12.0', '<')) {
270
            $this->markTestSkipped('PostgreSQL < 12.0 does not support GENERATED AS IDENTITY columns.');
271
        }
272
273
        $config = $this->database;
274
        unset($config['fixture']);
275
        $this->prepareDatabase($config, \realpath(__DIR__ . '/../../../data') . '/postgres12.sql');
276
277
        $qb = $this->getQueryBuilder(false);
278
279
        $expected = "SELECT SETVAL('\"item_12_id_seq\"',(SELECT COALESCE(MAX(\"id\"),0) FROM \"item_12\")+1,false)";
280
        $sql = $qb->resetSequence('item_12');
281
        $this->assertEquals($expected, $sql);
282
283
        $expected = "SELECT SETVAL('\"item_12_id_seq\"',4,false)";
284
        $sql = $qb->resetSequence('item_12', 4);
285
        $this->assertEquals($expected, $sql);
286
    }
287
288
    public function upsertProvider(): array
289
    {
290
        $concreteData = [
291
            'regular values' => [
292
                3 => [
293
                    'WITH "EXCLUDED" ("email", "address", "status", "profile_id") AS (VALUES (CAST(:qp0 AS varchar), CAST(:qp1 AS text), CAST(:qp2 AS int2), CAST(:qp3 AS int4))), "upsert" AS (UPDATE "T_upsert" SET "address"="EXCLUDED"."address", "status"="EXCLUDED"."status", "profile_id"="EXCLUDED"."profile_id" FROM "EXCLUDED" WHERE (("T_upsert"."email"="EXCLUDED"."email")) RETURNING "T_upsert".*) INSERT INTO "T_upsert" ("email", "address", "status", "profile_id") SELECT "email", "address", "status", "profile_id" FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "upsert" WHERE (("upsert"."email"="EXCLUDED"."email")))',
294
                    'INSERT INTO "T_upsert" ("email", "address", "status", "profile_id") VALUES (:qp0, :qp1, :qp2, :qp3) ON CONFLICT ("email") DO UPDATE SET "address"=EXCLUDED."address", "status"=EXCLUDED."status", "profile_id"=EXCLUDED."profile_id"',
295
                ],
296
                4 => [
297
                    [
298
                        ':qp0' => '[email protected]',
299
                        ':qp1' => 'bar {{city}}',
300
                        ':qp2' => 1,
301
                        ':qp3' => null,
302
                    ],
303
                ],
304
            ],
305
            'regular values with update part' => [
306
                3 => [
307
                    'WITH "EXCLUDED" ("email", "address", "status", "profile_id") AS (VALUES (CAST(:qp0 AS varchar), CAST(:qp1 AS text), CAST(:qp2 AS int2), CAST(:qp3 AS int4))), "upsert" AS (UPDATE "T_upsert" SET "address"=:qp4, "status"=:qp5, "orders"=T_upsert.orders + 1 FROM "EXCLUDED" WHERE (("T_upsert"."email"="EXCLUDED"."email")) RETURNING "T_upsert".*) INSERT INTO "T_upsert" ("email", "address", "status", "profile_id") SELECT "email", "address", "status", "profile_id" FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "upsert" WHERE (("upsert"."email"="EXCLUDED"."email")))',
308
                    'INSERT INTO "T_upsert" ("email", "address", "status", "profile_id") VALUES (:qp0, :qp1, :qp2, :qp3) ON CONFLICT ("email") DO UPDATE SET "address"=:qp4, "status"=:qp5, "orders"=T_upsert.orders + 1',
309
                ],
310
                4 => [
311
                    [
312
                        ':qp0' => '[email protected]',
313
                        ':qp1' => 'bar {{city}}',
314
                        ':qp2' => 1,
315
                        ':qp3' => null,
316
                        ':qp4' => 'foo {{city}}',
317
                        ':qp5' => 2,
318
                    ],
319
                ],
320
            ],
321
            'regular values without update part' => [
322
                3 => [
323
                    'WITH "EXCLUDED" ("email", "address", "status", "profile_id") AS (VALUES (CAST(:qp0 AS varchar), CAST(:qp1 AS text), CAST(:qp2 AS int2), CAST(:qp3 AS int4))) INSERT INTO "T_upsert" ("email", "address", "status", "profile_id") SELECT "email", "address", "status", "profile_id" FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "T_upsert" WHERE (("T_upsert"."email"="EXCLUDED"."email")))',
324
                    'INSERT INTO "T_upsert" ("email", "address", "status", "profile_id") VALUES (:qp0, :qp1, :qp2, :qp3) ON CONFLICT DO NOTHING',
325
                ],
326
                4 => [
327
                    [
328
                        ':qp0' => '[email protected]',
329
                        ':qp1' => 'bar {{city}}',
330
                        ':qp2' => 1,
331
                        ':qp3' => null,
332
                    ],
333
                ],
334
            ],
335
            'query' => [
336
                3 => [
337
                    'WITH "EXCLUDED" ("email", "status") AS (SELECT "email", 2 AS "status" FROM "customer" WHERE "name"=:qp0 LIMIT 1), "upsert" AS (UPDATE "T_upsert" SET "status"="EXCLUDED"."status" FROM "EXCLUDED" WHERE (("T_upsert"."email"="EXCLUDED"."email")) RETURNING "T_upsert".*) INSERT INTO "T_upsert" ("email", "status") SELECT "email", "status" FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "upsert" WHERE (("upsert"."email"="EXCLUDED"."email")))',
338
                    'INSERT INTO "T_upsert" ("email", "status") SELECT "email", 2 AS "status" FROM "customer" WHERE "name"=:qp0 LIMIT 1 ON CONFLICT ("email") DO UPDATE SET "status"=EXCLUDED."status"',
339
                ],
340
            ],
341
            'query with update part' => [
342
                3 => [
343
                    'WITH "EXCLUDED" ("email", "status") AS (SELECT "email", 2 AS "status" FROM "customer" WHERE "name"=:qp0 LIMIT 1), "upsert" AS (UPDATE "T_upsert" SET "address"=:qp1, "status"=:qp2, "orders"=T_upsert.orders + 1 FROM "EXCLUDED" WHERE (("T_upsert"."email"="EXCLUDED"."email")) RETURNING "T_upsert".*) INSERT INTO "T_upsert" ("email", "status") SELECT "email", "status" FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "upsert" WHERE (("upsert"."email"="EXCLUDED"."email")))',
344
                    'INSERT INTO "T_upsert" ("email", "status") SELECT "email", 2 AS "status" FROM "customer" WHERE "name"=:qp0 LIMIT 1 ON CONFLICT ("email") DO UPDATE SET "address"=:qp1, "status"=:qp2, "orders"=T_upsert.orders + 1',
345
                ],
346
            ],
347
            'query without update part' => [
348
                3 => [
349
                    'WITH "EXCLUDED" ("email", "status") AS (SELECT "email", 2 AS "status" FROM "customer" WHERE "name"=:qp0 LIMIT 1) INSERT INTO "T_upsert" ("email", "status") SELECT "email", "status" FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "T_upsert" WHERE (("T_upsert"."email"="EXCLUDED"."email")))',
350
                    'INSERT INTO "T_upsert" ("email", "status") SELECT "email", 2 AS "status" FROM "customer" WHERE "name"=:qp0 LIMIT 1 ON CONFLICT DO NOTHING',
351
                ],
352
            ],
353
            'values and expressions' => [
354
                3 => 'INSERT INTO {{%T_upsert}} ({{%T_upsert}}.[[email]], [[ts]]) VALUES (:qp0, now())',
355
            ],
356
            'values and expressions with update part' => [
357
                3 => 'INSERT INTO {{%T_upsert}} ({{%T_upsert}}.[[email]], [[ts]]) VALUES (:qp0, now())',
358
            ],
359
            'values and expressions without update part' => [
360
                3 => 'INSERT INTO {{%T_upsert}} ({{%T_upsert}}.[[email]], [[ts]]) VALUES (:qp0, now())',
361
            ],
362
            'query, values and expressions with update part' => [
363
                3 => [
364
                    'WITH "EXCLUDED" ("email", [[time]]) AS (SELECT :phEmail AS "email", now() AS [[time]]), "upsert" AS (UPDATE {{%T_upsert}} SET "ts"=:qp1, [[orders]]=T_upsert.orders + 1 FROM "EXCLUDED" WHERE (({{%T_upsert}}."email"="EXCLUDED"."email")) RETURNING {{%T_upsert}}.*) INSERT INTO {{%T_upsert}} ("email", [[time]]) SELECT "email", [[time]] FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "upsert" WHERE (("upsert"."email"="EXCLUDED"."email")))',
365
                    'INSERT INTO {{%T_upsert}} ("email", [[time]]) SELECT :phEmail AS "email", now() AS [[time]] ON CONFLICT ("email") DO UPDATE SET "ts"=:qp1, [[orders]]=T_upsert.orders + 1',
366
                ],
367
            ],
368
            'query, values and expressions without update part' => [
369
                3 => [
370
                    'WITH "EXCLUDED" ("email", [[time]]) AS (SELECT :phEmail AS "email", now() AS [[time]]), "upsert" AS (UPDATE {{%T_upsert}} SET "ts"=:qp1, [[orders]]=T_upsert.orders + 1 FROM "EXCLUDED" WHERE (({{%T_upsert}}."email"="EXCLUDED"."email")) RETURNING {{%T_upsert}}.*) INSERT INTO {{%T_upsert}} ("email", [[time]]) SELECT "email", [[time]] FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "upsert" WHERE (("upsert"."email"="EXCLUDED"."email")))',
371
                    'INSERT INTO {{%T_upsert}} ("email", [[time]]) SELECT :phEmail AS "email", now() AS [[time]] ON CONFLICT ("email") DO UPDATE SET "ts"=:qp1, [[orders]]=T_upsert.orders + 1',
372
                ],
373
            ],
374
            'no columns to update' => [
375
                3 => [
376
                    'WITH "EXCLUDED" ("a") AS (VALUES (CAST(:qp0 AS int2))) INSERT INTO "T_upsert_1" ("a") SELECT "a" FROM "EXCLUDED" WHERE NOT EXISTS (SELECT 1 FROM "T_upsert_1" WHERE (("T_upsert_1"."a"="EXCLUDED"."a")))',
377
                    'INSERT INTO "T_upsert_1" ("a") VALUES (:qp0) ON CONFLICT DO NOTHING',
378
                ],
379
            ],
380
        ];
381
        $newData = parent::upsertProvider();
382
        foreach ($concreteData as $testName => $data) {
383
            $newData[$testName] = \array_replace($newData[$testName], $data);
384
        }
385
        return $newData;
386
    }
387
388
    public function updateProvider(): array
389
    {
390
        $items = parent::updateProvider();
391
392
        $items[] = [
393
            'profile',
394
            [
395
                'description' => new JsonExpression(['abc' => 'def', 123, null]),
396
            ],
397
            [
398
                'id' => 1,
399
            ],
400
            $this->replaceQuotes('UPDATE [[profile]] SET [[description]]=:qp0 WHERE [[id]]=:qp1'),
401
            [
402
                ':qp0' => '{"abc":"def","0":123,"1":null}',
403
                ':qp1' => 1,
404
            ],
405
        ];
406
407
        return $items;
408
    }
409
410
    public function testDropIndex(): void
411
    {
412
        $qb = $this->getQueryBuilder();
413
414
        $expected = 'DROP INDEX "index"';
415
        $sql = $qb->dropIndex('index', '{{table}}');
416
        $this->assertEquals($expected, $sql);
417
418
        $expected = 'DROP INDEX "schema"."index"';
419
        $sql = $qb->dropIndex('index', '{{schema.table}}');
420
        $this->assertEquals($expected, $sql);
421
422
        $expected = 'DROP INDEX "schema"."index"';
423
        $sql = $qb->dropIndex('schema.index', '{{schema2.table}}');
424
        $this->assertEquals($expected, $sql);
425
426
        $expected = 'DROP INDEX "schema"."index"';
427
        $sql = $qb->dropIndex('index', '{{schema.%table}}');
428
        $this->assertEquals($expected, $sql);
429
430
        $expected = 'DROP INDEX {{%schema.index}}';
431
        $sql = $qb->dropIndex('index', '{{%schema.table}}');
432
        $this->assertEquals($expected, $sql);
433
    }
434
}
435