### Install Project Dependencies Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/docs/contributing.md Install all project dependencies by running `npm install` in the cloned repository's root directory. Ensure you have navigated to the correct path first. ```sh cd npm install ``` -------------------------------- ### Connect to PostgreSQL using Cloud SQL Node.js Connector Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Example demonstrating how to establish a connection pool to a PostgreSQL instance using the Cloud SQL Node.js Connector. Ensure you have the 'pg' package installed. ```js import pg from 'pg'; import {Connector} from '@google-cloud/cloud-sql-connector'; const {Pool} = pg; const connector = new Connector(); const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', ipType: 'PUBLIC', }); const pool = new Pool({ ...clientOpts, user: 'my-user', password: 'my-password', database: 'db-name', max: 5, }); const {rows} = await pool.query('SELECT NOW()'); console.table(rows); // prints returned time value from server await pool.end(); connector.close(); ``` -------------------------------- ### Install Cloud SQL Node.js Connector Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Install the library using npm. This is the initial step before using the connector in your Node.js application. ```sh npm install @google-cloud/cloud-sql-connector ``` -------------------------------- ### Use Local Proxy Tunnel with Prisma (PostgreSQL) Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Starts a local proxy tunnel using a Unix domain socket for PostgreSQL and connects with Prisma. This method is suitable for unsupported drivers like Prisma. Ensure '@google-cloud/cloud-sql-connector' and 'prisma' are installed. ```js import {Connector} from '@google-cloud/cloud-sql-connector'; import {PrismaClient} from '@prisma/client'; const connector = new Connector(); await connector.startLocalProxy({ instanceConnectionName: 'my-project:us-east1:my-instance', listenOptions: { path: '.s.PGSQL.5432' }, }); const hostPath = process.cwd(); const datasourceUrl = `postgresql://my-user:password@localhost/dbName?host=${hostPath}`; const prisma = new PrismaClient({ datasourceUrl }); connector.close(); await prisma.$disconnect(); ``` -------------------------------- ### Run Project Tests Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/docs/contributing.md Execute all project tests using the `npm test` command. This requires that all project dependencies have been installed. ```sh npm test ``` -------------------------------- ### Connect to SQL Server with tedious Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Establishes a SQL Server connection using the 'tedious' driver and the Cloud SQL Node.js Connector. Ensure 'tedious' and '@google-cloud/cloud-sql-connector' are installed. Note the 'server' and 'port' properties are due to a tedious driver bug and have no impact. ```js const {Connection, Request} = require('tedious'); const {Connector} = require('@google-cloud/cloud-sql-connector'); const connector = new Connector(); const clientOpts = await connector.getTediousOptions({ instanceConnectionName: process.env.SQLSERVER_CONNECTION_NAME, ipType: 'PUBLIC', }); const connection = new Connection({ // Please note that the `server` property here is not used and is only defined // due to a bug in the tedious driver (ref: https://github.com/tediousjs/tedious/issues/1541) // With that in mind, do not try to change this value since it will have no // impact in how the connector works, this README will be updated to remove // this property declaration as soon as the tedious driver bug is fixed server: '0.0.0.0', authentication: { type: 'default', options: { userName: 'my-user', password: 'my-password', }, }, options: { ...clientOpts, // Please note that the `port` property here is not used and is only defined // due to a bug in the tedious driver (ref: https://github.com/tediousjs/tedious/issues/1541) // With that in mind, do not try to change this value since it will have no // impact in how the connector works, this README will be updated to remove // this property declaration as soon as the tedious driver bug is fixed port: 9999, database: 'my-database', }, }); connection.connect(err => { if (err) { throw err; } let result; const req = new Request('SELECT GETUTCDATE()', err => { if (err) { throw err; } }); req.on('error', err => { throw err; }); req.on('row', columns => { result = columns; }); req.on('requestCompleted', () => { console.table(result); }); connection.execSql(req); }); connection.close(); connector.close(); ``` -------------------------------- ### Connect to MySQL with mysql2 Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Establishes a MySQL connection pool using the 'mysql2' driver and the Cloud SQL Node.js Connector. Ensure 'mysql2' and '@google-cloud/cloud-sql-connector' are installed. ```js import mysql from 'mysql2/promise'; import {Connector} from '@google-cloud/cloud-sql-connector'; const connector = new Connector(); const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', ipType: 'PUBLIC', }); const pool = await mysql.createPool({ ...clientOpts, user: 'my-user', password: 'my-password', database: 'db-name', }); const conn = await pool.getConnection(); const [result] = await conn.query(`SELECT NOW();`); console.table(result); // prints returned time value from server await pool.end(); connector.close(); ``` -------------------------------- ### Get Options for PSC IP Connection in TypeScript Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md This TypeScript example shows how to use the IpAddressTypes enum for obtaining connection options for a Cloud SQL instance via PSC IP. ```js import {Connector, IpAddressTypes} from '@google-cloud/cloud-sql-connector'; const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', ipType: IpAddressTypes.PSC, }); ``` -------------------------------- ### Get Options for IAM Authentication in TypeScript Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md This TypeScript example demonstrates using the AuthTypes enum for automatic IAM database authentication. ```js import {AuthTypes, Connector} from '@google-cloud/cloud-sql-connector'; const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', authType: AuthTypes.IAM, }); ``` -------------------------------- ### Postgres Automatic IAM Authentication Example Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Connect to a Cloud SQL Postgres instance using automatic IAM database authentication. Ensure the instance is configured for IAM authentication and the user is an IAM database user. ```js import pg from 'pg'; import {Connector} from '@google-cloud/cloud-sql-connector'; const {Pool} = pg; const connector = new Connector(); const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', authType: 'IAM', }); const pool = new Pool({ ...clientOpts, user: 'test-sa@test-project.iam', database: 'db-name', max: 5, }); const {rows} = await pool.query('SELECT NOW()'); console.table(rows); // prints returned time value from server await pool.end(); connector.close(); ``` -------------------------------- ### MySQL Automatic IAM Authentication Example Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Connect to a Cloud SQL MySQL instance using automatic IAM database authentication. Ensure the instance is configured for IAM authentication and the user is an IAM database user. ```js import mysql from 'mysql2/promise'; import {Connector} from '@google-cloud/cloud-sql-connector'; const connector = new Connector(); const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', authType: 'IAM', }); const pool = await mysql.createPool({ ...clientOpts, user: 'test-sa', database: 'db-name', }); const conn = await pool.getConnection(); const [result] = await conn.query(`SELECT NOW();`); console.table(result); // prints returned time value from server await pool.end(); connector.close(); ``` -------------------------------- ### Get Options for Private Service Connect (PSC) IP Connection Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Use this snippet to obtain connection options for a Cloud SQL instance using a Private Service Connect (PSC) IP address. ```js const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', ipType: 'PSC', }); ``` -------------------------------- ### Get Options for Automatic IAM Database Authentication Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Configure a Connector to use automatic IAM database authentication by specifying 'IAM' for the authType. ```js const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', authType: 'IAM', }); ``` -------------------------------- ### Build Docker Image for MySQL2 Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/knex/README.md Build a Docker image for your Cloud Run application using the mysql2 driver. Replace placeholders with your specific project details. ```bash docker build -t REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/IMAGE_NAME mysql2 ``` -------------------------------- ### Build Docker Image for Cloud Run Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/prisma/README.md Build a Docker image for your Cloud Run application. Replace 'mysql' with 'postgresql' if you are using a PostgreSQL instance. ```bash docker build -t REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/IMAGE_NAME mysql ``` -------------------------------- ### Deploy to Cloud Run (MySQL/PostgreSQL, Public IP) Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/knex/README.md Use this command to deploy your application to Cloud Run when connecting to MySQL or PostgreSQL instances via public IP. It sets necessary environment variables and retrieves the database password from Secret Manager. ```bash gcloud run deploy SERVICE_NAME \ --image=REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/IMAGE_NAME \ --set-env-vars=DB_USER=DB_USER,DB_IAM_USER=DB_IAM_USER,DB_NAME=DB_NAME,INSTANCE_CONNECTION_NAME=INSTANCE_CONNECTION_NAME \ --region=REGION \ --update-secrets=DB_PASSWORD=DB_PASSWORD:latest ``` -------------------------------- ### Deploy to Cloud Run (SQL Server, Public IP) Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/knex/README.md Deploy your application to Cloud Run for public IP connections to SQL Server instances. This command sets the required environment variables and fetches the database password from Secret Manager. ```bash gcloud run deploy SERVICE_NAME \ --image=REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/IMAGE_NAME \ --set-env-vars=DB_USER=DB_USER,DB_NAME=DB_NAME,INSTANCE_CONNECTION_NAME=INSTANCE_CONNECTION_NAME \ --region=REGION \ --update-secrets=DB_PASSWORD=DB_PASSWORD:latest ``` -------------------------------- ### Run System Tests with Cloud SQL Environment Variables Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/docs/contributing.md Execute the end-to-end system tests by running `npm run system-test`. This requires setting environment variables for your Cloud SQL instance connection details. ```sh POSTGRES_USER=my-user POSTGRES_PASS=my-password POSTGRES_DB=db-name POSTGRES_CONNECTION_NAME=my-project:region:my-instance npm run system-test ``` -------------------------------- ### Enable Artifact Registry API Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/prisma/README.md Enable the Artifact Registry API for your Google Cloud project. This is required before creating a repository. ```bash gcloud services enable artifactregistry.googleapis.com ``` -------------------------------- ### Configure Connector with Google Auth Library Credentials Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Instantiate the Connector with custom credentials from the google-auth-library, useful for non-default credential configurations. ```sh npm install google-auth-library ``` ```js import {GoogleAuth} from 'google-auth-library'; import {Connector} from '@google-cloud/cloud-sql-connector'; const connector = new Connector({ auth: new GoogleAuth({ scopes: ['https://www.googleapis.com/auth/sqlservice.admin'] }), }); ``` -------------------------------- ### Deploy to Cloud Run (MySQL/PostgreSQL, Private IP) Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/knex/README.md This command deploys your application to Cloud Run for private IP connections to MySQL or PostgreSQL instances. It configures VPC network settings and retrieves the database password from Secret Manager. ```bash gcloud run deploy SERVICE_NAME \ --image=REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/IMAGE_NAME \ --set-env-vars=DB_USER=DB_USER,DB_IAM_USER=DB_IAM_USER,DB_NAME=DB_NAME,INSTANCE_CONNECTION_NAME=INSTANCE_CONNECTION_NAME,IP_TYPE=PRIVATE \ --network=VPC_NETWORK \ --subnet=SUBNET_NAME \ --vpc-egress=private-ranges-only \ --region=REGION \ --update-secrets=DB_PASSWORD=DB_PASSWORD:latest ``` -------------------------------- ### Deploy to Cloud Run (SQL Server, Private IP) Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/knex/README.md Use this command to deploy your application to Cloud Run for private IP connections to SQL Server instances. It configures VPC network settings and retrieves the database password from Secret Manager. ```bash gcloud run deploy SERVICE_NAME \ --image=REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/IMAGE_NAME \ --set-env-vars=DB_USER=DB_USER,DB_NAME=DB_NAME,INSTANCE_CONNECTION_NAME=INSTANCE_CONNECTION_NAME,IP_TYPE=PRIVATE \ --network=VPC_NETWORK \ --subnet=SUBNET_NAME \ --vpc-egress=private-ranges-only \ --region=REGION \ --update-secrets=DB_PASSWORD=DB_PASSWORD:latest ``` -------------------------------- ### Create Artifact Registry Docker Repository Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/prisma/README.md Create a Docker repository in Artifact Registry to store your container images. Specify the repository name, format, and location. ```bash gcloud artifacts repositories create REPO_NAME \ --repository-format=docker \ --location=REGION ``` -------------------------------- ### Set Custom Quota Project with GoogleAuth Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Configure the connector to use a custom quota project by providing a custom GoogleAuth instance with client options. ```js import {GoogleAuth} from 'google-auth-library'; import {Connector} from '@google-cloud/cloud-sql-connector'; const connector = new Connector({ auth: new GoogleAuth({ clientOptions: { quotaProjectId: '', }, }), }); ``` -------------------------------- ### Generate Client Certificate Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/test/README.md Generates an X509 certificate for the client using the CA's key and certificate, valid for 365000 days. ```bash $ openssl x509 -sha256 -req -days 365000 -set_serial 01 -in client-req.pem -out client-cert.pem -CA ca-cert.pem -CAkey ca-key.pem ``` -------------------------------- ### Push Docker Image to Artifact Registry Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/prisma/README.md Push the built Docker image to your Artifact Registry repository. This makes the image available for deployment to Cloud Run. ```bash docker push REGION-docker.pkg.dev/PROJECT_ID/REPO_NAME/IMAGE_NAME ``` -------------------------------- ### Generate Server Certificate Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/test/README.md Generates an X509 certificate for the server using the CA's key and certificate, valid for 365000 days. ```bash $ openssl x509 -sha256 -days 365000 -req -set_serial 01 -in server-req.pem -out server-cert.pem -CA ca-cert.pem -CAkey ca-key.pem ``` -------------------------------- ### Copy CA Certificate to Clipboard Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/test/README.md Copies the content of the CA certificate to the system clipboard for easy pasting into the test fixture file. ```bash $ cat ca-cert.pem | pbcopy ``` -------------------------------- ### Configure Docker Authentication for Artifact Registry Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/prisma/README.md Configure the Docker CLI to authenticate with your Artifact Registry. This allows you to push and pull images from the registry. ```bash gcloud auth configure-docker REGION-docker.pkg.dev ``` -------------------------------- ### Generate Client Private Key and Certificate Request Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/test/README.md Generates a 2048-bit RSA private key and a certificate signing request (CSR) for the client. ```bash $ openssl req -sha256 -newkey rsa:2048 -nodes -days 365000 -keyout client-key.pem -out client-req.pem ``` -------------------------------- ### Connect to Cloud SQL Instance Using DNS Name Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Connect to a Cloud SQL instance using a custom DNS name, such as a write endpoint DNS name from Advanced Disaster Recovery. Ensure the DNS name is configured correctly in your DNS records. ```js import mysql from 'mysql2/promise'; import {Connector} from '@google-cloud/cloud-sql-connector'; const connector = new Connector(); const clientOpts = await connector.getOptions({ domainName: 'prod-db.mycompany.example.com', ipType: 'PUBLIC', }); const pool = await mysql.createPool({ ...clientOpts, user: 'my-user', password: 'my-password', database: 'db-name', }); const conn = await pool.getConnection(); const [result] = await conn.query(`SELECT NOW();`); console.table(result); // prints returned time value from server await pool.end(); connector.close(); ``` -------------------------------- ### Generate Server Private Key and Certificate Request Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/test/README.md Generates a 2048-bit RSA private key and a certificate signing request (CSR) for the server. ```bash $ openssl req -sha256 -newkey rsa:2048 -nodes -days 365000 -keyout server-key.pem -out server-req.pem ``` -------------------------------- ### Run Connector Integration Tests Directly Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/docs/contributing.md Execute the connector integration tests directly using Node.js with the `ts-node/esm` loader. This bypasses the standard test runner. ```sh node --loader ts-node/esm test/serial/connector-integration.ts ``` -------------------------------- ### Generate CA Private Key Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/test/README.md Generates a 2048-bit private key for the Certificate Authority (CA). ```bash $ openssl genrsa 2048 > ca-key.pem ``` -------------------------------- ### Generate CA Certificate Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/test/README.md Generates a self-signed X509 certificate for the CA, valid for 365000 days. ```bash $ openssl req -new -x509 -nodes -days 365000 -key ca-key.pem -out ca-cert.pem ``` -------------------------------- ### Add Service Account as Database User Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/knex/README.md Add your Cloud Run service account as a database user to your Cloud SQL instance. This is required for IAM authentication. ```bash gcloud sql users create SERVICE_ACCOUNT_EMAIL \ --instance=INSTANCE_NAME \ --type=cloud_iam_user ``` -------------------------------- ### Connect to Cloud SQL using Private IP Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/README.md Configures the Cloud SQL Node.js Connector to use an instance's private IP address for connections. Ensure your application is attached to the proper VPC network, potentially using a VPC Connector. ```js const clientOpts = await connector.getOptions({ instanceConnectionName: 'my-project:region:my-instance', ipType: 'PRIVATE', }); ``` -------------------------------- ### Grant Cloud SQL Client Role Source: https://github.com/googlecloudplatform/cloud-sql-nodejs-connector/blob/main/examples/cloudrun/knex/README.md Grant the Cloud SQL Client role to your Cloud Run service account. This is a prerequisite for IAM authentication. ```bash gcloud projects add-iam-policy-binding PROJECT_ID \ --member="serviceAccount:SERVICE_ACCOUNT_EMAIL" \ --role="roles/cloudsql.client" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.