|
35 | 35 |
|
36 | 36 | // Setup the database connection in the container. |
37 | 37 | $container['db'] = function () { |
38 | | - $username = getenv("DB_USER"); |
39 | | - $password = getenv("DB_PASS"); |
40 | | - $schema = getenv("DB_NAME"); |
41 | | - $hostname = getenv("DB_HOSTNAME") ?: "127.0.0.1"; |
42 | | - $cloud_sql_connection_name = getenv("CLOUD_SQL_CONNECTION_NAME"); |
| 38 | + $username = getenv('DB_USER'); |
| 39 | + $password = getenv('DB_PASS'); |
| 40 | + $dbName = getenv('DB_NAME'); |
| 41 | + $hostname = getenv('DB_HOSTNAME') ?: '127.0.0.1'; |
| 42 | + $cloud_sql_connection_name = getenv('CLOUD_SQL_CONNECTION_NAME'); |
43 | 43 |
|
44 | 44 | try { |
45 | 45 | // # [START cloud_sql_mysql_pdo_create] |
46 | 46 | // // $username = 'your_db_user'; |
47 | 47 | // // $password = 'yoursupersecretpassword'; |
48 | | - // // $schema = 'your_db_name'; |
| 48 | + // // $dbName = 'your_db_name'; |
49 | 49 | // // $cloud_sql_connection_name = getenv("CLOUD_SQL_CONNECTION_NAME"); |
| 50 | + // // $hostname = "127.0.0.1"; // Only used in TCP mode. |
50 | 51 |
|
51 | 52 | if ($cloud_sql_connection_name) { |
52 | 53 | // Connect using UNIX sockets |
53 | 54 | $dsn = sprintf( |
54 | 55 | 'mysql:dbname=%s;unix_socket=/cloudsql/%s', |
55 | | - $schema, |
| 56 | + $dbName, |
56 | 57 | $cloud_sql_connection_name |
57 | 58 | ); |
58 | 59 | } else { |
59 | 60 | // Connect using TCP |
60 | | - // $hostname = '127.0.0.1'; |
61 | | - $dsn = sprintf('mysql:dbname=%s;host=%s', $schema, $hostname); |
| 61 | + $dsn = sprintf('mysql:dbname=%s;host=%s', $dbName, $hostname); |
62 | 62 | } |
63 | 63 |
|
64 | 64 | $conn = new PDO($dsn, $username, $password); |
65 | 65 | # [END cloud_sql_mysql_pdo_create] |
| 66 | + } catch (TypeError $e) { |
| 67 | + throw new RuntimeException( |
| 68 | + sprintf( |
| 69 | + 'Invalid or missing configuration! Make sure you have set ' . |
| 70 | + '$username, $password, $dbName, and $hostname (for TCP mode) ' . |
| 71 | + 'or $cloud_sql_connection_name (for UNIX socket mode). ' . |
| 72 | + 'The PHP error was %s', |
| 73 | + $e->getMessage() |
| 74 | + ), |
| 75 | + $e->getCode(), |
| 76 | + $e |
| 77 | + ); |
66 | 78 | } catch (PDOException $e) { |
67 | 79 | throw new RuntimeException( |
68 | | - "Could not connect to the Cloud SQL Database. " . |
69 | | - "Refer to https://cloud.google.com/sql/docs/mysql/connect-admin-proxy " . |
70 | | - "for more assistance. The PDO error was " . $e->getMessage(), |
| 80 | + sprintf( |
| 81 | + 'Could not connect to the Cloud SQL Database. Check that ' . |
| 82 | + 'your username and password are correct, that the Cloud SQL ' . |
| 83 | + 'proxy is running, and that the database exists and is ready ' . |
| 84 | + 'for use. For more assistance, refer to %s. The PDO error was %s', |
| 85 | + 'https://cloud.google.com/sql/docs/mysql/connect-external-app', |
| 86 | + $e->getMessage() |
| 87 | + ), |
71 | 88 | $e->getCode(), |
72 | 89 | $e |
73 | 90 | ); |
|
0 commit comments