--- id: 6d3dcf69-9c0c-4d8a-b1a7-27267c07da51 type: code_pattern title: "CloudSQL write_to_cloudsql pattern with Postgres function" tags: [esb-monorepo, object-handler, python, cloudsql, pattern] importance: 0.7 confidence: 0.8 created: "2025-12-10T19:55:28.150687+00:00" updated: "2025-12-10T19:55:28.150687+00:00" relations: - target: db7cb384-b686-4afc-956c-ff74861a11cc type: SOLVES direction: incoming strength: 0.5 - target: e80e161a-4be4-428d-8590-267b9ab4cc7c type: BUILDS_ON direction: incoming strength: 0.5 --- Pattern for calling Postgres upsert functions from Python via Cloud SQL Connector: (1) Strip unwanted fields (e.g., raw_data) before sending, (2) Build function name from object_type: fn_upsert_{object_type.lower()}, (3) Pass data as JSONB: cursor.execute('SELECT fn_upsert_account(%s::jsonb)', (json.dumps(data),)), (4) Use connection singleton for serverless pooling, (5) Always close connection in finally block. Env vars: CLOUDSQL_INSTANCE, CLOUDSQL_USER, CLOUDSQL_DATABASE, CLOUDSQL_IAM_AUTH, CLOUDSQL_PASSWORD (if not IAM).