xref: /webtrees/app/DB.php (revision 4c96e13d7daf3e97fb6e9d448a6a4532bbd1b36b)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Illuminate\Database\Capsule\Manager;
23use Illuminate\Database\Query\Builder;
24use PDO;
25use RuntimeException;
26
27/**
28 * Database abstraction
29 */
30class DB extends Manager
31{
32    public static function driverName(): string
33    {
34        return parent::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME);
35    }
36
37    public static function prefix(string $identifier = ''): string
38    {
39        return parent::connection()->getTablePrefix() . $identifier;
40    }
41
42    /**
43     * @internal
44     */
45    public static function caseInsensitiveLikeOperator(): string
46    {
47        if (self::driverName() === 'pgsql') {
48            return 'ILIKE';
49        }
50
51        if (self::driverName() === 'sqlsrv') {
52            return 'COLLATE SQL_UTF8_General_CI_AI LIKE';
53        }
54
55        return 'LIKE';
56    }
57
58    /**
59     * @internal
60     */
61    public static function groupConcat(string $column): string
62    {
63        switch (self::driverName()) {
64            case 'pgsql':
65            case 'sqlsrv':
66                return 'STRING_AGG(' . $column . ", ',')";
67
68            case 'mysql':
69            case 'sqlite':
70            default:
71                return 'GROUP_CONCAT(' . $column . ')';
72        }
73    }
74
75    public static function lastInsertId(): int
76    {
77        $return = parent::connection()->getPdo()->lastInsertId();
78
79        if ($return === false) {
80            throw new RuntimeException('Unable to retrieve last insert ID');
81        }
82
83        // All IDs are integers in our schema.
84        return (int) $return;
85    }
86
87    /**
88     * PHPSTAN can't detect the magic methods in the parent class.
89     */
90    public static function query(): Builder
91    {
92        return parent::connection()->query();
93    }
94}
95