Google App Engine: How to connect to Cloud SQL wit

2019-07-31 02:29发布

问题:

I have a Zend Framework 1.12 application that uses the Zend DB Adapter class to connect with MySql. I need to deploy it soon and am investigating Google App Engine.

My current problem is that I can't connect the application to Google Cloud SQL. This Google page, https://developers.google.com/appengine/docs/php/cloud-sql/, gives an example using PHP and PDO. It uses a DSN as a parameter.

The Zend DB Adapter class does not take a DSN as a parameter, but instead constructs it from the other parameters it receives. I have tried to engineer the Zend DB Adapter params to give the correct DSN, but still not luck. Here's my attempt:

$config = new Zend_Config(
    array(
        'database' => array(
            'adapter' => 'Pdo_Mysql',
            'params'  => array(
                'host'     => 'test-instance',
                'dbname'   => 'my_db_name',
                'username' => 'root',
                'password' => 'rootpassword',
                'charset'  => 'utf8',
                'driver_options'  => [
                    'unix_socket' => '/cloudsql/test-project'
                ]
            )
        )
    )
);

try {
    $this->_db = Zend_Db::factory($config->database);
    $this->_db->getConnection();
} catch (Exception $e){    
    Zend_Registry::get('logger')->debug('Cannot create the connection...');
    Zend_Registry::get('logger')->debug(print_r($e, true));
}

The exception in the message is

The mysql driver is not currently installed

Any ideas?

At this stage I am just trying it from the GAE SDK on my desktop. I have not uploaded the application to the cloud. I doubt this is the issue though. (My workstation IP is authorised to use the Cloud Sql instance).

回答1:

I have not used the Zend Framework with AppEngine myself, but in my experience (not that I have found it documented anywhere), if you are connecting to Cloud SQL from an AppEngine app using the "root" user, you should not provide the password, or it fails to connect.

Also as shown in the documentation (here: https://developers.google.com/appengine/docs/php/cloud-sql/#PHP_Connecting_to_your_Cloud_SQL_instance), the unix_socket option should be in the format /cloudsql/project-name:instance-name

Therefore I would try rewriting your $config as follows:

$config = new Zend_Config(
    array(
        'database' => array(
            'adapter' => 'Pdo_Mysql',
            'params'  => array(
                'host'     => '',
                'dbname'   => 'my_db_name',
                'username' => 'root',
                'password' => '',
                'charset'  => 'utf8',
                'driver_options'  => [
                    'unix_socket' => '/cloudsql/test-project:test-instance'
                ]
            )
        )
    )
);