Passed
Push — master ( bff06a...77db42 )
by Alexander
01:45
created

QueryBuilderTest::testResetSequence()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql\Tests;
6
7
use Yiisoft\Db\Expressions\ArrayExpression;
8
use Yiisoft\Db\Expressions\Expression;
9
use Yiisoft\Db\Expressions\JsonExpression;
10
use Yiisoft\Db\Querys\Query;
11
use Yiisoft\Db\Pgsql\Schema;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Pgsql\Schema was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Yiisoft\Db\Tests\TraversableObject;
13
use Yiisoft\Db\Tests\QueryBuilderTest as AbstractQueryBuilderTest;
14
15
class QueryBuilderTest extends AbstractQueryBuilderTest
16
{
17
    public ?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
            // adding conditions for ILIKE i.e. case insensitive LIKE
68
            // http://www.postgresql.org/docs/8.3/static/functions-matching.html#FUNCTIONS-LIKE
69
70
            // empty values
71
            [['ilike', 'name', []], '0=1', []],
72
            [['not ilike', 'name', []], '', []],
73
            [['or ilike', 'name', []], '0=1', []],
74
            [['or not ilike', 'name', []], '', []],
75
76
            // simple ilike
77
            [['ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%']],
78
            [['not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%']],
79
            [['or ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%']],
80
            [['or not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%']],
81
82
            // ilike for many values
83
            [['ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 AND "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']],
84
            [['not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 AND "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']],
85
            [['or ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 OR "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']],
86
            [['or not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 OR "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']],
87
88
            // array condition corner cases
89
            [['@>', 'id', new ArrayExpression([1])], '"id" @> ARRAY[:qp0]', [':qp0' => 1]],
90
            'scalar can not be converted to array #1' => [['@>', 'id', new ArrayExpression(1)], '"id" @> ARRAY[]', []],
91
            ['scalar can not be converted to array #2' => ['@>', 'id', new ArrayExpression(false)], '"id" @> ARRAY[]', []],
92
            [['&&', 'price', new ArrayExpression([12, 14], 'float')], '"price" && ARRAY[:qp0, :qp1]::float[]', [':qp0' => 12, ':qp1' => 14]],
93
            [['@>', 'id', new ArrayExpression([2, 3])], '"id" @> ARRAY[:qp0, :qp1]', [':qp0' => 2, ':qp1' => 3]],
94
            '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]],
95
            [['@>', 'id', new ArrayExpression([])], '"id" @> ARRAY[]', []],
96
            'array can contain nulls' => [['@>', 'id', new ArrayExpression([null])], '"id" @> ARRAY[:qp0]', [':qp0' => null]],
97
            'traversable objects are supported' => [['@>', 'id', new ArrayExpression(new TraversableObject([1, 2, 3]))], '[[id]] @> ARRAY[:qp0, :qp1, :qp2]', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]],
98
            [['@>', 'time', new ArrayExpression([new Expression('now()')])], '[[time]] @> ARRAY[now()]', []],
