Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.82% covered (success)
98.82%
84 / 85
96.67% covered (success)
96.67%
29 / 30
CRAP
0.00% covered (danger)
0.00%
0 / 1
AbstractAdapter
98.82% covered (success)
98.82%
84 / 85
96.67% covered (success)
96.67%
29 / 30
59
0.00% covered (danger)
0.00%
0 / 1
 __construct
n/a
0 / 0
n/a
0 / 0
0
 connect
n/a
0 / 0
n/a
0 / 0
0
 setOptions
n/a
0 / 0
n/a
0 / 0
0
 getOptions
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 hasOptions
n/a
0 / 0
n/a
0 / 0
0
 beginTransaction
n/a
0 / 0
n/a
0 / 0
0
 commit
n/a
0 / 0
n/a
0 / 0
0
 rollback
n/a
0 / 0
n/a
0 / 0
0
 getTransactionManager
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isTransaction
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getTransactionDepth
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 transaction
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 isSuccess
n/a
0 / 0
n/a
0 / 0
0
 select
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 insert
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 update
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 delete
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 executeSql
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 query
n/a
0 / 0
n/a
0 / 0
0
 prepare
n/a
0 / 0
n/a
0 / 0
0
 bindParams
n/a
0 / 0
n/a
0 / 0
0
 execute
n/a
0 / 0
n/a
0 / 0
0
 fetch
n/a
0 / 0
n/a
0 / 0
0
 fetchAll
n/a
0 / 0
n/a
0 / 0
0
 createSql
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createSchema
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isConnected
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getConnection
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 hasStatement
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getStatement
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 hasResult
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getResult
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 listen
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
7.01
 getListener
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setProfiler
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getProfiler
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 clearProfiler
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 hasError
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setError
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getError
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 throwError
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 clearError
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 disconnect
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 escape
n/a
0 / 0
n/a
0 / 0
0
 getLastId
n/a
0 / 0
n/a
0 / 0
0
 getNumberOfRows
n/a
0 / 0
n/a
0 / 0
0
 getNumberOfAffectedRows
n/a
0 / 0
n/a
0 / 0
0
 getVersion
n/a
0 / 0
n/a
0 / 0
0
 getTables
