[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6G9AJWPNE77FBRBX650VBFP":3,"skill-same:01M6G9AJWPNE77FBRBX650VBFP":76},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":22,"publishedAt":43,"linkOnly":44,"markdownContent":45,"markdownBody":46,"frontMatter":47,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":13,"repositoryHtmlUrl":53,"repositoryHomepageUrl":6,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":55,"install":56,"resources":69},"01M6G9AJWPNE77FBRBX650VBFP","azure-postgres-ts",null,"Connect to Azure Database for PostgreSQL Flexible Server from Node.js\u002FTypeScript using the pg (node-postgres) package. Use for PostgreSQL queries, connection pooling, transactions, and Microsoft Entra ID (passwordless) authentication. Triggers: \"PostgreSQL\", \"postgres\", \"pg client\", \"node-postgres\", \"Azure PostgreSQL connection\", \"PostgreSQL TypeScript\", \"pg Pool\", \"passwordless postgres\".","ricardoaevt\u002Fnexus-roms","ricardoaevt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F164531880?v=4","01M6DGFGSV6CF9AKPHABBREC79","01M6DGFGYNNPJVDFQA05TDPSBN",0,"AGPL-3.0","https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fmicrosoft_skills\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fazure-postgres-ts\u002FSKILL.md",[17],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",[23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],"azure postgres","azure","azure postgres ts","postgres","passwordless","id","triggers","connection pooling","queries","use","node","transactions","typescript","server","package","postgresql","database","authentication","connect","entra id","2026-11-10 10:12:30",false,"---\nname: azure-postgres-ts\ndescription: |\n  Connect to Azure Database for PostgreSQL Flexible Server from Node.js\u002FTypeScript using the pg (node-postgres) package. Use for PostgreSQL queries, connection pooling, transactions, and Microsoft Entra ID (passwordless) authentication. Triggers: \"PostgreSQL\", \"postgres\", \"pg client\", \"node-postgres\", \"Azure PostgreSQL connection\", \"PostgreSQL TypeScript\", \"pg Pool\", \"passwordless postgres\".\npackage: pg\n---\n\n# Azure PostgreSQL for TypeScript (node-postgres)\n\nConnect to Azure Database for PostgreSQL Flexible Server using the `pg` (node-postgres) package with support for password and Microsoft Entra ID (passwordless) authentication.\n\n## Installation\n\n```bash\nnpm install pg @azure\u002Fidentity\nnpm install -D @types\u002Fpg\n```\n\n## Environment Variables\n\n```bash\n# Required\nAZURE_POSTGRESQL_HOST=\u003Cserver>.postgres.database.azure.com\nAZURE_POSTGRESQL_DATABASE=\u003Cdatabase>\nAZURE_POSTGRESQL_PORT=5432\n\n# For password authentication\nAZURE_POSTGRESQL_USER=\u003Cusername>\nAZURE_POSTGRESQL_PASSWORD=\u003Cpassword>\n\n# For Entra ID authentication\nAZURE_POSTGRESQL_USER=\u003Centra-user>@\u003Cserver>   # e.g., user@contoso.com\nAZURE_POSTGRESQL_CLIENTID=\u003Cmanaged-identity-client-id>  # For user-assigned identity\n```\n\n## Authentication\n\n### Option 1: Password Authentication\n\n```typescript\nimport { Client, Pool } from \"pg\";\n\nconst client = new Client({\n  host: process.env.AZURE_POSTGRESQL_HOST,\n  database: process.env.AZURE_POSTGRESQL_DATABASE,\n  user: process.env.AZURE_POSTGRESQL_USER,\n  password: process.env.AZURE_POSTGRESQL_PASSWORD,\n  port: Number(process.env.AZURE_POSTGRESQL_PORT) || 5432,\n  ssl: { rejectUnauthorized: true }  \u002F\u002F Required for Azure\n});\n\nawait client.connect();\n```\n\n### Option 2: Microsoft Entra ID (Passwordless) - Recommended\n\n```typescript\nimport { Client, Pool } from \"pg\";\nimport { DefaultAzureCredential } from \"@azure\u002Fidentity\";\n\n\u002F\u002F For system-assigned managed identity\nconst credential = new DefaultAzureCredential();\n\n\u002F\u002F For user-assigned managed identity\n\u002F\u002F const credential = new DefaultAzureCredential({\n\u002F\u002F   managedIdentityClientId: process.env.AZURE_POSTGRESQL_CLIENTID\n\u002F\u002F });\n\n\u002F\u002F Acquire access token for Azure PostgreSQL\nconst tokenResponse = await credential.getToken(\n  \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\"\n);\n\nconst client = new Client({\n  host: process.env.AZURE_POSTGRESQL_HOST,\n  database: process.env.AZURE_POSTGRESQL_DATABASE,\n  user: process.env.AZURE_POSTGRESQL_USER,  \u002F\u002F Entra ID user\n  password: tokenResponse.token,             \u002F\u002F Token as password\n  port: Number(process.env.AZURE_POSTGRESQL_PORT) || 5432,\n  ssl: { rejectUnauthorized: true }\n});\n\nawait client.connect();\n```\n\n## Core Workflows\n\n### 1. Single Client Connection\n\n```typescript\nimport { Client } from \"pg\";\n\nconst client = new Client({\n  host: process.env.AZURE_POSTGRESQL_HOST,\n  database: process.env.AZURE_POSTGRESQL_DATABASE,\n  user: process.env.AZURE_POSTGRESQL_USER,\n  password: process.env.AZURE_POSTGRESQL_PASSWORD,\n  port: 5432,\n  ssl: { rejectUnauthorized: true }\n});\n\ntry {\n  await client.connect();\n  \n  const result = await client.query(\"SELECT NOW() as current_time\");\n  console.log(result.rows[0].current_time);\n} finally {\n  await client.end();  \u002F\u002F Always close connection\n}\n```\n\n### 2. Connection Pool (Recommended for Production)\n\n```typescript\nimport { Pool } from \"pg\";\n\nconst pool = new Pool({\n  host: process.env.AZURE_POSTGRESQL_HOST,\n  database: process.env.AZURE_POSTGRESQL_DATABASE,\n  user: process.env.AZURE_POSTGRESQL_USER,\n  password: process.env.AZURE_POSTGRESQL_PASSWORD,\n  port: 5432,\n  ssl: { rejectUnauthorized: true },\n  \n  \u002F\u002F Pool configuration\n  max: 20,                    \u002F\u002F Maximum connections in pool\n  idleTimeoutMillis: 30000,   \u002F\u002F Close idle connections after 30s\n  connectionTimeoutMillis: 10000  \u002F\u002F Timeout for new connections\n});\n\n\u002F\u002F Query using pool (automatically acquires and releases connection)\nconst result = await pool.query(\"SELECT * FROM users WHERE id = $1\", [userId]);\n\n\u002F\u002F Explicit checkout for multiple queries\nconst client = await pool.connect();\ntry {\n  const res1 = await client.query(\"SELECT * FROM users\");\n  const res2 = await client.query(\"SELECT * FROM orders\");\n} finally {\n  client.release();  \u002F\u002F Return connection to pool\n}\n\n\u002F\u002F Cleanup on shutdown\nawait pool.end();\n```\n\n### 3. Parameterized Queries (Prevent SQL Injection)\n\n```typescript\n\u002F\u002F ALWAYS use parameterized queries - never concatenate user input\nconst userId = 123;\nconst email = \"user@example.com\";\n\n\u002F\u002F Single parameter\nconst result = await pool.query(\n  \"SELECT * FROM users WHERE id = $1\",\n  [userId]\n);\n\n\u002F\u002F Multiple parameters\nconst result = await pool.query(\n  \"INSERT INTO users (email, name, created_at) VALUES ($1, $2, NOW()) RETURNING *\",\n  [email, \"John Doe\"]\n);\n\n\u002F\u002F Array parameter\nconst ids = [1, 2, 3, 4, 5];\nconst result = await pool.query(\n  \"SELECT * FROM users WHERE id = ANY($1::int[])\",\n  [ids]\n);\n```\n\n### 4. Transactions\n\n```typescript\nconst client = await pool.connect();\n\ntry {\n  await client.query(\"BEGIN\");\n  \n  const userResult = await client.query(\n    \"INSERT INTO users (email) VALUES ($1) RETURNING id\",\n    [\"user@example.com\"]\n  );\n  const userId = userResult.rows[0].id;\n  \n  await client.query(\n    \"INSERT INTO orders (user_id, total) VALUES ($1, $2)\",\n    [userId, 99.99]\n  );\n  \n  await client.query(\"COMMIT\");\n} catch (error) {\n  await client.query(\"ROLLBACK\");\n  throw error;\n} finally {\n  client.release();\n}\n```\n\n### 5. Transaction Helper Function\n\n```typescript\nasync function withTransaction\u003CT>(\n  pool: Pool,\n  fn: (client: PoolClient) => Promise\u003CT>\n): Promise\u003CT> {\n  const client = await pool.connect();\n  try {\n    await client.query(\"BEGIN\");\n    const result = await fn(client);\n    await client.query(\"COMMIT\");\n    return result;\n  } catch (error) {\n    await client.query(\"ROLLBACK\");\n    throw error;\n  } finally {\n    client.release();\n  }\n}\n\n\u002F\u002F Usage\nconst order = await withTransaction(pool, async (client) => {\n  const user = await client.query(\n    \"INSERT INTO users (email) VALUES ($1) RETURNING *\",\n    [\"user@example.com\"]\n  );\n  const order = await client.query(\n    \"INSERT INTO orders (user_id, total) VALUES ($1, $2) RETURNING *\",\n    [user.rows[0].id, 99.99]\n  );\n  return order.rows[0];\n});\n```\n\n### 6. Typed Queries with TypeScript\n\n```typescript\nimport { Pool, QueryResult } from \"pg\";\n\ninterface User {\n  id: number;\n  email: string;\n  name: string;\n  created_at: Date;\n}\n\n\u002F\u002F Type the query result\nconst result: QueryResult\u003CUser> = await pool.query\u003CUser>(\n  \"SELECT * FROM users WHERE id = $1\",\n  [userId]\n);\n\nconst user: User | undefined = result.rows[0];\n\n\u002F\u002F Type-safe insert\nasync function createUser(\n  pool: Pool,\n  email: string,\n  name: string\n): Promise\u003CUser> {\n  const result = await pool.query\u003CUser>(\n    \"INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *\",\n    [email, name]\n  );\n  return result.rows[0];\n}\n```\n\n## Pool with Entra ID Token Refresh\n\nFor long-running applications, tokens expire and need refresh:\n\n```typescript\nimport { Pool, PoolConfig } from \"pg\";\nimport { DefaultAzureCredential, AccessToken } from \"@azure\u002Fidentity\";\n\nclass AzurePostgresPool {\n  private pool: Pool | null = null;\n  private credential: DefaultAzureCredential;\n  private tokenExpiry: Date | null = null;\n  private config: Omit\u003CPoolConfig, \"password\">;\n\n  constructor(config: Omit\u003CPoolConfig, \"password\">) {\n    this.credential = new DefaultAzureCredential();\n    this.config = config;\n  }\n\n  private async getToken(): Promise\u003Cstring> {\n    const tokenResponse = await this.credential.getToken(\n      \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\"\n    );\n    this.tokenExpiry = new Date(tokenResponse.expiresOnTimestamp);\n    return tokenResponse.token;\n  }\n\n  private isTokenExpired(): boolean {\n    if (!this.tokenExpiry) return true;\n    \u002F\u002F Refresh 5 minutes before expiry\n    return new Date() >= new Date(this.tokenExpiry.getTime() - 5 * 60 * 1000);\n  }\n\n  async getPool(): Promise\u003CPool> {\n    if (this.pool && !this.isTokenExpired()) {\n      return this.pool;\n    }\n\n    \u002F\u002F Close existing pool if token expired\n    if (this.pool) {\n      await this.pool.end();\n    }\n\n    const token = await this.getToken();\n    this.pool = new Pool({\n      ...this.config,\n      password: token\n    });\n\n    return this.pool;\n  }\n\n  async query\u003CT>(text: string, params?: any[]): Promise\u003CQueryResult\u003CT>> {\n    const pool = await this.getPool();\n    return pool.query\u003CT>(text, params);\n  }\n\n  async end(): Promise\u003Cvoid> {\n    if (this.pool) {\n      await this.pool.end();\n      this.pool = null;\n    }\n  }\n}\n\n\u002F\u002F Usage\nconst azurePool = new AzurePostgresPool({\n  host: process.env.AZURE_POSTGRESQL_HOST!,\n  database: process.env.AZURE_POSTGRESQL_DATABASE!,\n  user: process.env.AZURE_POSTGRESQL_USER!,\n  port: 5432,\n  ssl: { rejectUnauthorized: true },\n  max: 20\n});\n\nconst result = await azurePool.query(\"SELECT NOW()\");\n```\n\n## Error Handling\n\n```typescript\nimport { DatabaseError } from \"pg\";\n\ntry {\n  await pool.query(\"INSERT INTO users (email) VALUES ($1)\", [email]);\n} catch (error) {\n  if (error instanceof DatabaseError) {\n    switch (error.code) {\n      case \"23505\":  \u002F\u002F unique_violation\n        console.error(\"Duplicate entry:\", error.detail);\n        break;\n      case \"23503\":  \u002F\u002F foreign_key_violation\n        console.error(\"Foreign key constraint failed:\", error.detail);\n        break;\n      case \"42P01\":  \u002F\u002F undefined_table\n        console.error(\"Table does not exist:\", error.message);\n        break;\n      case \"28P01\":  \u002F\u002F invalid_password\n        console.error(\"Authentication failed\");\n        break;\n      case \"57P03\":  \u002F\u002F cannot_connect_now (server starting)\n        console.error(\"Server unavailable, retry later\");\n        break;\n      default:\n        console.error(`PostgreSQL error ${error.code}: ${error.message}`);\n    }\n  }\n  throw error;\n}\n```\n\n## Connection String Format\n\n```typescript\n\u002F\u002F Alternative: Use connection string\nconst pool = new Pool({\n  connectionString: `postgres:\u002F\u002F${user}:${password}@${host}:${port}\u002F${database}?sslmode=require`\n});\n\n\u002F\u002F With SSL required (Azure)\nconst connectionString = \n  `postgres:\u002F\u002Fuser:password@server.postgres.database.azure.com:5432\u002Fmydb?sslmode=require`;\n```\n\n## Pool Events\n\n```typescript\nconst pool = new Pool({ \u002F* config *\u002F });\n\npool.on(\"connect\", (client) => {\n  console.log(\"New client connected to pool\");\n});\n\npool.on(\"acquire\", (client) => {\n  console.log(\"Client checked out from pool\");\n});\n\npool.on(\"release\", (err, client) => {\n  console.log(\"Client returned to pool\");\n});\n\npool.on(\"remove\", (client) => {\n  console.log(\"Client removed from pool\");\n});\n\npool.on(\"error\", (err, client) => {\n  console.error(\"Unexpected pool error:\", err);\n});\n```\n\n## Azure-Specific Configuration\n\n| Setting | Value | Description |\n|---------|-------|-------------|\n| `ssl.rejectUnauthorized` | `true` | Always use SSL for Azure |\n| Default port | `5432` | Standard PostgreSQL port |\n| PgBouncer port | `6432` | Use when PgBouncer enabled |\n| Token scope | `https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default` | Entra ID token scope |\n| Token lifetime | ~1 hour | Refresh before expiry |\n\n## Pool Sizing Guidelines\n\n| Workload | `max` | `idleTimeoutMillis` |\n|----------|-------|---------------------|\n| Light (dev\u002Ftest) | 5-10 | 30000 |\n| Medium (production) | 20-30 | 30000 |\n| Heavy (high concurrency) | 50-100 | 10000 |\n\n> **Note**: Azure PostgreSQL has connection limits based on SKU. Check your tier's max connections.\n\n## Best Practices\n\n1. **Always use connection pools** for production applications\n2. **Use parameterized queries** - Never concatenate user input\n3. **Always close connections** - Use `try\u002Ffinally` or connection pools\n4. **Enable SSL** - Required for Azure (`ssl: { rejectUnauthorized: true }`)\n5. **Handle token refresh** - Entra ID tokens expire after ~1 hour\n6. **Set connection timeouts** - Avoid hanging on network issues\n7. **Use transactions** - For multi-statement operations\n8. **Monitor pool metrics** - Track `pool.totalCount`, `pool.idleCount`, `pool.waitingCount`\n9. **Graceful shutdown** - Call `pool.end()` on application termination\n10. **Use TypeScript generics** - Type your query results for safety\n\n## Key Types\n\n```typescript\nimport {\n  Client,\n  Pool,\n  PoolClient,\n  PoolConfig,\n  QueryResult,\n  QueryResultRow,\n  DatabaseError,\n  QueryConfig\n} from \"pg\";\n```\n\n## Reference Links\n\n| Resource | URL |\n|----------|-----|\n| node-postgres Docs | https:\u002F\u002Fnode-postgres.com |\n| npm Package | https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fpg |\n| GitHub Repository | https:\u002F\u002Fgithub.com\u002Fbrianc\u002Fnode-postgres |\n| Azure PostgreSQL Docs | https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fpostgresql\u002Fflexible-server\u002F |\n| Passwordless Connection | https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fpostgresql\u002Fflexible-server\u002Fhow-to-connect-with-managed-identity |\n","# Azure PostgreSQL for TypeScript (node-postgres)\n\nConnect to Azure Database for PostgreSQL Flexible Server using the `pg` (node-postgres) package with support for password and Microsoft Entra ID (passwordless) authentication.\n\n## Installation\n\n```bash\nnpm install pg @azure\u002Fidentity\nnpm install -D @types\u002Fpg\n```\n\n## Environment Variables\n\n```bash\n# Required\nAZURE_POSTGRESQL_HOST=\u003Cserver>.postgres.database.azure.com\nAZURE_POSTGRESQL_DATABASE=\u003Cdatabase>\nAZURE_POSTGRESQL_PORT=5432\n\n# For password authentication\nAZURE_POSTGRESQL_USER=\u003Cusername>\nAZURE_POSTGRESQL_PASSWORD=\u003Cpassword>\n\n# For Entra ID authentication\nAZURE_POSTGRESQL_USER=\u003Centra-user>@\u003Cserver>   # e.g., user@contoso.com\nAZURE_POSTGRESQL_CLIENTID=\u003Cmanaged-identity-client-id>  # For user-assigned identity\n```\n\n## Authentication\n\n### Option 1: Password Authentication\n\n```typescript\nimport { Client, Pool } from \"pg\";\n\nconst client = new Client({\n  host: process.env.AZURE_POSTGRESQL_HOST,\n  database: process.env.AZURE_POSTGRESQL_DATABASE,\n  user: process.env.AZURE_POSTGRESQL_USER,\n  password: process.env.AZURE_POSTGRESQL_PASSWORD,\n  port: Number(process.env.AZURE_POSTGRESQL_PORT) || 5432,\n  ssl: { rejectUnauthorized: true }  \u002F\u002F Required for Azure\n});\n\nawait client.connect();\n```\n\n### Option 2: Microsoft Entra ID (Passwordless) - Recommended\n\n```typescript\nimport { Client, Pool } from \"pg\";\nimport { DefaultAzureCredential } from \"@azure\u002Fidentity\";\n\n\u002F\u002F For system-assigned managed identity\nconst credential = new DefaultAzureCredential();\n\n\u002F\u002F For user-assigned managed identity\n\u002F\u002F const credential = new DefaultAzureCredential({\n\u002F\u002F   managedIdentityClientId: process.env.AZURE_POSTGRESQL_CLIENTID\n\u002F\u002F });\n\n\u002F\u002F Acquire access token for Azure PostgreSQL\nconst tokenResponse = await credential.getToken(\n  \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\"\n);\n\nconst client = new Client({\n  host: process.env.AZURE_POSTGRESQL_HOST,\n  database: process.env.AZURE_POSTGRESQL_DATABASE,\n  user: process.env.AZURE_POSTGRESQL_USER,  \u002F\u002F Entra ID user\n  password: tokenResponse.token,             \u002F\u002F Token as password\n  port: Number(process.env.AZURE_POSTGRESQL_PORT) || 5432,\n  ssl: { rejectUnauthorized: true }\n});\n\nawait client.connect();\n```\n\n## Core Workflows\n\n### 1. Single Client Connection\n\n```typescript\nimport { Client } from \"pg\";\n\nconst client = new Client({\n  host: process.env.AZURE_POSTGRESQL_HOST,\n  database: process.env.AZURE_POSTGRESQL_DATABASE,\n  user: process.env.AZURE_POSTGRESQL_USER,\n  password: process.env.AZURE_POSTGRESQL_PASSWORD,\n  port: 5432,\n  ssl: { rejectUnauthorized: true }\n});\n\ntry {\n  await client.connect();\n  \n  const result = await client.query(\"SELECT NOW() as current_time\");\n  console.log(result.rows[0].current_time);\n} finally {\n  await client.end();  \u002F\u002F Always close connection\n}\n```\n\n### 2. Connection Pool (Recommended for Production)\n\n```typescript\nimport { Pool } from \"pg\";\n\nconst pool = new Pool({\n  host: process.env.AZURE_POSTGRESQL_HOST,\n  database: process.env.AZURE_POSTGRESQL_DATABASE,\n  user: process.env.AZURE_POSTGRESQL_USER,\n  password: process.env.AZURE_POSTGRESQL_PASSWORD,\n  port: 5432,\n  ssl: { rejectUnauthorized: true },\n  \n  \u002F\u002F Pool configuration\n  max: 20,                    \u002F\u002F Maximum connections in pool\n  idleTimeoutMillis: 30000,   \u002F\u002F Close idle connections after 30s\n  connectionTimeoutMillis: 10000  \u002F\u002F Timeout for new connections\n});\n\n\u002F\u002F Query using pool (automatically acquires and releases connection)\nconst result = await pool.query(\"SELECT * FROM users WHERE id = $1\", [userId]);\n\n\u002F\u002F Explicit checkout for multiple queries\nconst client = await pool.connect();\ntry {\n  const res1 = await client.query(\"SELECT * FROM users\");\n  const res2 = await client.query(\"SELECT * FROM orders\");\n} finally {\n  client.release();  \u002F\u002F Return connection to pool\n}\n\n\u002F\u002F Cleanup on shutdown\nawait pool.end();\n```\n\n### 3. Parameterized Queries (Prevent SQL Injection)\n\n```typescript\n\u002F\u002F ALWAYS use parameterized queries - never concatenate user input\nconst userId = 123;\nconst email = \"user@example.com\";\n\n\u002F\u002F Single parameter\nconst result = await pool.query(\n  \"SELECT * FROM users WHERE id = $1\",\n  [userId]\n);\n\n\u002F\u002F Multiple parameters\nconst result = await pool.query(\n  \"INSERT INTO users (email, name, created_at) VALUES ($1, $2, NOW()) RETURNING *\",\n  [email, \"John Doe\"]\n);\n\n\u002F\u002F Array parameter\nconst ids = [1, 2, 3, 4, 5];\nconst result = await pool.query(\n  \"SELECT * FROM users WHERE id = ANY($1::int[])\",\n  [ids]\n);\n```\n\n### 4. Transactions\n\n```typescript\nconst client = await pool.connect();\n\ntry {\n  await client.query(\"BEGIN\");\n  \n  const userResult = await client.query(\n    \"INSERT INTO users (email) VALUES ($1) RETURNING id\",\n    [\"user@example.com\"]\n  );\n  const userId = userResult.rows[0].id;\n  \n  await client.query(\n    \"INSERT INTO orders (user_id, total) VALUES ($1, $2)\",\n    [userId, 99.99]\n  );\n  \n  await client.query(\"COMMIT\");\n} catch (error) {\n  await client.query(\"ROLLBACK\");\n  throw error;\n} finally {\n  client.release();\n}\n```\n\n### 5. Transaction Helper Function\n\n```typescript\nasync function withTransaction\u003CT>(\n  pool: Pool,\n  fn: (client: PoolClient) => Promise\u003CT>\n): Promise\u003CT> {\n  const client = await pool.connect();\n  try {\n    await client.query(\"BEGIN\");\n    const result = await fn(client);\n    await client.query(\"COMMIT\");\n    return result;\n  } catch (error) {\n    await client.query(\"ROLLBACK\");\n    throw error;\n  } finally {\n    client.release();\n  }\n}\n\n\u002F\u002F Usage\nconst order = await withTransaction(pool, async (client) => {\n  const user = await client.query(\n    \"INSERT INTO users (email) VALUES ($1) RETURNING *\",\n    [\"user@example.com\"]\n  );\n  const order = await client.query(\n    \"INSERT INTO orders (user_id, total) VALUES ($1, $2) RETURNING *\",\n    [user.rows[0].id, 99.99]\n  );\n  return order.rows[0];\n});\n```\n\n### 6. Typed Queries with TypeScript\n\n```typescript\nimport { Pool, QueryResult } from \"pg\";\n\ninterface User {\n  id: number;\n  email: string;\n  name: string;\n  created_at: Date;\n}\n\n\u002F\u002F Type the query result\nconst result: QueryResult\u003CUser> = await pool.query\u003CUser>(\n  \"SELECT * FROM users WHERE id = $1\",\n  [userId]\n);\n\nconst user: User | undefined = result.rows[0];\n\n\u002F\u002F Type-safe insert\nasync function createUser(\n  pool: Pool,\n  email: string,\n  name: string\n): Promise\u003CUser> {\n  const result = await pool.query\u003CUser>(\n    \"INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *\",\n    [email, name]\n  );\n  return result.rows[0];\n}\n```\n\n## Pool with Entra ID Token Refresh\n\nFor long-running applications, tokens expire and need refresh:\n\n```typescript\nimport { Pool, PoolConfig } from \"pg\";\nimport { DefaultAzureCredential, AccessToken } from \"@azure\u002Fidentity\";\n\nclass AzurePostgresPool {\n  private pool: Pool | null = null;\n  private credential: DefaultAzureCredential;\n  private tokenExpiry: Date | null = null;\n  private config: Omit\u003CPoolConfig, \"password\">;\n\n  constructor(config: Omit\u003CPoolConfig, \"password\">) {\n    this.credential = new DefaultAzureCredential();\n    this.config = config;\n  }\n\n  private async getToken(): Promise\u003Cstring> {\n    const tokenResponse = await this.credential.getToken(\n      \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\"\n    );\n    this.tokenExpiry = new Date(tokenResponse.expiresOnTimestamp);\n    return tokenResponse.token;\n  }\n\n  private isTokenExpired(): boolean {\n    if (!this.tokenExpiry) return true;\n    \u002F\u002F Refresh 5 minutes before expiry\n    return new Date() >= new Date(this.tokenExpiry.getTime() - 5 * 60 * 1000);\n  }\n\n  async getPool(): Promise\u003CPool> {\n    if (this.pool && !this.isTokenExpired()) {\n      return this.pool;\n    }\n\n    \u002F\u002F Close existing pool if token expired\n    if (this.pool) {\n      await this.pool.end();\n    }\n\n    const token = await this.getToken();\n    this.pool = new Pool({\n      ...this.config,\n      password: token\n    });\n\n    return this.pool;\n  }\n\n  async query\u003CT>(text: string, params?: any[]): Promise\u003CQueryResult\u003CT>> {\n    const pool = await this.getPool();\n    return pool.query\u003CT>(text, params);\n  }\n\n  async end(): Promise\u003Cvoid> {\n    if (this.pool) {\n      await this.pool.end();\n      this.pool = null;\n    }\n  }\n}\n\n\u002F\u002F Usage\nconst azurePool = new AzurePostgresPool({\n  host: process.env.AZURE_POSTGRESQL_HOST!,\n  database: process.env.AZURE_POSTGRESQL_DATABASE!,\n  user: process.env.AZURE_POSTGRESQL_USER!,\n  port: 5432,\n  ssl: { rejectUnauthorized: true },\n  max: 20\n});\n\nconst result = await azurePool.query(\"SELECT NOW()\");\n```\n\n## Error Handling\n\n```typescript\nimport { DatabaseError } from \"pg\";\n\ntry {\n  await pool.query(\"INSERT INTO users (email) VALUES ($1)\", [email]);\n} catch (error) {\n  if (error instanceof DatabaseError) {\n    switch (error.code) {\n      case \"23505\":  \u002F\u002F unique_violation\n        console.error(\"Duplicate entry:\", error.detail);\n        break;\n      case \"23503\":  \u002F\u002F foreign_key_violation\n        console.error(\"Foreign key constraint failed:\", error.detail);\n        break;\n      case \"42P01\":  \u002F\u002F undefined_table\n        console.error(\"Table does not exist:\", error.message);\n        break;\n      case \"28P01\":  \u002F\u002F invalid_password\n        console.error(\"Authentication failed\");\n        break;\n      case \"57P03\":  \u002F\u002F cannot_connect_now (server starting)\n        console.error(\"Server unavailable, retry later\");\n        break;\n      default:\n        console.error(`PostgreSQL error ${error.code}: ${error.message}`);\n    }\n  }\n  throw error;\n}\n```\n\n## Connection String Format\n\n```typescript\n\u002F\u002F Alternative: Use connection string\nconst pool = new Pool({\n  connectionString: `postgres:\u002F\u002F${user}:${password}@${host}:${port}\u002F${database}?sslmode=require`\n});\n\n\u002F\u002F With SSL required (Azure)\nconst connectionString = \n  `postgres:\u002F\u002Fuser:password@server.postgres.database.azure.com:5432\u002Fmydb?sslmode=require`;\n```\n\n## Pool Events\n\n```typescript\nconst pool = new Pool({ \u002F* config *\u002F });\n\npool.on(\"connect\", (client) => {\n  console.log(\"New client connected to pool\");\n});\n\npool.on(\"acquire\", (client) => {\n  console.log(\"Client checked out from pool\");\n});\n\npool.on(\"release\", (err, client) => {\n  console.log(\"Client returned to pool\");\n});\n\npool.on(\"remove\", (client) => {\n  console.log(\"Client removed from pool\");\n});\n\npool.on(\"error\", (err, client) => {\n  console.error(\"Unexpected pool error:\", err);\n});\n```\n\n## Azure-Specific Configuration\n\n| Setting | Value | Description |\n|---------|-------|-------------|\n| `ssl.rejectUnauthorized` | `true` | Always use SSL for Azure |\n| Default port | `5432` | Standard PostgreSQL port |\n| PgBouncer port | `6432` | Use when PgBouncer enabled |\n| Token scope | `https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default` | Entra ID token scope |\n| Token lifetime | ~1 hour | Refresh before expiry |\n\n## Pool Sizing Guidelines\n\n| Workload | `max` | `idleTimeoutMillis` |\n|----------|-------|---------------------|\n| Light (dev\u002Ftest) | 5-10 | 30000 |\n| Medium (production) | 20-30 | 30000 |\n| Heavy (high concurrency) | 50-100 | 10000 |\n\n> **Note**: Azure PostgreSQL has connection limits based on SKU. Check your tier's max connections.\n\n## Best Practices\n\n1. **Always use connection pools** for production applications\n2. **Use parameterized queries** - Never concatenate user input\n3. **Always close connections** - Use `try\u002Ffinally` or connection pools\n4. **Enable SSL** - Required for Azure (`ssl: { rejectUnauthorized: true }`)\n5. **Handle token refresh** - Entra ID tokens expire after ~1 hour\n6. **Set connection timeouts** - Avoid hanging on network issues\n7. **Use transactions** - For multi-statement operations\n8. **Monitor pool metrics** - Track `pool.totalCount`, `pool.idleCount`, `pool.waitingCount`\n9. **Graceful shutdown** - Call `pool.end()` on application termination\n10. **Use TypeScript generics** - Type your query results for safety\n\n## Key Types\n\n```typescript\nimport {\n  Client,\n  Pool,\n  PoolClient,\n  PoolConfig,\n  QueryResult,\n  QueryResultRow,\n  DatabaseError,\n  QueryConfig\n} from \"pg\";\n```\n\n## Reference Links\n\n| Resource | URL |\n|----------|-----|\n| node-postgres Docs | https:\u002F\u002Fnode-postgres.com |\n| npm Package | https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fpg |\n| GitHub Repository | https:\u002F\u002Fgithub.com\u002Fbrianc\u002Fnode-postgres |\n| Azure PostgreSQL Docs | https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fpostgresql\u002Fflexible-server\u002F |\n| Passwordless Connection | https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fpostgresql\u002Fflexible-server\u002Fhow-to-connect-with-managed-identity |\n",{"name":5,"package":48,"description":49},"pg","Connect to Azure Database for PostgreSQL Flexible Server from Node.js\u002FTypeScript using the pg (node-postgres) package. Use for PostgreSQL queries, connection pooling, transactions, and Microsoft Entra ID (passwordless) authentication. Triggers: \"PostgreSQL\", \"postgres\", \"pg client\", \"node-postgres\", \"Azure PostgreSQL connection\", \"PostgreSQL TypeScript\", \"pg Pool\", \"passwordless postgres\".\n","main","d41309588593cee5c2fb44062474efc3a99fbcb6",".agent\u002Fskills\u002Fmicrosoft_skills\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fazure-postgres-ts","https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms","https:\u002F\u002Fgithub.com\u002Fricardoaevt","2026-03-23 00:05:03",{"source":8,"skillName":5,"commands":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add ricardoaevt\u002Fnexus-roms --skill azure-postgres-ts",{"tool":62,"command":63},"bunx","bunx skills add ricardoaevt\u002Fnexus-roms --skill azure-postgres-ts",{"tool":65,"command":66},"pnpm","pnpm dlx skills add ricardoaevt\u002Fnexus-roms --skill azure-postgres-ts","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fmicrosoft_skills\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fazure-postgres-ts\u002FSKILL.md",true,[70],{"path":71,"resourceType":72,"resourceTypeDesc":73,"sizeBytes":74,"sourceHtmlUrl":75},"references\u002Facceptance-criteria.md","REFERENCE","参考文档",4413,"https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fmicrosoft_skills\u002F.github\u002Fplugins\u002Fazure-sdk-typescript\u002Fskills\u002Fazure-postgres-ts\u002Freferences\u002Facceptance-criteria.md",[77,101,117,132,143,152],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":81,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":43},"01M6G9HYKQRK6HBKVTZM3258M3","openspec-propose","Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.","MIT","https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fopenspec-propose\u002FSKILL.md",[],[85,86,87,88,89,90,91,92,93,94,95,32,96,97,98,99,100],"openspec propose","openspec","cli","generated","with","proposal","complete","get","build","implementation","ready","user","artifacts","tasks","change","design",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":81,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":43},"01M6G9HV9V20WFCHYVSDNQMJVK","openspec-new-change","Start a new OpenSpec change using the experimental artifact workflow. Use when the user wants to create a new feature, fix, or modification with a structured step-by-step approach.","https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fopenspec-new-change\u002FSKILL.md",[],[86,108,99,109,87,110,111,112,32,96,113,114,115,116,89],"openspec new change","new feature","structured","artifact","workflow","create","start","fix","feature",{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":81,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":43},"01M6G9HRF6R89QZXGSFC9DRQW3","openspec-explore","Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.","https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fopenspec-explore\u002FSKILL.md",[],[124,125,86,32,126,87,99,96,127,128,129,130,131],"openspec explore","explore","partner","think","thinking partner","thinking","ideas","requirements",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":81,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":43},"01M6G9HP3APFCXZG7XRWBMM524","openspec-continue-change","Continue working on an OpenSpec change by creating the next artifact. Use when the user wants to progress their change, create the next artifact, or continue their workflow.","https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fopenspec-continue-change\u002FSKILL.md",[],[86,139,140,99,112,87,113,96,32,141,111,142],"continue","openspec continue change","next","progress",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":81,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":43},"01M6G9HKT3WMSDBSKA7YM4MSSQ","openspec-archive-change","Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.","https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fopenspec-archive-change\u002FSKILL.md",[],[150,86,151,99,87,112,96,32,94,91],"openspec archive change","archive",{"skillNo":153,"name":154,"nameZh":6,"description":155,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":81,"licenseFileUrl":6,"sourceHtmlUrl":156,"categories":157,"keywords":158,"publishedAt":43},"01M6G9HHEG0RJK4E0YTVZZ6A8T","openspec-apply-change","Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.","https:\u002F\u002Fgithub.com\u002Fricardoaevt\u002Fnexus-roms\u002Fblob\u002Fmain\u002F.agent\u002Fskills\u002Fopenspec-apply-change\u002FSKILL.md",[],[86,99,159,160,98,114,139,161,96,32,94,87],"openspec apply change","implement","work"]