99
            [['@>', 'id', new ArrayExpression((new Query($db))->select('id')->from('users')->where(['active' => 1]))], '[[id]] @> ARRAY(SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]],
100
            [['@>', '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]],
101
102
            // json conditions
103
            [['=', 'jsoncol', new JsonExpression(['lang' => 'uk', 'country' => 'UA'])], '[[jsoncol]] = :qp0', [':qp0' => '{"lang":"uk","country":"UA"}']],
104
            [['=', 'jsoncol', new JsonExpression([false])], '[[jsoncol]] = :qp0', [':qp0' => '[false]']],
105
            [['=', 'prices', new JsonExpression(['seeds' => 15, 'apples' => 25], 'jsonb')], '[[prices]] = :qp0::jsonb', [':qp0' => '{"seeds":15,"apples":25}']],
106
            'nested json' => [
107
                ['=', 'data', new JsonExpression(['user' => ['login' => 'silverfire', 'password' => 'c4ny0ur34d17?'], 'props' => ['mood' => 'good']])],
108
                '"data" = :qp0', [':qp0' => '{"user":{"login":"silverfire","password":"c4ny0ur34d17?"},"props":{"mood":"good"}}']
109
            ],
110
            'null value' => [['=', 'jsoncol', new JsonExpression(null)], '"jsoncol" = :qp0', [':qp0' => 'null']],
111
            'null as array value' => [['=', 'jsoncol', new JsonExpression([null])], '"jsoncol" = :qp0', [':qp0' => '[null]']],
112
            'null as object value' => [['=', 'jsoncol', new JsonExpression(['nil' => null])], '"jsoncol" = :qp0', [':qp0' => '{"nil":null}']],
113
114
            //[['=', 'jsoncol', new JsonExpression(new DynamicModel(['a' => 1, 'b' => 2]))], '[[jsoncol]] = :qp0', [':qp0' => '{"a":1,"b":2}']],
115
            'query' => [['=', 'jsoncol', new JsonExpression((new Query($db))->select('params')->from('user')->where(['id' => 1]))], '[[jsoncol]] = (SELECT [[params]] FROM [[user]] WHERE [[id]]=:qp0)', [':qp0' => 1]],
116
            '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]],
117
118
            'array of json expressions' => [
119
                ['=', 'colname', new ArrayExpression([new JsonExpression(['a' => null, 'b' => 123, 'c' => [4, 5]]), new JsonExpression([true])])],
120
                '"colname" = ARRAY[:qp0, :qp1]',
121
                [':qp0' => '{"a":null,"b":123,"c":[4,5]}', ':qp1' => '[true]']
122
            ],
123
            'Items in ArrayExpression of type json should be casted to Json' => [
124
                ['=', 'colname', new ArrayExpression([['a' => null, 'b' => 123, 'c' => [4, 5]], [true]], 'json')],
125
                '"colname" = ARRAY[:qp0, :qp1]::json[]',
126
                [':qp0' => '{"a":null,"b":123,"c":[4,5]}', ':qp1' => '[true]']
127
            ],
128
            'Two dimension array of text' => [
129
                ['=', 'colname', new ArrayExpression([['text1', 'text2'], ['text3', 'text4'], [null, 'text5']], 'text', 2)],
130
                '"colname" = ARRAY[ARRAY[:qp0, :qp1]::text[], ARRAY[:qp2, :qp3]::text[], ARRAY[:qp4, :qp5]::text[]]::text[][]',
131
                [':qp0' => 'text1', ':qp1' => 'text2', ':qp2' => 'text3', ':qp3' => 'text4', ':qp4' => null, ':qp5' => 'text5'],
132
            ],
133
            'Three dimension array of booleans' => [
134
                ['=', 'colname', new ArrayExpression([[[true], [false, null]], [[false], [true], [false]], [['t', 'f']]], 'bool', 3)],
135
                '"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[][][]',
136
                [':qp0' => true, ':qp1' => false, ':qp2' => null, ':qp3' => false, ':qp4' => true, ':qp5' => false, ':qp6' => 't', ':qp7' => 'f'],
137
            ],
138
139
            // Checks to verity that operators work correctly
140
            [['@>', 'id', new ArrayExpression([1])], '"id" @> ARRAY[:qp0]', [':qp0' => 1]],
141
            [['<@', 'id', new ArrayExpression([1])], '"id" <@ ARRAY[:qp0]', [':qp0' => 1]],
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
        ]);
150
    }
151
152
    public function testAlterColumn(): void