n/a
0 / 0
n/a
0 / 0
0
 hasTable
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2declare(strict_types=1);
3/**
4 * Pop PHP Framework (https://www.popphp.org/)
5 *
6 * @link       https://github.com/popphp/popphp-framework
7 * @author     Nick Sagona, III <nick@popphp.org>
8 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
9 * @license    https://www.popphp.org/license     New BSD License
10 */
11
12/**
13 * @namespace
14 */
15namespace Pop\Db\Adapter;
16
17use Pop\Db\Sql;
18use Pop\Db\Adapter\Transaction;
19use Pop\Utils\CallableObject;
20
21/**
22 * Db abstract adapter class
23 *
24 * @category   Pop
25 * @package    Pop\Db
26 * @author     Nick Sagona, III <nick@popphp.org>
27 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
28 * @license    https://www.popphp.org/license     New BSD License
29 * @version    7.0.0
30 */
31abstract class AbstractAdapter implements AdapterInterface
32{
33
34    /**
35     * Database connection options
36     * @var array
37     */
38    protected array $options = [];
39
40    /**
41     * Database connection object/resource
42     * @var mixed
43     */
44    protected mixed $connection = null;
45
46    /**
47     * Statement object/resource
48     * @var mixed
49     */
50    protected mixed $statement = null;
51
52    /**
53     * Result object/resource
54     * @var mixed
55     */
56    protected mixed $result = null;
57
58    /**
59     * Error string/object/resource
60     * @var mixed
61     */
62    protected mixed $error = null;
63
64    /**
65     * Query listener object/resource
66     * @var mixed
67     */
68    protected mixed $listener = null;
69
70    /**
71     * Query profiler
72     * @var ?Profiler\Profiler
73     */
74    protected ?Profiler\Profiler $profiler = null;
75
76    /**
77     * Transaction manager
78     * @var Transaction\Manager|null
79     */
80    protected ?Transaction\Manager $transactionManager = null;
81
82    /**
83     * Constructor
84     *
85     * Instantiate the database adapter object
86     *
87     * @param  array $options
88     */
89    abstract public function __construct(array $options = []);
90
91    /**
92     * Connect to the database
93     *
94     * @param  array $options
95     * @return AbstractAdapter
96     */
97    abstract public function connect(array $options = []): AbstractAdapter;
98
99    /**
100     * Set database connection options
101     *
102     * @param  array $options
103     * @return AbstractAdapter
104     */
105    abstract public function setOptions(array $options): AbstractAdapter;
106
107    /**
108     * Get database connection options
109     *
110     * @return array
111     */
112    public function getOptions(): array
113    {
114        return $this->options;
115    }
116
117    /**
118     * Has database connection options
119     *
120     * @return bool
121     */
122    abstract public function hasOptions(): bool;
123
124    /**
125     * Begin a transaction
126     *
127     * @return AbstractAdapter
128     */
129    abstract public function beginTransaction(): AbstractAdapter;
130
131    /**
132     * Commit a transaction
133     *
134     * @return AbstractAdapter
135     */
136    abstract public function commit(): AbstractAdapter;
137
138    /**
139     * Rollback a transaction
140     *
141     * @return AbstractAdapter
142     */
143    abstract public function rollback(): AbstractAdapter;
144
145    /**
146     * Return the transaction manager object, initialize on first use
147     *
148     * @return Transaction\Manager
149     */
150    protected function getTransactionManager(): Transaction\Manager
151    {
152        return ($this->transactionManager ??= new Transaction\Manager());
153    }
154
155    /**
156     * Check if adapter is in the middle of an open transaction
157     *
158     * @return bool
159     */
160    public function isTransaction(): bool
161    {
162        return !is_null($this->transactionManager) && $this->transactionManager->isTransaction();
163    }
164
165    /**
166     * Get transaction depth
167     *
168     * @return int
169     */
170    public function getTransactionDepth(): int
171    {
172        return is_null($this->transactionManager) ? 0 : $this->transactionManager->getTransactionDepth();
173    }
174
175    /**
176     * Execute complete transaction with the DB adapter
177     *
178     * @param  mixed $callable
179     * @param  mixed $params
180     * @throws \Exception
181     * @return void
182     */
183    public function transaction(mixed $callable, mixed $params = null): void
184    {
185        if (!($callable instanceof CallableObject)) {
186            $callable = new CallableObject($callable, $params);
187        }
188
189        try {
190            $this->beginTransaction();
191            $callable->call();
192            $this->commit();
193        } catch (\Exception $e) {
194            $this->rollback();
195            throw $e;
196        }
197    }
198
199    /**
200     * Check if transaction is success
201     *
202     * @return bool
203     */
204    abstract public function isSuccess(): bool;
205
206    /**
207     * Directly execute a SELECT SQL query or prepared statement and return the results
208     *
209     * @param  string|Sql $sql
210     * @param  array      $params
211     * @throws Exception
212     * @return array
213     */
214    public function select(string|Sql $sql, array $params = []): array
215    {
216        if ((is_string($sql) && !str_starts_with(strtolower(trim($sql)), 'select')) ||
217            (($sql instanceof Sql) && !($sql->hasSelect()))) {
218            throw new Exception('Error: The SQL statement is not a valid SELECT statement.');
219        }
220
221        $this->executeSql($sql, $params);
222        return $this->fetchAll();
223    }
224
225    /**
226     * Directly execute an INSERT SQL query or prepared statement and return the results
227     *
228     * @param  string|Sql $sql
229     * @param  array      $params
230     * @throws Exception
231     * @return int
232     */
233    public function insert(string|Sql $sql, array $params = []): int
234    {
235        if ((is_string($sql) && !str_starts_with(strtolower(trim($sql)), 'insert')) ||
236            (($sql instanceof Sql) && !($sql->hasInsert()))) {
237            throw new Exception('Error: The SQL statement is not a valid INSERT statement.');
238        }
239
240        $this->executeSql($sql, $params);
241        return $this->getNumberOfAffectedRows();
242    }
243
244    /**
245     * Directly execute an UPDATE SQL query or prepared statement and return the results
246     *
247     * @param  string|Sql $sql
248     * @param  array      $params
249     * @throws Exception
250     * @return int
251     */
252    public function update(string|Sql $sql, array $params = []): int
253    {
254        if ((is_string($sql) && !str_starts_with(strtolower(trim($sql)), 'update')) ||
255            (($sql instanceof Sql) && !($sql->hasUpdate()))) {
256            throw new Exception('Error: The SQL statement is not a valid UPDATE statement.');
257        }
258
259        $this->executeSql($sql, $params);
260        return $this->getNumberOfAffectedRows();
261    }
262
263    /**
264     * Directly execute a DELETE SQL query or prepared statement and return the results
265     *
266     * @param  string|Sql $sql
267     * @param  array      $params
268     * @throws Exception
269     * @return int
270     */
271    public function delete(string|Sql $sql, array $params = []): int
272    {
273        if ((is_string($sql) && !str_starts_with(strtolower(trim($sql)), 'delete')) ||
274            (($sql instanceof Sql) && !($sql->hasDelete()))) {
275            throw new Exception('Error: The SQL statement is not a valid DELETE statement.');
276        }
277
278        $this->executeSql($sql, $params);
279        return $this->getNumberOfAffectedRows();
280    }
281
282    /**
283     * Execute a SQL query or prepared statement with params
284     *
285     * @param  string|Sql $sql
286     * @param  array      $params
287     * @return AbstractAdapter
288     */
289    public function executeSql(string|Sql $sql, array $params = []): AbstractAdapter
290    {
291        if (!empty($params)) {
292            $this->prepare($sql)
293                ->bindParams($params)
294                ->execute();
295        } else {
296            $this->query($sql);
297        }
298
299        return $this;
300    }
301
302    /**
303     * Execute a SQL query directly
304     *
305     * @param  mixed $sql
306     * @return AbstractAdapter
307     */
308    abstract public function query(mixed $sql): AbstractAdapter;
309
310    /**
311     * Prepare a SQL query
312     *
313     * @param  mixed $sql
314     * @return AbstractAdapter
315     */
316    abstract public function prepare(mixed $sql): AbstractAdapter;
317
318    /**
319     * Bind parameters to a prepared SQL query
320     *
321     * @param  array $params
322     * @return AbstractAdapter
323     */
324    abstract public function bindParams(array $params): AbstractAdapter;
325
326    /**
327     * Execute a prepared SQL query
328     *
329     * @return AbstractAdapter
330     */
331    abstract public function execute(): AbstractAdapter;
332
333    /**
334     * Fetch and return a row from the result
335     *
336     * @return mixed
337     */
338    abstract public function fetch(): mixed;
339
340    /**
341     * Fetch and return all rows from the result
342     *
343     * @return array
344     */
345    abstract public function fetchAll(): array;
346
347    /**
348     * Create SQL builder
349     *
350     * @return Sql
351     */
352    public function createSql(): Sql
353    {
354        return new Sql($this);
355    }
356
357    /**
358     * Create Schema builder
359     *
360     * @return Sql\Schema
361     */
362    public function createSchema(): Sql\Schema
363    {
364        return new Sql\Schema($this);
365    }
366
367    /**
368     * Determine whether or not connected
369     *
370     * @return bool
371     */
372    public function isConnected(): bool
373    {
374        return ($this->connection !== null);
375    }
376
377    /**
378     * Get the connection object/resource
379     *
380     * @return mixed
381     */
382    public function getConnection(): mixed
383    {
384        return $this->connection;
385    }
386
387    /**
388     * Determine whether or not a statement resource exists
389     *
390     * @return bool
391     */
392    public function hasStatement(): bool
393    {
394        return ($this->statement !== null);
395    }
396
397    /**
398     * Get the statement object/resource
399     *
400     * @return mixed
401     */
402    public function getStatement(): mixed
403    {
404        return $this->statement;
405    }
406
407    /**
408     * Determine whether or not a result resource exists
409     *
410     * @return bool
411     */
412    public function hasResult(): bool
413    {
414        return ($this->result !== null);
415    }
416
417    /**
418     * Get the result object/resource
419     *
420     * @return mixed
421     */
422    public function getResult(): mixed
423    {
424        return $this->result;
425    }
426
427    /**
428     * Add query listener to the adapter
429     *
430     * @param  mixed             $listener
431     * @param  mixed             $params
432     * @param  Profiler\Profiler $profiler
433     * @return mixed
434     */
435    public function listen(mixed $listener, mixed $params = null, Profiler\Profiler $profiler = new Profiler\Profiler()): mixed
436    {
437        $this->profiler = $profiler;
438
439        if (!($listener instanceof CallableObject)) {
440            $this->listener = new CallableObject($listener, [$this->profiler]);
441            if ($params !== null) {
442                if (is_array($params)) {
443                    $this->listener->addParameters($params);
444                } else {
445                    $this->listener->addParameter($params);
446                }
447            }
448        } else {
449            $this->listener = $listener;
450            if ($params !== null) {
451                if (is_array($params)) {
452                    array_unshift($params, $this->profiler);
453                } else {
454                    $params = [$this->profiler, $params];
455                }
456                $this->listener->addParameters($params);
457            } else {
458                $this->listener->addNamedParameter('profiler', $this->profiler);
459            }
460        }
461
462        $handler = $this->listener->call();
463        if ($this->profiler->hasDebugger()) {
464            $this->profiler->getDebugger()->addHandler($handler);
465        }
466
467        return $handler;
468    }
469
470    /**
471     * Get query listener
472     *
473     * @return mixed
474     */
475    public function getListener(): mixed
476    {
477        return $this->listener;
478    }
479
480    /**
481     * Set query profiler
482     *
483     * @param  Profiler\Profiler $profiler
484     * @return AbstractAdapter
485     */
486    public function setProfiler(Profiler\Profiler $profiler): AbstractAdapter
487    {
488        $this->profiler = $profiler;
489        return $this;
490    }
491
492    /**
493     * Get query profiler
494     *
495     * @return Profiler\Profiler|null
496     */
497    public function getProfiler(): Profiler\Profiler|null
498    {
499        return $this->profiler;
500    }
501
502    /**
503     * Clear query profiler
504     *
505     * @return AbstractAdapter
506     */
507    public function clearProfiler(): AbstractAdapter
508    {
509        $this->profiler = null;
510        return $this;
511    }
512
513    /**
514     * Determine whether or not there is an error
515     *
516     * @return bool
517     */
518    public function hasError(): bool
519    {
520        return ($this->error !== null);
521    }
522
523    /**
524     * Set the error
525     *
526     * @param  string $error
527     * @return AbstractAdapter
528     */
529    public function setError(string $error): AbstractAdapter
530    {
531        $this->error = $error;
532        return $this;
533    }
534
535    /**
536     * Get the error
537     *
538     * @return mixed
539     */
540    public function getError(): mixed
541    {
542        return $this->error;
543    }
544
545    /**
546     * Throw a database error exception
547     *
548     * @param  ?string $error
549     * @throws Exception
550     * @return void
551     */
552    public function throwError(?string $error = null): void
553    {
554        if ($error !== null) {
555            $this->setError($error);
556        }
557        if ($this->error !== null) {
558            throw new Exception($this->error);
559        }
560    }
561
562    /**
563     * Clear the error
564     *
565     * @return AbstractAdapter
566     */
567    public function clearError(): AbstractAdapter
568    {
569        $this->error = null;
570        return $this;
571    }
572
573    /**
574     * Disconnect from the database
575     *
576     * @return void
577     */
578    public function disconnect(): void
579    {
580        $this->connection = null;
581        $this->result     = null;
582        $this->statement  = null;
583        $this->error      = null;
584    }
585
586    /**
587     * Escape the value
588     *
589     * @param  ?string $value
590     * @return string
591     */
592    abstract public function escape(?string $value = null): string;
593
594    /**
595     * Return the last ID of the last query
596     *
597     * @return int
598     */
599    abstract public function getLastId(): int;
600
601    /**
602     * Return the number of rows from the last query
603     *
604     * @return int
605     */
606    abstract public function getNumberOfRows(): int;
607
608    /**
609     * Return the number of affected rows from the last query
610     *
611     * @return int
612     */
613    abstract public function getNumberOfAffectedRows(): int;
614
615    /**
616     * Return the database version
617     *
618     * @return string
619     */
620    abstract public function getVersion(): string;
621
622    /**
623     * Return the tables in the database
624     *
625     * @return array
626     */
627    abstract public function getTables(): array;
628
629    /**
630     * Return if the database has a table
631     *
632     * @param  string  $table
633     * @return bool
634     */
635    public function hasTable(string $table): bool
636    {
637        return (in_array($table, $this->getTables()));
638    }
639
640}