ICanBoogie/ActiveRecord v2.2.0
  • Namespace
  • Class

Namespaces

  • ICanBoogie
    • ActiveRecord

Classes

  • ActiveRecordCacheBase
  • BelongsToRelation
  • Connection
  • ConnectionCollection
  • ConnectionOptions
  • DateTimePropertySupport
  • HasManyRelation
  • Helpers
  • Model
  • ModelCollection
  • Query
  • Relation
  • RelationCollection
  • RelationNotDefined
  • RunTimeActiveRecordCache
  • Statement
  • Table

Interfaces

  • ActiveRecordCache
  • Exception

Traits

  • CreatedAtProperty
  • DateTimeProperty
  • UpdatedAtProperty

Exceptions

  • ActiveRecordClassNotValid
  • ConnectionAlreadyEstablished
  • ConnectionNotDefined
  • ConnectionNotEstablished
  • ModelAlreadyInstantiated
  • ModelNotDefined
  • RecordNotFound
  • ScopeNotDefined
  • StatementNotValid
  • UnableToSetFetchMode

Functions

  • extract_charset_and_collate
  • get_model
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 
<?php

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

namespace ICanBoogie\ActiveRecord;

use ICanBoogie\Accessor\AccessorTrait;
use ICanBoogie\ActiveRecord\ConnectionOptions as Options;

/**
 * A connection to a database.
 *
 * @property-read string $charset The character set used to communicate with the database. Defaults to "utf8".
 * @property-read string $collate The collation of the character set. Defaults to "utf8_general_ci".
 * @property-read string $driver_name Name of the PDO driver.
 * @property-read string $id Identifier of the database connection.
 * @property-read string $table_name_prefix The prefix to prepend to every table name.
 */
class Connection extends \PDO
{
    use AccessorTrait;

    /**
     * Connection identifier.
     *
     * @var string
     */
    private $id;

    protected function get_id()
    {
        return $this->id;
    }

    /**
     * Prefix to prepend to every table name.
     *
     * If set to "dev", all table names will be named like "dev_nodes", "dev_contents", etc.
     * This is a convenient way of creating a namespace for tables in a shared database.
     * By default, the prefix is the empty string, that is there is not prefix.
     *
     * @var string
     */
    private $table_name_prefix = Options::DEFAULT_TIMEZONE;

    protected function get_table_name_prefix()
    {
        return $this->table_name_prefix;
    }

    /**
     * Charset for the connection. Also used to specify the charset while creating tables.
     *
     * @var string
     */
    private $charset = Options::DEFAULT_CHARSET;

    protected function get_charset()
    {
        return $this->charset;
    }

    /**
     * Used to specify the collate while creating tables.
     *
     * @var string
     */
    private $collate = Options::DEFAULT_COLLATE;

    protected function get_collate()
    {
        return $this->collate;
    }

    /**
     * Timezone of the connection.
     *
     * @var string
     */
    private $timezone = Options::DEFAULT_TIMEZONE;

    protected function get_timezone()
    {
        return $this->timezone;
    }

    /**
     * Driver name for the connection.
     *
     * @var string
     */
    private $driver_name;

    protected function get_driver_name()
    {
        return $this->driver_name;
    }

    /**
     * The number of database queries and executions, used for statistics purpose.
     *
     * @var int
     */
    public $queries_count = 0;

    /**
     * The number of micro seconds spent per request.
     *
     * @var array[]array
     */
    public $profiling = [];

    /**
     * Establish a connection to a database.
     *
     * Custom options can be specified using the driver-specific connection options. See
     * {@link Options}.
     *
     * @link http://www.php.net/manual/en/pdo.construct.php
     * @link http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
     *
     * @param string $dsn
     * @param string $username
     * @param string $password
     * @param array $options
     */
    public function __construct($dsn, $username = null, $password = null, $options = [])
    {
        $this->driver_name = $this->resolve_driver_name($dsn);
        $this->apply_options($options);
        $this->before_connection($options);

        parent::__construct($dsn, $username, $password, $options);

        $this->after_connection();
    }

    /**
     * Alias to {@link query}.
     *
     * @return Statement
     */
    public function __invoke()
    {
        return call_user_func_array([ $this, 'query' ], func_get_args());
    }

    /**
     * Resolve the driver name from the DSN string.
     *
     * @param string $dsn
     *
     * @return string
     */
    protected function resolve_driver_name($dsn)
    {
        return explode(':', $dsn, 2)[0];
    }