153
    {
154
        $qb = $this->getQueryBuilder();
155
156
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" DROP NOT NULL';
157
        $sql = $qb->alterColumn('foo1', 'bar', 'varchar(255)');
158
        $this->assertEquals($expected, $sql);
159
160
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" SET NOT null';
161
        $sql = $qb->alterColumn('foo1', 'bar', 'SET NOT null');
162
        $this->assertEquals($expected, $sql);
163
164
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" drop default';
165
        $sql = $qb->alterColumn('foo1', 'bar', 'drop default');
166
        $this->assertEquals($expected, $sql);
167
168
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" reset xyz';
169
        $sql = $qb->alterColumn('foo1', 'bar', 'reset xyz');
170
        $this->assertEquals($expected, $sql);
171
172
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" DROP NOT NULL';
173
174
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255));
175
        $this->assertEquals($expected, $sql);
176
177
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" SET NOT NULL';
178
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255)->notNull());
179
        $this->assertEquals($expected, $sql);
180
181
        $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)';
182
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255)->check('char_length(bar) > 5'));
183
        $this->assertEquals($expected, $sql);
184
185
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" SET DEFAULT \'\', ALTER COLUMN "bar" DROP NOT NULL';
186
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255)->defaultValue(''));
187
        $this->assertEquals($expected, $sql);
188
189
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(255), ALTER COLUMN "bar" SET DEFAULT \'AbCdE\', ALTER COLUMN "bar" DROP NOT NULL';
190
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(255)->defaultValue('AbCdE'));
191
        $this->assertEquals($expected, $sql);
192
193
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE timestamp(0), ALTER COLUMN "bar" SET DEFAULT CURRENT_TIMESTAMP, ALTER COLUMN "bar" DROP NOT NULL';
194
        $sql = $qb->alterColumn('foo1', 'bar', $this->timestamp()->defaultExpression('CURRENT_TIMESTAMP'));
195
        $this->assertEquals($expected, $sql);
196
197
        $expected = 'ALTER TABLE "foo1" ALTER COLUMN "bar" TYPE varchar(30), ALTER COLUMN "bar" DROP DEFAULT, ALTER COLUMN "bar" DROP NOT NULL, ADD UNIQUE ("bar")';
198
        $sql = $qb->alterColumn('foo1', 'bar', $this->string(30)->unique());
199
        $this->assertEquals($expected, $sql);
200
    }
201
202
    public function indexesProvider(): array
203
    {
204
        $result = parent::indexesProvider();
205
        $result['drop'][0] = 'DROP INDEX [[CN_constraints_2_single]]';
206
207
        return $result;
208
    }
209
210
    public function defaultValuesProvider(): void
211
    {
212
        $this->markTestSkipped('Adding/dropping default constraints is not supported in PostgreSQL.');
213
    }
214
215
    public function testCommentColumn(): void
216
    {
217
        $qb = $this->getQueryBuilder();
218
219
        $expected = "COMMENT ON COLUMN [[comment]].[[text]] IS 'This is my column.'";
220
        $sql = $qb->addCommentOnColumn('comment', 'text', 'This is my column.');
221
        $this->assertEquals($this->replaceQuotes($expected), $sql);
222
223
        $expected = 'COMMENT ON COLUMN [[comment]].[[text]] IS NULL';
224
        $sql = $qb->dropCommentFromColumn('comment', 'text');
225
        $this->assertEquals($this->replaceQuotes($expected), $sql);
226
    }
227
228
    public function testCommentTable(): void
229
    {
230
        $qb = $this->getQueryBuilder();
231
232
        $expected = "COMMENT ON TABLE [[comment]] IS 'This is my table.'";
233
        $sql = $qb->addCommentOnTable('comment', 'This is my table.');
234
        $this->assertEquals($this->replaceQuotes($expected), $sql);
235
236
        $expected = 'COMMENT ON TABLE [[comment]] IS NULL';
237
        $sql = $qb->dropCommentFromTable('comment');
238
        $this->assertEquals($this->replaceQuotes($expected), $sql);
239
    }
240
241
    public function batchInsertProvider(): array
