When using multiple databases, each must have a unique env_var_key to avoid conflicts:
Multiple databases with unique env vars
Copy
databases: users: subtype: # your choice, from target platform access: api: [query] env_var_key: USERS_DATABASE_URL products: subtype: # your choice, from target platform access: api: [query] env_var_key: PRODUCTS_DATABASE_URL orders: subtype: # your choice, from target platform access: api: [query] env_var_key: ORDERS_DATABASE_URL
Now the api service receives three separate connection strings:
USERS_DATABASE_URL
PRODUCTS_DATABASE_URL
ORDERS_DATABASE_URL
Each database must have a unique env_var_key if the same service accesses multiple databases. Using the same key for different databases will cause conflicts.
Access databases using standard PostgreSQL libraries with the automatically injected connection string:
Node.js
Python
Go
Install the PostgreSQL client:
Copy
npm install pg
Then develop like you normally would, using the env_var_key you defined in your suga.yaml.
Copy
import { Pool } from 'pg';// Connection string automatically injected by Sugaconst pool = new Pool({ connectionString: process.env.DATABASE_URL});// Query databaseconst result = await pool.query( 'SELECT * FROM users WHERE active = $1', [true]);const users = result.rows;// Insert dataawait pool.query( 'INSERT INTO users (name, email) VALUES ($1, $2)', ['Alice', '[email protected]']);// Update dataawait pool.query( 'UPDATE users SET name = $1 WHERE id = $2', ['Bob', 1]);
Install the PostgreSQL client:
Copy
pip install psycopg2-binary
Then develop like you normally would, using the env_var_key you defined in your suga.yaml.
Copy
import psycopg2import os# Connection string automatically injected by Sugaconn = psycopg2.connect(os.environ['DATABASE_URL'])cursor = conn.cursor()# Query databasecursor.execute('SELECT * FROM users WHERE active = %s', [True])users = cursor.fetchall()# Insert datacursor.execute( 'INSERT INTO users (name, email) VALUES (%s, %s)', ['Alice', '[email protected]'])conn.commit()# Update datacursor.execute( 'UPDATE users SET name = %s WHERE id = %s', ['Bob', 1])conn.commit()
Install the PostgreSQL client:
Copy
go get github.com/jackc/pgx/v5/pgxpool
Then develop like you normally would, using the env_var_key you defined in your suga.yaml.
Copy
import ( "context" "os" "github.com/jackc/pgx/v5/pgxpool")// Connection string automatically injected by Sugapool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))if err != nil { panic(err)}defer pool.Close()// Query databaserows, err := pool.Query(context.Background(), "SELECT * FROM users WHERE active = $1", true)// Insert data_, err = pool.Exec(context.Background(), "INSERT INTO users (name, email) VALUES ($1, $2)", "Alice", "[email protected]")// Update data_, err = pool.Exec(context.Background(), "UPDATE users SET name = $1 WHERE id = $2", "Bob", 1)