    /**
     * Applies options to the instance.
     *
     * @param array $options
     */
    protected function apply_options(array $options)
    {
        $options = Options::normalize($options);

        $this->id = $options[Options::ID];
        $this->table_name_prefix = $options[Options::TABLE_NAME_PREFIX];

        if ($this->table_name_prefix)
        {
            $this->table_name_prefix .= '_';
        }

        list($this->charset, $this->collate) = extract_charset_and_collate($options[Options::CHARSET_AND_COLLATE]);

        $this->timezone = $options[Options::TIMEZONE];
    }

    /**
     * Called before the connection.
     *
     * May alter the options according to the driver.
     *
     * @param array $options
     */
    protected function before_connection(array &$options)
    {
        if ($this->driver_name != 'mysql')
        {
            return;
        }

        $init_command = 'SET NAMES ' . $this->charset;

        if ($this->timezone)
        {
            $init_command .= ', time_zone = "' . $this->timezone . '"';
        }

        $options += [

            self::MYSQL_ATTR_INIT_COMMAND => $init_command

        ];
    }

    protected function after_connection()
    {
        $this->setAttribute(self::ATTR_ERRMODE, self::ERRMODE_EXCEPTION);
        $this->setAttribute(self::ATTR_STATEMENT_CLASS, [ Statement::class ]);
    }

    /**
     * Overrides the method to resolve the statement before it is prepared, then set its fetch
     * mode and connection.
     *
     * @param string $statement Query statement.
     * @param array $options
     *
     * @return Statement The prepared statement.
     *
     * @throws StatementNotValid if the statement cannot be prepared.
     */
    public function prepare($statement, $options = [])
    {
        $statement = $this->resolve_statement($statement);

        try
        {
            /* @var $statement Statement */
            $statement = parent::prepare($statement, $options);
        }
        catch (\PDOException $e)
        {
            throw new StatementNotValid($statement, 500, $e);
        }

        $statement->connection = $this;

        if (isset($options['mode']))
        {
            $mode = (array) $options['mode'];

            call_user_func_array([ $statement, 'setFetchMode' ], $mode);
        }

        return $statement;
    }

    /**
     * Overrides the method in order to prepare (and resolve) the statement and execute it with
     * the specified arguments and options.
     *
     * @inheritdoc
     *
     * @return Statement
     */
    public function query($statement, array $args = [], array $options = [])
    {
        $statement = $this->prepare($statement, $options);
        $statement->execute($args);

        return $statement;
    }

    /**
     * Executes a statement.
     *
     * The statement is resolved using the {@link resolve_statement()} method before it is
     * executed.
     *
     * The execution of the statement is wrapped in a try/catch block. {@link PDOException} are
     * caught and {@link StatementNotValid} exception are thrown with additional information
     * instead.
     *
     * Using this method increments the `queries_by_connection` stat.
     *
     * @inheritdoc
     *
     * @throws StatementNotValid if the statement cannot be executed.
     */
    public function exec($statement)
    {
        $statement = $this->resolve_statement($statement);

        try
        {
            $this->queries_count++;

            return parent::exec($statement);
        }
        catch (\PDOException $e)
        {
            throw new StatementNotValid($statement, 500, $e);
        }
    }

    /**
     * Places quotes around the identifier.
     *
     * @param string|array $identifier
     *
     * @return string|array
     */
    public function quote_identifier($identifier)
    {
        $quote = $this->driver_name == 'oci' ? '"' : '`';

        if (is_array($identifier))
        {
            return array_map(function($v) use ($quote) {

                return $quote . $v . $quote;

            }, $identifier);
        }

        return $quote . $identifier . $quote;
    }

    /**
     * Replaces placeholders with their value.
     *
     * The following placeholders are supported:
     *
     * - `{prefix}`: replaced by the {@link $table_name_prefix} property.
     * - `{charset}`: replaced by the {@link $charset} property.
     * - `{collate}`: replaced by the {@link $collate} property.
     *
     * @param string $statement
     *
     * @return string The resolved statement.
     */
    public function resolve_statement($statement)
    {
        return strtr($statement, [

            '{prefix}' => $this->table_name_prefix,
            '{charset}' => $this->charset,
            '{collate}' => $this->collate

        ]);
    }

    /**
     * Alias for the `beginTransaction()` method.
     *
     * @see PDO::beginTransaction()
     */
    public function begin()
    {
        return $this->beginTransaction();
    }