242
    {
243
        $data = parent::batchInsertProvider();
244
245
        $data['escape-danger-chars']['expected'] = "INSERT INTO \"customer\" (\"address\") VALUES ('SQL-danger chars are escaped: ''); --')";
246
        $data['bool-false, bool2-null']['expected'] = 'INSERT INTO "type" ("bool_col", "bool_col2") VALUES (FALSE, NULL)';
247
        $data['bool-false, time-now()']['expected'] = 'INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (FALSE, now())';
248
249
        return $data;
250
    }
251
252
    public function testResetSequence(): void
253
    {
254
        $qb = $this->getQueryBuilder();
255
256
        $expected = "SELECT SETVAL('\"item_id_seq\"',(SELECT COALESCE(MAX(\"id\"),0) FROM \"item\")+1,false)";
257
        $sql = $qb->resetSequence('item');
258
        $this->assertEquals($expected, $sql);
259
260
        $expected = "SELECT SETVAL('\"item_id_seq\"',4,false)";
261
        $sql = $qb->resetSequence('item', 4);
262
        $this->assertEquals($expected, $sql);
263
    }
264
265
    public function testResetSequencePostgres12(): void
266
    {
267
        if (version_compare($this->getConnection(false)->getServerVersion(), '12.0', '<')) {
268
            $this->markTestSkipped('PostgreSQL < 12.0 does not support GENERATED AS IDENTITY columns.');
269
        }
270
271
        $config = $this->database;
0 ignored issues
show
Bug introduced by
The property database does not exist on Yiisoft\Db\Pgsql\Tests\QueryBuilderTest. Did you mean databases?
Loading history...
272
        unset($config['fixture']);
273
        $this->prepareDatabase($config, realpath(__DIR__ . '/../../../data') . '/postgres12.sql');
0 ignored issues
show
Bug introduced by
realpath(__DIR__ . '/../...a') . '/postgres12.sql' of type string is incompatible with the type boolean expected by parameter $open of Yiisoft\Db\Tests\Databas...Case::prepareDatabase(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

273
        $this->prepareDatabase($config, /** @scrutinizer ignore-type */ realpath(__DIR__ . '/../../../data') . '/postgres12.sql');
Loading history...
274
275
        $qb = $this->getQueryBuilder(false);
276
277
        $expected = "SELECT SETVAL('\"item_12_id_seq\"',(SELECT COALESCE(MAX(\"id\"),0) FROM \"item_12\")+1,false)";
278
        $sql = $qb->resetSequence('item_12');
279
        $this->assertEquals($expected, $sql);
280
281
        $expected = "SELECT SETVAL('\"item_12_id_seq\"',4,false)";
282
        $sql = $qb->resetSequence('item_12', 4);
283
        $this->assertEquals($expected, $sql);
284
    }
285
286
    public function upsertProvider(): array
287
    {
288
        $concreteData = [
289
            'regular values' => [
290
                3 => [
291
                    '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")))',
292
                    '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"',
293
                ],
294
                4 => [
295
                    [
296
                        ':qp0' => '[email protected]',
297
                        ':qp1' => 'bar {{city}}',
298
                        ':qp2' => 1,
299
                        ':qp3' => null,
300
                    ],
301
                ],
302
            ],
303
            'regular values with update part' => [
304
                3 => [
305
                    '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")))',
306
                    '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',
307
                ],
308
                4 => [
309
                    [
310
                        ':qp0' => '[email protected]',
311
                        ':qp1' => 'bar {{city}}',
312
                        ':qp2' => 1,
313
                        ':qp3' => null,
314
                        ':qp4' => 'foo {{city}}',
315
                        ':qp5' => 2,
316
                    ],
317
                ],
318
            ],
319
            'regular values without update part' => [
320
                3 => [
321
                    '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")))',
322
                    'INSERT INTO "T_upsert" ("email", "address", "status", "profile_id") VALUES (:qp0, :qp1, :qp2, :qp3) ON CONFLICT DO NOTHING',
323
                ],
324
                4 => [
325
                    [
326
                        ':qp0' => '[email protected]',
327
                        ':qp1' => 'bar {{city}}',
328
                        ':qp2' => 1,
329
                        ':qp3' => null,
330
                    ],
331
                ],
332
            ],
333
            'query' => [
334
                3 => [
335
                    '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")))',
336
                    '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"',
337
                ],
338
            ],
339
            'query with update part' => [
340
                3 => [
341
                    '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")))',
342
                    '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',
343
                ],
344
            ],
345
            'query without update part' => [
346
                3 => [
347
                    '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")))',
348
                    'INSERT INTO "T_upsert" ("email", "status") SELECT "email", 2 AS "status" FROM "customer" WHERE "name"=:qp0 LIMIT 1 ON CONFLICT DO NOTHING',
349
                ],
350
            ],
351
            'values and expressions' => [
352
                3 => 'INSERT INTO {{%T_upsert}} ({{%T_upsert}}.[[email]], [[ts]]) VALUES (:qp0, now())',
353
            ],
354
            'values and expressions with update part' => [
355
                3 => 'INSERT INTO {{%T_upsert}} ({{%T_upsert}}.[[email]], [[ts]]) VALUES (:qp0, now())',
356
            ],
357
            'values and expressions without update part' => [
358
                3 => 'INSERT INTO {{%T_upsert}} ({{%T_upsert}}.[[email]], [[ts]]) VALUES (:qp0, now())',
359
            ],
360
            'query, values and expressions with update part' => [
361
                3 => [
362
                    '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")))',
363
                    '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',
364
                ],
365
            ],
366
            'query, values and expressions without update part' => [
367
                3 => [
368
                    '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")))',
369
                    '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',
370
                ],
371
            ],
372
            'no columns to update' => [
373
                3 => [
374
                    '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")))',
375
                    'INSERT INTO "T_upsert_1" ("a") VALUES (:qp0) ON CONFLICT DO NOTHING',
376
                ],
377
            ],
378
        ];
379
        $newData = parent::upsertProvider();
380
        foreach ($concreteData as $testName => $data) {
381
            $newData[$testName] = array_replace($newData[$testName], $data);
382
        }
383
        return $newData;
384
    }
385
386
    public function updateProvider(): array
387
    {
388
        $items = parent::updateProvider();
389
390
        $items[] = [
391
            'profile',
392
            [
393
                'description' => new JsonExpression(['abc' => 'def', 123, null]),
394
            ],
395
            [
396
                'id' => 1,
397
            ],
398
            $this->replaceQuotes('UPDATE [[profile]] SET [[description]]=:qp0 WHERE [[id]]=:qp1'),
399
            [
400
                ':qp0' => '{"abc":"def","0":123,"1":null}',
401
                ':qp1' => 1,
402
            ],
403
        ];
404
405
        return $items;
406
    }
407
408
    public function testDropIndex(): void
409
    {
410
        $qb = $this->getQueryBuilder();
411
412
        $expected = 'DROP INDEX "index"';
413
        $sql = $qb->dropIndex('index', '{{table}}');
414
        $this->assertEquals($expected, $sql);
415
416
        $expected = 'DROP INDEX "schema"."index"';
417
        $sql = $qb->dropIndex('index', '{{schema.table}}');
418
        $this->assertEquals($expected, $sql);
419
420
        $expected = 'DROP INDEX "schema"."index"';
421
        $sql = $qb->dropIndex('schema.index', '{{schema2.table}}');
422
        $this->assertEquals($expected, $sql);
423
424
        $expected = 'DROP INDEX "schema"."index"';
425
        $sql = $qb->dropIndex('index', '{{schema.%table}}');
426
        $this->assertEquals($expected, $sql);
427
428
        $expected = 'DROP INDEX {{%schema.index}}';
429
        $sql = $qb->dropIndex('index', '{{%schema.table}}');
430
        $this->assertEquals($expected, $sql);
431
    }
432
}
433