• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ICanBoogie / ActiveRecord / 11644506357

02 Nov 2024 05:17PM UTC coverage: 86.318%. Remained the same
11644506357

push

github

olvlvl
Tidy Query

9 of 18 new or added lines in 2 files covered. (50.0%)

90 existing lines in 3 files now uncovered.

1369 of 1586 relevant lines covered (86.32%)

24.43 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

64.97
/lib/ActiveRecord/Table.php
1
<?php
2

3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
namespace ICanBoogie\ActiveRecord;
13

14
use ICanBoogie\ActiveRecord\Config\TableDefinition;
15
use LogicException;
16
use RuntimeException;
17
use Throwable;
18

19
use function array_combine;
20
use function array_diff_key;
21
use function array_fill;
22
use function array_flip;
23
use function array_keys;
24
use function array_merge;
25
use function array_values;
26
use function count;
27
use function implode;
28
use function is_array;
29
use function is_numeric;
30
use function is_string;
31
use function strtr;
32

33
/**
34
 * A representation of a database table.
35
 */
36
readonly class Table
37
{
38
    /**
39
     * Name of the table, without the prefix defined by the connection.
40
     *
41
     * @var non-empty-string
42
     */
43
    public string $unprefixed_name;
44

45
    /**
46
     * Name of the table, including the prefix defined by the connection.
47
     *
48
     * @var non-empty-string
49
     */
50
    public string $name;
51

52
    /**
53
     * Alias for the table's name, which can be defined using the {@link ALIAS} attribute
54
     * or automatically created.
55
     *
56
     * This is the value for the "{primary}" placeholder.
57
     *
58
     * @var non-empty-string
59
     */
60
    public string $alias;
61
    public Schema $schema;
62

63
    /**
64
     * Primary key of the table, retrieved from the schema defined using the {@link SCHEMA} attribute.
65
     *
66
     * @var non-empty-string|non-empty-array<non-empty-string>|null
67
     */
68
    public array|string|null $primary;
69

70
    /**
71
     * SQL fragment for the FROM clause of the query, made of the table's name and alias and those
72
     * of the hierarchy.
73
     */
74
    public string $update_join;
75

76
    public function make_update_join(): string
77
    {
78
        $join = '';
78✔
79
        $parent = $this->parent;
78✔
80

81
        while ($parent) {
78✔
82
            assert(is_string($this->primary));
83

84
            $join .= " INNER JOIN `$parent->name` `$parent->alias` USING(`$this->primary`)";
55✔
85
            $parent = $parent->parent;
55✔
86
        }
87

88
        return $join;
78✔
89
    }
90

91
    /**
92
     * SQL fragment for the FROM clause of the query, made of the table's name and alias and those
93
     * of the related tables, inherited and implemented.
94
     *
95
     * This is the value for the `{self_and_related}` placeholder.
96
     */
97
    public string $select_join;
98

99
    private function make_select_join(): string
100
    {
101
        return "`$this->alias`" . $this->update_join;
78✔
102
    }
103

104
    public Schema $extended_schema;
105

106
    /**
107
     * Returns the extended schema.
108
     */
109
    private function make_extended_schema(): Schema
110
    {
111
        $table = $this;
55✔
112
        $columns = [];
55✔
113

114
        while ($table) {
55✔
115
            $columns[] = $table->schema->columns;
55✔
116

117
            $table = $table->parent;
55✔
118
        }
119

120
        $columns = array_reverse($columns);
55✔
121
        $columns = array_merge(...array_values($columns));
55✔
122

123
        return new Schema($columns, primary: $this->primary);
55✔
124
    }
125

126
    public function __construct(
127
        public Connection $connection,
128
        TableDefinition $definition,
129
        public ?self $parent = null,
130
    ) {
131
        $this->unprefixed_name = $definition->name;
78✔
132
        $this->name = $connection->table_name_prefix . $this->unprefixed_name;
78✔
133
        $this->alias = $definition->alias;
78✔
134
        $this->schema = $definition->schema;
78✔
135
        $this->primary = $this->schema->primary;
78✔
136
        $this->extended_schema = $this->parent
78✔
137
            ? $this->make_extended_schema()
55✔
138
            : $this->schema;
78✔
139
        $this->update_join = $this->make_update_join();
78✔
140
        $this->select_join = $this->make_select_join();
78✔
141
    }
142

143
    /**
144
     * Interface to the connection's query() method.
145
     *
146
     * The statement is resolved using the resolve_statement() method and prepared.
147
     *
148
     * @param non-empty-string $query
149
     * @param mixed[] $args
150
     */
151
    public function __invoke(string $query, array $args = []): Statement
152
    {
UNCOV
153
        $statement = $this->prepare($query);
×
154

UNCOV
155
        return $statement($args);
×
156
    }
157

158
    /*
159
    **
160

161
    INSTALL
162

163
    **
164
    */
165

166
    /**
167
     * Creates table.
168
     *
169
     * @throws Throwable if install fails.
170
     */
171
    public function install(): void
172
    {
173
        $this->connection->create_table($this->unprefixed_name, $this->schema);
66✔
174
    }
175

176
    /**
177
     * Drops table.
178
     *
179
     * @throws Throwable if uninstall fails.
180
     */
181
    public function uninstall(): void
182
    {
183
        $this->drop();
1✔
184
    }
185

186
    /**
187
     * Checks whether the table is installed.
188
     */
189
    public function is_installed(): bool
190
    {
191
        return $this->connection->table_exists($this->unprefixed_name);
36✔
192
    }
193

194
    /**
195
     * Resolves statement placeholders.
196
     *
197
     * The following placeholders are replaced:
198
     *
199
     * - `{alias}`: The alias of the table.
200
     * - `{prefix}`: The prefix used for the tables of the connection.
201
     * - `{primary}`: The primary key of the table.
202
     * - `{self}`: The name of the table.
203
     * - `{self_and_related}`: The escaped name of the table and the possible JOIN clauses.
204
     *
205
     * Note: If the table has a multi-column primary keys `{primary}` is replaced by
206
     * `__multi-column_primary__<concatenated_columns>` where `<concatenated_columns>` is the columns
207
     * concatenated with an underscore ("_") as separator. For instance, if a table primary key is
208
     * made of columns "p1" and "p2", `{primary}` is replaced by `__multi-column_primary__p1_p2`.
209
     * It's not very helpful, but we still have to decide what to do with this.
210
     *
211
     * @param string $statement The statement to resolve.
212
     */
213
    public function resolve_statement(string $statement): string
214
    {
215
        $primary = $this->primary;
45✔
216
        $primary = is_array($primary) ? '__multicolumn_primary__' . implode('_', $primary) : $primary;
45✔
217

218
        return strtr($statement, [
45✔
219

220
            '{alias}' => $this->alias,
45✔
221
            '{prefix}' => $this->connection->table_name_prefix,
45✔
222
            '{primary}' => $primary,
45✔
223
            '{self}' => $this->name,
45✔
224
            '{self_and_related}' => "`$this->name`" . ($this->select_join ? " $this->select_join" : '')
45✔
225

226
        ]);
45✔
227
    }
228

229
    /**
230
     * Interface to the connection's prepare method.
231
     *
232
     * The statement is resolved by the {@link resolve_statement()} method before the call is
233
     * forwarded.
234
     *
235
     * @param non-empty-string $query
236
     */
237
    public function prepare(string $query): Statement
238
    {
239
        $query = $this->resolve_statement($query);
40✔
240

241
        return $this->connection->prepare($query);
40✔
242
    }
243

244
    /**
245
     * Executes a statement.
246
     *
247
     * The statement is prepared by the {@link prepare()} method before it is executed.
248
     *
249
     * @param non-empty-string $query
250
     * @param array<int|string, mixed> $args
251
     */
252
    public function execute(string $query, array $args = []): Statement
253
    {
254
        $statement = $this->prepare($query);
40✔
255

256
        return $statement($args);
40✔
257
    }
258

259
    /**
260
     * Filters mass assignment values.
261
     *
262
     * @param array<string, mixed> $values
263
     *
264
     * @return array{ array<int|string|null>, array<string, string>, array<string> }
265
     */
266
    private function filter_values(array $values, bool $extended = false): array
267
    {
268
        $filtered = [];
39✔
269
        $holders = [];
39✔
270
        $identifiers = [];
39✔
271
        $schema = $extended ? $this->extended_schema : $this->schema;
39✔
272
        $driver = $this->connection->driver;
39✔
273

274
        foreach ($schema->filter_values($values) as $identifier => $value) {
39✔
275
            $quoted_identifier = $driver->quote_identifier($identifier);
38✔
276

277
            $filtered[] = $driver->cast_value($value);
38✔
278
            $holders[$identifier] = "$quoted_identifier = ?";
38✔
279
            $identifiers[] = $quoted_identifier;
38✔
280
        }
281

282
        return [ $filtered, $holders, $identifiers ];
39✔
283
    }
284

285
    /**
286
     * Saves values.
287
     *
288
     * @param array<string, mixed> $values
289
     * @param array<string, mixed> $options
290
     *
291
     * @throws Throwable
292
     */
293
    public function save(array $values, int $id = null, array $options = []): int|false
294
    {
295
        // TODO: If we have a parent, we should do the changes in a transaction.
296

297
        if ($id) {
34✔
298
            $this->update($values, $id);
1✔
299

300
            return $id;
1✔
301
        }
302

303
        return $this->save_callback($values, $id, $options);
34✔
304
    }
305

306
    /**
307
     * @param array<string, mixed> $values
308
     * @param array<string, mixed> $options
309
     */
310
    private function save_callback(array $values, int $id = null, array $options = []): int
311
    {
312
        assert(count($values) > 0);
313

314
        if ($id) {
34✔
UNCOV
315
            $this->update($values, $id);
×
316

UNCOV
317
            return $id;
×
318
        }
319

320
        $parent_id = 0;
34✔
321

322
        if ($this->parent) {
34✔
323
            $parent_id = $this->parent->save_callback($values, null, $options)
30✔
NEW
324
                ?: throw new RuntimeException("Parent save failed: {$this->parent->name} returning $parent_id.");
×
325

326
            assert(is_string($this->primary));
327
            assert(is_numeric($parent_id));
328

329
            $values[$this->primary] = $parent_id;
30✔
330
        }
331

332
        $driver_name = $this->connection->driver_name;
34✔
333

334
        [ $filtered, $holders, $identifiers ] = $this->filter_values($values);
34✔
335

336
        // FIXME: ALL THIS NEED REWRITE !
337

338
        if ($holders) {
34✔
339
            // If we have a parent, its primary key values must be used.
340

341
            if ($driver_name === 'mysql') {
34✔
NEW
342
                if ($parent_id && empty($holders[$this->primary])) {
×
NEW
343
                    $filtered[] = $parent_id;
×
NEW
344
                    $holders[] = '`{primary}` = ?';
×
345
                }
346

UNCOV
347
                $statement = 'INSERT INTO `{self}` SET ' . implode(', ', $holders);
×
UNCOV
348
                $statement = $this->prepare($statement);
×
349

350
                $statement->execute($filtered);
×
351
            } elseif ($driver_name === 'sqlite') {
34✔
352
                $this->insert($values);
34✔
353
            } else {
354
                throw new LogicException("Don't know what to do with $driver_name");
×
355
            }
UNCOV
356
        } elseif ($parent_id) {
×
357
            #
358
            # a new entry has been created, but we don't have any other fields then the primary key
359
            #
360

361
            if (empty($identifiers[$this->primary])) {
×
UNCOV
362
                $identifiers[] = '`{primary}`';
×
363
                $filtered[] = $parent_id;
×
364
            }
365

UNCOV
366
            $identifiers = implode(', ', $identifiers);
×
UNCOV
367
            $placeholders = implode(', ', array_fill(0, count($filtered), '?'));
×
368

369
            $statement = "INSERT INTO `{self}` ($identifiers) VALUES ($placeholders)";
×
370
            $statement = $this->prepare($statement);
×
371

UNCOV
372
            $statement->execute($filtered);
×
373
        }/* else {
374
            $rc = true;
375
        }*/
376

377
        if ($parent_id) {
34✔
378
            return $parent_id;
30✔
379
        }
380
//
381
//        if (!$rc) {
382
//            return false;
383
//        }
384

385
        return $this->connection->last_insert_id;
34✔
386
    }
387

388
    /**
389
     * Inserts values into the table.
390
     *
391
     * @param non-empty-array<mixed> $values The values to insert.
392
     * @param bool $ignore Optional value to ignore insert errors.
393
     * @param bool $upsert Optional value to update the row if there's a matching primary key.
394
     */
395
    public function insert(array $values, bool $ignore = false, bool $upsert = false): void
396
    {
397
        [ $values, $holders, $identifiers ] = $this->filter_values($values);
39✔
398

399
        if (!$values) {
39✔
400
            throw new LogicException("No values to insert");
1✔
401
        }
402

403
        $driver_name = $this->connection->driver_name;
38✔
404

405
        if ($driver_name == 'mysql') {
38✔
UNCOV
406
            $query = 'INSERT';
×
407

UNCOV
408
            if ($ignore) {
×
UNCOV
409
                $query .= ' IGNORE ';
×
410
            }
411

UNCOV
412
            $query .= ' INTO `{self}` SET ' . implode(', ', $holders);
×
413

UNCOV
414
            if ($upsert) {
×
415
                #
416
                # We use the same input values, but we take care of
417
                # removing the primary key and its corresponding value
418
                #
419

UNCOV
420
                $update_values = array_combine(array_keys($holders), $values);
×
421
                $update_holders = $holders;
×
422

UNCOV
423
                $primary = $this->primary;
×
424

UNCOV
425
                if (is_array($primary)) {
×
UNCOV
426
                    $flip = array_flip($primary);
×
427

428
                    $update_holders = array_diff_key($update_holders, $flip);
×
UNCOV
429
                    $update_values = array_diff_key($update_values, $flip);
×
430
                } else {
UNCOV
431
                    unset($update_holders[$primary]);
×
432
                    unset($update_values[$primary]);
×
433
                }
434

435
                $update_values = array_values($update_values);
×
436

UNCOV
437
                $query .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update_holders);
×
438

439
                $values = array_merge($values, $update_values);
×
440
            }
441
        } elseif ($driver_name == 'sqlite') {
38✔
442
            $holders = array_fill(0, count($identifiers), '?');
38✔
443

444
            $query = 'INSERT'
38✔
445
                . ($ignore | $upsert ? ' OR' : '')
38✔
446
                . ($ignore ? ' IGNORE' : '')
38✔
447
                . ($upsert ? ' REPLACE' : '')
38✔
448
                . ' INTO `{self}` (' . implode(', ', $identifiers) . ')'
38✔
449
                . ' VALUES (' . implode(', ', $holders) . ')';
38✔
450
        } else {
UNCOV
451
            throw new LogicException("Unsupported drive: $driver_name.");
×
452
        }
453

454
        $this->execute($query, $values);
38✔
455
    }