    /**
     * Parses a schema to create a schema with low level definitions.
     *
     * For example, a column defined as 'serial' is parsed as :
     *
     * 'type' => 'integer', 'serial' => true, 'size' => 'big', 'unsigned' => true,
     * 'primary' => true
     *
     * @param array $schema
     *
     * @return array
     */
    public function parse_schema(array $schema)
    {
        $driver_name = $this->driver_name;

        $schema['primary'] = [];
        $schema['indexes'] = [];

        foreach ($schema['fields'] as $identifier => &$definition)
        {
            $definition = (array) $definition;

            #
            # translate special indexes to keys
            #

            if (isset($definition[0]))
            {
                $definition['type'] = $definition[0];

                unset($definition[0]);
            }

            if (isset($definition[1]))
            {
                $definition['size'] = $definition[1];

                unset($definition[1]);
            }

            #
            # handle special types
            #

            switch($definition['type'])
            {
                case 'serial':
                {
                    $definition['type'] = 'integer';

                    #
                    # because auto increment only works on "INTEGER AUTO INCREMENT" in SQLite
                    #

                    if ($driver_name != 'sqlite')
                    {
                        $definition += [ 'size' => 'big', 'unsigned' => true ];
                    }

                    $definition += [ 'auto increment' => true, 'primary' => true ];
                }
                break;

                case 'foreign':
                {
                    $definition['type'] = 'integer';

                    if ($driver_name != 'sqlite')
                    {
                        $definition += [ 'size' => 'big', 'unsigned' => true ];
                    }

                    $definition += [ 'indexed' => true ];
                }
                break;

                case 'varchar':
                {
                    $definition += [ 'size' => 255 ];
                }
                break;
            }

            #
            # primary
            #

            if (isset($definition['primary']) && !in_array($identifier, $schema['primary']))
            {
                $schema['primary'][] = $identifier;
            }

            #
            # indexed
            #

            if (!empty($definition['indexed']) && empty($definition['unique']))
            {
                $index = $definition['indexed'];

                if (is_string($index))
                {
                    if (isset($schema['indexes'][$index]) && in_array($identifier, $schema['indexes'][$index]))
                    {
                        # $identifier is already defined in $index
                    }
                    else
                    {
                        $schema['indexes'][$index][] = $identifier;
                    }
                }
                else
                {
                    if (!in_array($identifier, $schema['indexes']))
                    {
                        $schema['indexes'][$identifier] = $identifier;
                    }
                }
            }
        }

        #
        # indexes that are part of the primary key are deleted
        #

        if ($schema['indexes'] && $schema['primary'])
        {
            $schema['indexes'] = array_diff($schema['indexes'], $schema['primary']);
        }

        if (count($schema['primary']) == 1)
        {
            $schema['primary'] = $schema['primary'][0];
        }

        return $schema;
    }

