【问题标题】:Use PHPUnit/CakePHP Fixtures with Point type使用带有 Point 类型的 PHPUnit/CakePHP Fixtures
【发布时间】:2017-12-02 03:16:05
【问题描述】:

我创建了一个用于预处理 POI 的 API,并将节点的坐标存储在“点”型列 (MySQL) 中。

API 已经完成并且运行没有错误,你可以猜到我已经为 CakePHP 实现了 Point-Type。

但现在的问题是: 我想用 PHPUnit 测试 API,但是 Cake\Database\Schema\Table::createSql-Method 搞砸了 sql。

直到那里 Object 包含点类型,但是此函数创建的 sql 缺少数据类型。

您知道如何解决缺少的类型吗? 或者我如何在夹具中执行原始 sql 查询?

以下是 sn-ps 和数据


“节点”的 Fixture 的 $fields:

public $fields = [
    'id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
    'osm_id' => ['type' => 'biginteger', 'length' => 20, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
    'version' => ['type' => 'biginteger', 'length' => 20, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
    'coordinates' => ['type' => 'point', 'length' => null, 'null' => false, 'default' => null, 'collate' => null, 'comment' => '', 'precision' => null],
    'category' => ['type' => 'string', 'length' => 255, 'null' => false, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null, 'fixed' => null],
    'created' => ['type' => 'timestamp', 'length' => null, 'null' => false, 'default' => 'CURRENT_TIMESTAMP', 'comment' => '', 'precision' => null],
    'modified' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
    '_constraints' => [
        'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
    ],
    '_options' => [
        'engine' => 'InnoDB',
        'collation' => 'utf8_general_ci'
    ],
];

在 vendor/cakephp/cakephp/src/TestSuite/Fixture/TestFixture.php 中调试 $this->_schema /src/TestSuite/Fixture/TestFixture.php(第 294 行)

object(Cake\Database\Schema\Table) {
    [protected] _table => 'nodes'
    [protected] _columns => [
            'id' => [
                    'type' => 'integer',
                    'length' => (int) 11,
                    'unsigned' => false,
                    'null' => false,
                    'default' => null,
                    'comment' => '',
                    'autoIncrement' => true,
                    'precision' => null,
                    'baseType' => null
            ],
            'osm_id' => [
                    'type' => 'biginteger',
                    'length' => (int) 20,
                    'unsigned' => false,
                    'null' => false,
                    'default' => null,
                    'comment' => '',
                    'precision' => null,
                    'autoIncrement' => null,
                    'baseType' => null
            ],
            'version' => [
                    'type' => 'biginteger',
                    'length' => (int) 20,
                    'unsigned' => false,
                    'null' => false,
                    'default' => null,
                    'comment' => '',
                    'precision' => null,
                    'autoIncrement' => null,
                    'baseType' => null
            ],
            'coordinates' => [
                    'type' => 'point',
                    'length' => null,
                    'null' => false,
                    'default' => null,
                    'comment' => '',
                    'precision' => null,
                    'baseType' => null
            ],
            'category' => [
                    'type' => 'string',
                    'length' => (int) 255,
                    'null' => false,
                    'default' => null,
                    'collate' => 'utf8_general_ci',
                    'comment' => '',
                    'precision' => null,
                    'fixed' => null,
                    'baseType' => null
            ],
            'created' => [
                    'type' => 'timestamp',
                    'length' => null,
                    'null' => false,
                    'default' => 'CURRENT_TIMESTAMP',
                    'comment' => '',
                    'precision' => null,
                    'baseType' => null
            ],
            'modified' => [
                    'type' => 'timestamp',
                    'length' => null,
                    'null' => true,
                    'default' => null,
                    'comment' => '',
                    'precision' => null,
                    'baseType' => null
            ]
    ]
    [protected] _typeMap => [
            'id' => 'integer',
            'osm_id' => 'biginteger',
            'version' => 'biginteger',
            'coordinates' => 'point',
            'category' => 'string',
            'created' => 'timestamp',
            'modified' => 'timestamp'
    ]
    [protected] _indexes => []
    [protected] _constraints => [
            'primary' => [
                    'type' => 'primary',
                    'columns' => [
                            (int) 0 => 'id'
                    ],
                    'length' => []
            ]
    ]
    [protected] _options => [
            'engine' => 'InnoDB',
            'collation' => 'utf8_general_ci'
    ]
    [protected] _temporary => false
    [protected] _columnKeys => [
            'type' => null,
            'baseType' => null,
            'length' => null,
            'precision' => null,
            'null' => null,
            'default' => null,
            'comment' => null
    ]
    [protected] _columnExtras => [
            'string' => [
                    'fixed' => null,
                    'collate' => null
            ],
            'text' => [
                    'collate' => null
            ],
            'integer' => [
                    'unsigned' => null,
                    'autoIncrement' => null
            ],
            'biginteger' => [
                    'unsigned' => null,
                    'autoIncrement' => null
            ],
            'decimal' => [
                    'unsigned' => null
            ],
            'float' => [
                    'unsigned' => null
            ]
    ]
    [protected] _indexKeys => [
            'type' => null,
            'columns' => [],
            'length' => [],
            'references' => [],
            'update' => 'restrict',
            'delete' => 'restrict'
    ]
    [protected] _validIndexTypes => [
            (int) 0 => 'index',
            (int) 1 => 'fulltext'
    ]
    [protected] _validConstraintTypes => [
            (int) 0 => 'primary',
            (int) 1 => 'unique',
            (int) 2 => 'foreign'
    ]
    [protected] _validForeignKeyActions => [
            (int) 0 => 'cascade',
            (int) 1 => 'setNull',
            (int) 2 => 'setDefault',
            (int) 3 => 'noAction',
            (int) 4 => 'restrict'
    ]
}

以及由上述shemas createSql-method 生成的错误sql-query:

object(Cake\Database\Statement\MysqlStatement) {
        [protected] _statement => object(PDOStatement) {
                queryString => 'CREATE TABLE `nodes` (
`id` INTEGER(11) NOT NULL AUTO_INCREMENT,
`osm_id` BIGINT NOT NULL,
`version` BIGINT NOT NULL,
`coordinates` NOT NULL,
`category` VARCHAR(255) COLLATE utf8_general_ci NOT NULL,
`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified` TIMESTAMP NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB'
        }
        [protected] _driver => object(Cake\Database\Driver\Mysql) {

                'connected' => true

        }
        [protected] _hasExecuted => false
        [protected] _bufferResults => true
}

如您所见,“坐标”缺少数据类型。


版本:

PHP:

PHP 5.6.30-12~ubuntu16.04.1+deb.sury.org+1

蛋糕:3.3.16

PHPUnit:4.8.36

【问题讨论】:

    标签: php mysql cakephp phpunit


    【解决方案1】:

    表创建 SQL 支持的类型在各自的架构类中硬编码。可能还有改进的余地,首先要为不受支持的类型抛出异常。

    通过架构类自定义列创建 SQL

    一种简洁的方法可能是创建扩展架构类并覆盖\Cake\Database\Schema\BaseSchema::columnSql() 方法并为point 类型相应地创建适当的SQL。

    这还需要使用扩展驱动程序类来覆盖创建相应架构类实例的schemaDialect() 方法。

    这里有一个简单的例子来说明这个原理:

    // src/Database/Driver/Mysql.php
    namespace App\Database\Driver;
    
    use App\Database\Schema\MysqlSchema;
    use Cake\Database\Driver\Mysql as BaseMysql;
    
    class Mysql extends BaseMysql
    {
        public function schemaDialect()
        {
            if (!$this->_schemaDialect) {
                $this->_schemaDialect = new MysqlSchema($this);
            }
    
            return $this->_schemaDialect;
        }
    }
    
    // src/Database/Schema/MysqlSchema.php
    namespace App\Database\Schema;
    
    use Cake\Database\Schema\MysqlSchema as BaseMysqlSchema;
    use Cake\Database\Schema\TableSchema; // as of CakePHP 3.4
    // use Cake\Database\Schema\Table as TableSchema; // before CakePHP 3.4
    
    class MysqlSchema extends BaseMysqlSchema
    {
        public function columnSql(TableSchema $schema, $name)
        {
            $data = $schema->column($name);
            if ($data['type'] === 'point') {
                $out = $this->_driver->quoteIdentifier($name);
    
                $out .= ' POINT';
    
                if (isset($data['null']) && $data['null'] === false) {
                    $out .= ' NOT NULL';
                }
    
                if (isset($data['comment']) && $data['comment'] !== '') {
                    $out .= ' COMMENT ' . $this->_driver->schemaValue($data['comment']);
                }
    
                return $out;
            }
    
            return parent::columnSql($schema, $name);
        }
    }
    

    然后在您的config/app.php 中相应地配置数据源driver 选项:

    'driver' => \App\Database\Driver\Mysql::class,
    

    通过夹具类自定义表创建 SQL

    更简单但也不那么 DRY 的方法是覆盖 TestFixture::create() 类中的 TestFixture::create() 方法,并在其中执行完全自定义的表创建 SQL。

    public function create(ConnectionInterface $db)
    {
        try {
            $query = 'CREATE TABLE ...';
    
            $stmt = $db->prepare($query);
            $stmt->execute();
            $stmt->closeCursor();
        } catch (Exception $e) {
            $msg = sprintf(
                'Fixture creation for "%s" failed "%s"',
                $this->table,
                $e->getMessage()
            );
            Log::error($msg);
            trigger_error($msg, E_USER_WARNING);
    
            return false;
        }
    
        return true;
    }
    

    如果您需要支持不同的方言,您可以查看$db->driver() 并相应地创建相应的 SQL。

    【讨论】:

    • 谢谢,第一种方法完美。 (但我必须在 MySql-Schema 中使用 Cake\Database\Schema\Table 而不是 Cake\Database\Schema\TableSchema)
    • 我忘记了 TableSchema 仅在 CakePHP 3.4 中可用,我已经更新了示例。 @DennisRichter
    • 对于那些使用url 定义数据库的人:当您定义driver 时不要忘记同时定义className 否则新的driver 类也用于连接。正确:driver=App\Database\Driver\Mysql&className=Cake\Database\Connection
    • 扩展驱动似乎仍然是 CakePHP 3.8 的一个很好的解决方案。请注意,POINT (book.cakephp.org/3/en/orm/…) 的食谱示例它们依赖于 toExpression() 方法,但测试 Fixture 仅依赖于 toDatabase(),因此需要一些工作。
    猜你喜欢
    • 2018-07-16
    • 2014-02-07
    • 2012-01-19
    • 2015-04-02
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多