456

457
    /**
458
     * Update the values of an entry.
459
     *
460
     * Even if the entry is spread over multiple tables, all the tables are updated in a single
461
     * step.
462
     *
463
     * @param array<string, mixed> $values
464
     */
465
    public function update(array $values, int|string $key): void
466
    {
467
        #
468
        # SQLite doesn't support UPDATE with INNER JOIN.
469
        #
470

471
        if ($this->connection->driver_name == 'sqlite') {
1✔
472
            $table = $this;
1✔
473

474
            while ($table) {
1✔
475
                [ $table_values, $holders ] = $table->filter_values($values);
1✔
476

477
                if ($holders) {
1✔
478
                    $query = 'UPDATE `{self}` SET ' . implode(', ', $holders) . ' WHERE `{primary}` = ?';
1✔
479
                    $table_values[] = $key;
1✔
480

481
                    $table->execute($query, $table_values);
1✔
482
                }
483

484
                $table = $table->parent;
1✔
485
            }
486

487
            return;
1✔
488
        }
489

UNCOV
490
        [ $values, $holders ] = $this->filter_values($values, true);
×
491

UNCOV
492
        $query = "UPDATE `{self}` $this->update_join  SET " . implode(', ', $holders) . ' WHERE `{primary}` = ?';
×
UNCOV
493
        $values[] = $key;
×
494

UNCOV
495
        $this->execute($query, $values);
×
496
    }