    /**
     * Creates a table of the specified name and schema.
     *
     * @param string $unprefixed_name The unprefixed name of the table.
     * @param array $schema The schema of the table.
     *
     * @return bool
     */
    public function create_table($unprefixed_name, array $schema)
    {
        // FIXME-20091201: I don't think 'UNIQUE' is properly implemented

        $driver_name = $this->driver_name;
        $unique_list = [];

        $schema = $this->parse_schema($schema);

        $parts = [];

        foreach ($schema['fields'] as $identifier => $params)
        {
            $definition = '`' . $identifier . '`';

            $type = $params['type'];
            $size = isset($params['size']) ? $params['size'] : 0;

            switch ($type)
            {
                case 'blob':
                case 'char':
                case 'integer':
                case 'text':
                case 'varchar':
                case 'bit':
                {
                    if ($size)
                    {
                        if (is_string($size))
                        {
                            $definition .= ' ' . strtoupper($size) . ($type == 'integer' ? 'INT' : $type);
                        }
                        else
                        {
                            $definition .= ' ' . $type . '(' . $size . ')';
                        }
                    }
                    else
                    {
                        $definition .= ' ' . $type;
                    }

                    if (($type == 'integer') && !empty($params['unsigned']))
                    {
                        $definition .= ' UNSIGNED';
                    }
                }
                break;

                case 'boolean':
                case 'date':
                case 'datetime':
                case 'time':
                case 'timestamp':
                case 'year':
                {
                    $definition .= ' ' . $type;
                }
                break;

                case 'enum':
                {
                    $enum = [];

                    foreach ((array) $size as $identifier)
                    {
                        $enum[] = '\'' . $identifier . '\'';
                    }

                    $definition .= ' ' . $type . '(' . implode(', ', $enum) . ')';
                }
                break;

                case 'double':
                case 'float':
                {
                    $definition .= ' ' . $type;

                    if ($size)
                    {
                        $definition .= '(' . implode(', ', (array) $size) . ')';
                    }
                }
                break;

                default:
                {
                    throw new \InvalidArgumentException("Unsupported type <q>{$type}</q> for row <q>{$identifier}</q>.");
                }
                break;
            }

            #
            # null
            #

            if (empty($params['null']))
            {
                $definition .= ' NOT NULL';
            }
            else
            {
                $definition .= ' NULL';
            }

            #
            # default
            #

            if (!empty($params['default']))
            {
                $default = $params['default'];

                $definition .= ' DEFAULT ' . ($default{strlen($default) - 1} == ')' || $default == 'CURRENT_TIMESTAMP' ? $default : '"' . $default . '"');
            }

            #
            # serial, unique
            #

            if (!empty($params['auto increment']))
            {
                if ($driver_name == 'mysql')
                {
                    $definition .= ' AUTO_INCREMENT';
                }
                else if ($driver_name == 'sqlite')
                {
//                  $definition .= ' PRIMARY KEY';
//                  unset($schema['primary']);
                }
            }
            else if (!empty($params['unique']))
            {
                $unique_id = $params['unique'];

                if ($unique_id === true)
                {
                    $definition .= ' UNIQUE';
                }
                else
                {
                    $unique_list[$unique_id][] = $identifier;
                }
            }

            $parts[] = $definition;
        }

        #
        # primary key
        #

        if ($schema['primary'])
        {
            $keys = (array) $schema['primary'];

            $parts[] = 'PRIMARY KEY (' . implode(', ', $this->quote_identifier($keys)) . ')';
        }

        #
        # indexes
        #

        if (isset($schema['indexes']) && $driver_name == 'mysql')
        {
            foreach ($schema['indexes'] as $key => $identifiers)
            {
                $definition = 'INDEX ';

                if (!is_numeric($key))
                {
                    $definition .= $this->quote_identifier($key) . ' ';
                }

                $definition .= '(' . implode(',', $this->quote_identifier((array) $identifiers)) . ')';

                $parts[] = $definition;
            }
        }

        $table_name = $this->table_name_prefix . $unprefixed_name;
        $statement = 'CREATE TABLE `' . $table_name . '` (' . implode(', ', $parts) . ')';

        if ($driver_name == 'mysql')
        {
            $statement .= ' CHARACTER SET ' . $this->charset . ' COLLATE ' . $this->collate;
        }

        $rc = ($this->exec($statement) !== false);

        if (!$rc)
        {
            return $rc;
        }

        if (isset($schema['indexes']) && $driver_name == 'sqlite')
        {
            #
            # SQLite: now that the table has been created, we can add indexes
            #

            foreach ($schema['indexes'] as $key => $identifiers)
            {
                $statement = 'CREATE INDEX IF NOT EXISTS `' . $key . '` ON ' . $table_name;

                $identifiers = (array) $identifiers;

                foreach ($identifiers as &$identifier)
                {
                    $identifier = '`' . $identifier . '`';
                }

                $statement .= ' (' . implode(',', $identifiers) . ')';

                $this->exec($statement);
            }
        }

        #
        # UNIQUE indexes
        #

        foreach ($unique_list as $unique_id => $columns)
        {
            $columns = implode(", ", $this->quote_identifier($columns));
            $statement = "ALTER TABLE `$table_name` ADD UNIQUE `$unique_id` ($columns)";

            $this->exec($statement);
        }

        return $rc;
    }

    /**
     * Checks if a specified table exists in the database.
     *
     * @param string $unprefixed_name The unprefixed name of the table.
     *
     * @return bool `true` if the table exists, `false` otherwise.
     */
    public function table_exists($unprefixed_name)
    {
        $name = $this->table_name_prefix . $unprefixed_name;

        if ($this->driver_name == 'sqlite')
        {
            $tables = $this
            ->query('SELECT name FROM sqlite_master WHERE type = "table" AND name = ?', [ $name ])
            ->fetchAll(self::FETCH_COLUMN);

            return !empty($tables);
        }

        $tables = $this->query('SHOW TABLES')->fetchAll(self::FETCH_COLUMN);

        return in_array($name, $tables);
    }

    /**
     * Optimizes the tables of the database.
     */
    public function optimize()
    {
        if ($this->driver_name == 'sqlite')
        {
            $this->exec('VACUUM');
        }
        else if ($this->driver_name == 'mysql')
        {
            $tables = $this->query('SHOW TABLES')->fetchAll(self::FETCH_COLUMN);

            $this->exec('OPTIMIZE TABLE ' . implode(', ', $tables));
        }
    }
}
ICanBoogie/ActiveRecord v2.2.0 API documentation generated by ApiGen