dracoblue.net

Unix socket in Doctrine DSN

When using the cloud sql proxy especially with cloud run for cloudsql mysql instance connections, these are available as unix sockets like this:

/cloudsql/PROJECT_NAME:REGION_NAME:INSTANCE_NAME

The gcloud documentation says with php pdo (without doctrine) the connection shall be made like this:

$dsn = sprintf(
    'mysql:dbname=%s;unix_socket=%s/%s',
    $dbName,
    $socketDir,
    $connectionName
);

// Connect to the database.
$conn = new PDO($dsn, $username, $password, $conn_config);

But if you set DATABASE_URL for:

doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'

like this, you will receive:

An exception occurred in the driver: SQLSTATE[HY000] [2002] No such file or directory  

After some time debugging, reading multiple documentation pages and the source code of Mysql/Driver.php the native "unix_socket" seems to not be directly supported in doctrine urls.

I ended up changing it to the format of:

mysql://localhost?unix_socket=/cloudsql/PROJECT_NAME:REGION_NAME:INSTANCE_NAME&dbname=production&user=root&password=sosecret

When beeing used with cloud run and a connected it is very important to store a DATABASE_URL in the secret manager in case it contains confidential information.

In cloudsql, doctrine, gcloud, mysql, php by
@ 11 Sep 2022, Comments at Reddit & Hackernews

Give something back

Were my blog posts useful to you? If you want to give back, support one of these charities, too!

Report hate in social media Campact e.V. With our technology and your help, we protect the oceans from plastic waste. Gesellschaft fur Freiheitsrechte e. V. The civil eye in the mediterranean

Recent Dev-Articles

Read recently

Recent Files

About