497

498
    /**
499
     * Deletes a record.
500
     *
501
     * @param int|string|array<int|string> $key
502
     */
503
    public function delete(int|string|array $key): void
504
    {
NEW
505
        $this->parent?->delete($key);
×
506

507
        $where = 'WHERE ';
×
508

UNCOV
509
        if (is_array($this->primary)) {
×
510
            $parts = [];
×
511

UNCOV
512
            foreach ($this->primary as $identifier) {
×
NEW
513
                $parts[] = "`$identifier` = ?";
×
514
            }
515

516
            $where .= implode(' AND ', $parts);
×
517
        } else {
UNCOV
518
            $where .= '`{primary}` = ?';
×
519
        }
520

UNCOV
521
        $statement = $this->prepare('DELETE FROM `{self}` ' . $where);
×
UNCOV
522
        $statement((array)$key);
×
523
    }
524

525
    /**
526
     * Truncates table.
527
     *
528
     * @FIXME-20081223: what about extends ?
529
     */
530
    public function truncate(bool $reset_autoincrement = false): void
531
    {
532
        if ($this->connection->driver_name == 'sqlite') {
1✔
533
            $this->execute("DELETE FROM {self}");
1✔
534
            if ($reset_autoincrement) {
1✔
535
                $this->execute("DELETE FROM sqlite_sequence WHERE name = '{self}'");
1✔
536
            }
537
            $this->execute('vacuum');
1✔
538

539
            return;
1✔
540
        }
541

UNCOV
542
        $this->execute("TRUNCATE TABLE {self}");
×
UNCOV
543
        $this->execute("ALTER TABLE {self} AUTO_INCREMENT = 1");
×
544
    }
545

546
    /**
547
     * Drops table.
548
     *
549
     * @throws StatementNotValid when the table cannot be dropped.
550
     */
551
    public function drop(bool $if_exists = false): void
552
    {
553
        $query = 'DROP TABLE' . ($if_exists ? ' IF EXISTS ' : '') . ' `{self}`';
2✔
554

555
        $this->execute($query);
2✔
556
    }
557
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc