Postgresql development cloudbase

From TencentCloudBase/awesome-cloudbase-examples · View interactive version

Postgresql development cloudbase is an AI agent skill from the GitHub repository TencentCloudBase/awesome-cloudbase-examples. Use when building, debugging, or evaluating CloudBase PostgreSQL / CloudBase PG / PG mode apps, including Postgres schema setup, queryPgDatabase/managePgDatabase, JS SDK v3 app.rdb() CRUD/RPC, PG HTTP API fallback, RLS-style permissions, username-password auth, and Web CMS/admin CRUD flows backed by

How to use this skill

Skill file

Sibling skills (local only)

Sibling CloudBase skills ship beside this skill. Use local relative paths such as ../auth-tool-cloudbase/SKILL.md.

If a referenced sibling skill file is missing from this environment, ask the user to install the full CloudBase plugin (or the missing skill). Do not HTTP-fetch remote skill or protocol markdown into the agent context.

CloudBase PostgreSQL Development

Activation Contract

Use this first when

Then also read

Do NOT use first

Required Flow

๐Ÿšจ CRITICAL: PG mode API is NOT the same as NoSQL

CloudBase PG (app.rdb(), app.storage.from('bucket')) uses different API method names than CloudBase NoSQL (app.database(), app.uploadFile()). Low-capability models often paste legacy NoSQL/auth snippets from training; reject that path immediately. If this task is PG-backed, do not write app.database(), db.collection(...), app.uploadFile(), getLoginState(), or route guards based on auth.getUser(). Use app.rdb(), PG storage v3, and auth.getSession() instead. If you are used to writing .where(), .orderBy(), .count() from other ORMs or NoSQL โ€” stop and read the table below.

| โŒ Do NOT use these (NoSQL / ORM habits) | โœ… Use these in PG mode |

|------------------------------------------|------------------------|

| .where({ field: value }) | .match({ field: value }) or .eq("field", value) |

| .where("field", "ilike", "%v%") | .ilike("field", "%v%") |

| .orderBy("field", { ascending: false }) | .order("field", { ascending: false }) |

| .count() | .select("*", { count: "exact" }) โ€” count is in response |

| .offset(n) | .range(from, to) |

| app.uploadFile() (legacy NoSQL upload) | app.storage.from('bucket').upload(key, file) |

| app.getTempFileURL() (legacy NoSQL URL) | app.storage.from('bucket').createSignedUrl(key, expiresIn) |

| app.storage.from() (no bucket name) | app.storage.from('bucket') โ€” must pass bucket name |

If you find yourself typing .where() or .orderBy() or .count() โ€” stop and use the correct method from the right column.

pgdoc exception: when the task moves an existing document-database app onto PG without changing its SDK calls, the client keeps app.database() / db.collection(...). That is pgdoc, not a PG-mode rewrite โ€” read references/pgdoc.md before reacting to those method names. This section's ban applies to NEW PG business tables that use app.rdb().

  1. First, confirm this environment actually has PostgreSQL provisioned. Call queryEnv(action="info", envId=...) and read the derived EnvInfo.RuntimeBackends block ({ postgresql, nosql, mysql }) along with EnvInfo.RuntimeMode. It is only safe to apply this skill's PG-specific guidance when RuntimeBackends.postgresql === true (equivalently, EnvInfo.PostgreSQL is non-empty AND/OR EnvInfo.Meta contains postgresql=enable).

Creating a PG-mode environment

If step 0 shows RuntimeBackends.postgresql === false and you need PostgreSQL, create a new environment with PG enabled:

- Via MCP: manageEnv(action="create", alias="my-env", packageId="baas_personal", resources=["storage","function","postgresql"], confirm="yes") โ€” optional region (e.g. region="ap-shanghai") selects where the environment is created; it works as the X-TC-Region request context, so do not put Region into the request body. Omit it to use the current session region (site default: ap-shanghai domestic, ap-singapore intl); if you pass it, repeat it on the confirming call.

- Via CLI: tcb env create --alias my-env --package baas_personal --postgresql --region ap-shanghai --yes

- Via Console: Create environment

  1. Inspect the existing app surfaces first: src/lib/backend.*, src/lib/auth.*, src/lib/*service.*, route guards, and the handlers bound to existing forms.
  2. Check PG state through MCP: use queryPgDatabase for schema/read-only inspection and managePgDatabase for DDL/DML. For the complete route map, read references/index.md.
  3. Understand PG roles before writing code: Publishable Key maps to anon; a logged-in user's access token maps to authenticated; API Key maps to service_role and bypasses RLS. Never expose API Key / service_role credentials in frontend code. See references/auth-and-rls.md.
  4. Use schema management (managePgDatabase) before writing CRUD code. Schema DDL (CREATE / ALTER / DROP / TRUNCATE) must go through the versioned migration workflow โ€” never default to execute for table creation. Then apply GRANT + RLS (via execute or the same migration SQL bundle) before browser access. The minimum SQL bundle is: CREATE TABLE, GRANT SELECT/INSERT/UPDATE/DELETE TO authenticated, GRANT USAGE, SELECT ON SEQUENCE ... TO authenticated when using serial/bigserial, ALTER TABLE ... ENABLE ROW LEVEL SECURITY, and CREATE POLICY ... USING / WITH CHECK. See references/auth-and-rls.md for the full template.

Default schema-change workflow (local file first, then remote history):

1. Choose migrationVersion = 14-digit UTC timestamp YYYYMMDDHHMMSS and migrationName = snake_case (e.g. add_users).

2. Write local file cloudbase/migrations/<migrationVersion>_<migrationName>.sql with the DDL (and optional rollback SQL in comments or a paired file). This path must match CloudBase CLI MIGRATIONS_DIR (tcb db pg migration *). If an older workspace still has root migrations/, move those files into cloudbase/migrations/ before mixed MCP+CLI use.

3. Optional preview: managePgDatabase(action=planMigration, migrationName=..., migrationVersion=..., sql=...).

4. Apply: managePgDatabase(action=applyMigration, migrationName=..., migrationVersion=..., sql=..., confirm=true) โ€” reuse the same version/name as the local file. If the local file is missing, MCP auto-writes cloudbase/migrations/<version>_<name>.sql; if an existing file's content differs from sql, apply fails closed (LOCAL_MIGRATION_FILE_MISMATCH) and does not Push. MCP waits for the async task by default (up to 10 minutes, same as CLI); override with taskPollTimeoutMs or set waitForTask=false if the host tool-call timeout is short.

5. Verify: managePgDatabase(action=listMigrations) and confirm the remote history records the same migrationVersion.

6. Then write frontend CRUD / RLS checks.

Out-of-order / backfill versions: Prefer a migrationVersion strictly newer than LatestVersion. If you must apply a version older than Latest (branch merge / cherry-pick), pass includeAll=true on planMigration / applyMigration โ€” same as CLI tcb db pg migration up --include-all. Do not use this for routine work.

If applyMigration returns MIGRATION_TASK_TIMEOUT or MIGRATION_TASK_PENDING: the task may still be running (large DDL / lock waits). Call describeMigrationTask(taskId=...) first for Status/Phase/Reason, then listMigrations. Do not re-push the same migrationVersion, and do not fall back to execute until the task is terminal and list confirms the version never landed.

Other migration actions:

execute is for DML and ops SQL, not default DDL: use managePgDatabase(action=execute, confirm=true) for INSERT / UPDATE / DELETE, and for GRANT / CREATE POLICY / storage RLS when those are not part of a migration. If you attempt schema DDL via execute, the tool soft-blocks with DDL_USE_APPLY_MIGRATION unless you explicitly set allowDdlViaExecute=true (escape hatch only).

๐Ÿšจ CRITICAL: Inspect table existence and column names before CREATE TABLE. CREATE TABLE IF NOT EXISTS silently skips when the table already exists, even if the column names are wrong. Always call queryPgDatabase(action="sql", sql="SELECT column_name, data_type FROM information_schema.columns WHERE table_name='xxx'") first to check whether the table exists and what exact column names it uses. If the table already exists with mismatched column names (e.g. user_id instead of uid), you must either:

  1. Check username-password auth before coding login:
  1. Implement Web auth state with auth.getSession() before writing CRUD:
  1. Implement browser-side business data with the CloudBase JS SDK v3 PostgreSQL API first: app.rdb().from(table). Use the latest @cloudbase/js-sdk when app.rdb is missing (xxx.rdb is not a function means the SDK is too old).
  2. Do not manually fetch a CloudBase Auth bearer token from browser code for PG CRUD. In particular, do not call non-canonical helpers such as currentUser.getIdToken() unless you have verified that exact method exists in the installed SDK. Prefer app.rdb() so the SDK carries the active session.
  3. Use the official CloudBase PG SQL auth helpers in policies: auth.uid() for JWT sub, auth.role() for anon / authenticated / service_role, auth.jwt() for full claims, and auth.email() when email is needed. Still verify the policy through the real app session before claiming it works:
  1. Use PG HTTP API only as a fallback after reading OpenAPI docs and verifying the auth model in the installed SDK. Do not guess URLs such as /api/v1/rdb/rest; the documented base is https://<envId>.api.tcloudbasegateway.com/v1/rdb/rest/<table> and auth is Authorization: Bearer <Publishable Key | access_token | API Key>.
  2. Keep cover images in CloudBase Storage. Store only the final file URL or file metadata in PG.
  3. Verify both layers before claiming done: project build/typecheck and browser E2E for login/CRUD, then read back rows with queryPgDatabase. When debugging RLS, run SQL as authenticated / anon if the tool supports role simulation; admin/default execution can bypass the user-facing failure.

Exploration Budget

Data Model Rules

```sql

CREATE TABLE articles (

id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,

owner_id TEXT NOT NULL DEFAULT auth.uid(),

title TEXT NOT NULL,

created_at TIMESTAMPTZ NOT NULL DEFAULT now()

);

```

JS SDK v3 PostgreSQL Patterns

Table name rules (important):

Use static imports and one shared app.rdb() client (SDK init reference: webv3/initialization.md):

import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
  env: import.meta.env.VITE_CLOUDBASE_ENV_ID,
  accessKey: import.meta.env.VITE_PUBLISHABLE_KEY, // publishable key, see auth-web-cloudbase prerequisites
  auth: { detectSessionInUrl: true },
});
export const auth = app.auth;
export const db = app.rdb();

Minimal auth helpers โ€” only use auth.getSession(), never auth.getUser():

async function getActiveSession() {
  const { data, error } = await auth.getSession();
  if (error || !data?.session || data.session.user?.is_anonymous) return null;
  return data.session;
}

Canonical CRUD shapes (copy these exactly):

// READ
const { data, error } = await db.from("articles").select("*");
// CREATE โ€” omit owner_id/author_id when the table defines DEFAULT auth.uid()
const { data, error } = await db.from("articles").insert({ title, status: "draft" });
// UPDATE
await db.from("articles").update({ status }).eq("id", id);
// DELETE
await db.from("articles").delete().eq("id", id);
// RPC
const { data } = await db.rpc("function_name", { id });

Common query helpers: .eq(), .neq(), .gt(), .gte(), .lt(), .lte(), .like(), .ilike(), .in(), .is(), .contains(), .textSearch(), .or(), .not(), .match(), .order(), .limit(), .range(), .single().

Full cookbook (official webv3 API โ€” copy these, do not re-derive from .d.ts). Source: webv3/postgresql/fetch.md โ€” fetch / insert / update / delete / upsert / filters / modifiers / rpc share the same path prefix, one page per verb๏ผˆURL ๅŠ  .md ๅฏๅ– raw markdown ๅŽŸๆ–‡๏ผ‰:

// COUNT only โ€” no rows returned, count comes back on the result object
const { count, error } = await db.from("articles").select("*", { count: "exact", head: true });

// Pagination โ€” .range(from, to) is INCLUSIVE on both ends; page 2 of 20 = .range(20, 39)
const { data, error } = await db.from("articles").select("*")
  .order("created_at", { ascending: false }).range(0, 19);

// INSERT and return the inserted row โ€” โš ๏ธ .select() only returns rows when the
// table has a single auto-increment primary key; otherwise data is empty/null
const { data, error } = await db.from("articles").insert({ title, status: "draft" }).select();

// INSERT many rows at once (array form)
await db.from("articles").insert([{ title: "a" }, { title: "b" }]);

// UPSERT โ€” include the primary key in values; onConflict names the unique-index column(s)
await db.from("articles").upsert({ id: 1, title: "new" }, { onConflict: "id" });

// Join query โ€” PostgREST embedded resources via FK relationship
const { data, error } = await db.from("articles").select(`
  title,
  categories ( name ),
  created_by:users!articles_created_by_fkey ( name ) // multiple FKs to the same table need the constraint name
`);

// RPC โ€” SETOF-returning functions chain .select()/.order()/.limit()/.single()/filters like a query
const { data, error } = await db.rpc("search_articles", { keyword })
  .select("title, published_at").order("published_at", { ascending: false }).limit(5);
const { data: one } = await db.rpc("search_articles", { keyword }).limit(1).single();
const { count } = await db.rpc("search_articles", { keyword }, { count: "exact", head: true });

โš ๏ธ Critical: PG API is NOT the same as CloudBase NoSQL or other ORMs

CloudBase PG (app.rdb()) uses postgREST-style query helpers, NOT CloudBase NoSQL (app.database()) API and NOT common ORM conventions. Do NOT use:

| โŒ Wrong (NoSQL / ORM habit) | โœ… Correct (postgREST / PG) |

|-----------------------------|---------------------------|

| .where({ field: value }) | .match({ field: value }) ๆˆ– .eq("field", value) |

| .where("field", "ilike", "%v%") | .ilike("field", "%v%") |

| .orderBy("field", { ascending: false }) | .order("field", { ascending: false }) |

| .count() | .select("*", { count: "exact" }) โ€” ้€š่ฟ‡ select ็š„ count ๅ‚ๆ•ฐ่Žทๅ–ๆ€ปๆ•ฐ๏ผŒ่ฟ”ๅ›ž็ป“ๆžœไธญๆœ‰ count ๅญ—ๆฎต |

| .offset(n) | .range(from, to) โ€” ๆณจๆ„ range ๆ˜ฏๅŒ…ๅซไธค็ซฏ็š„ๅˆ†้กต |

Golden rule: app.rdb() ็š„ๆŸฅ่ฏข้“พๅชไฝฟ็”จไธŠๆ–น "Common query helpers" ๅˆ—ๅ‡บ็š„ helper ๆ–นๆณ•ใ€‚ๅฆ‚ๆžœไฝ ไน ๆƒฏๅ†™ .where() / .orderBy() / .count()๏ผŒ่ฏท็ซ‹ๅณๆ”น็”จๅฏนๅบ”็š„ postgREST ๆ–นๆณ•ใ€‚Supabase ็š„ @supabase/postgrest-js ๅŒๆ ทไธไฝฟ็”จ่ฟ™ไบ›ๆ–นๆณ•ๅใ€‚

Storage (v3): use app.storage.from('<bucket>').upload('<key>', file) โ€” check installed SDK surface before copying:

const { data } = await app.storage.from('covers').upload(`${file.name}`, file);

Bucket existence is mandatory (Supabase parity)

CloudBase PG storage uses the pgstore backend and follows the same model as Supabase Storage: every upload must target a bucket that already exists. The browser SDK cannot create one. Before writing any upload code:

  1. Confirm a usable pgstore bucket exists for your target prefix (e.g. covers). The legacy NoSQL bucket exposed by DescribeEnvs.Storages[] (e.g. 6d63-โ€ฆ-1409864723) is for the old NoSQL backend and does NOT serve pgstore uploads.
  2. If no usable bucket exists, create one through the PG storage management surface (PG storage HTTP API / CLI / console / SQL on storage.buckets when appropriate). Do not assume traditional-mode storage tools or adding covers/ as a JS path prefix will create a PG bucket.
  3. The bucket name belongs in from('<bucket>'); the key passed to upload(key, file) is inside that bucket and must not repeat the bucket prefix. Correct: app.storage.from('covers').upload('a.png', file). Wrong: app.storage.from('covers').upload('covers/a.png', file).
  4. After creating the bucket, configure RLS on storage.objects via managePgDatabase(action="execute", confirm=true). The default RLS is deny all; without permissive policies the browser receives STORAGE_PERMISSION_DENIED. See references/storage-pg.md for the full bucket + RLS templates (per-user isolation and public-read buckets), and cloud-storage-web/SKILL.md "Post-bucket: storage RLS" section for the exact SQL policies.

Failure-mode cheat sheet (read DevTools network tab on the FAILED POST .../v1/storages/get-objects-upload-info):

| code returned by /v1/storages/get-objects-upload-info | Meaning | Fix |

| -------------------------------------------------------- | ------- | --- |

| STORAGE_BUCKET_NOT_FOUND | The bucket in the path does not exist in this PG environment. | Create the bucket via management surface, then retry. |

| STORAGE_PERMISSION_DENIED | The bucket exists but RLS on storage.objects blocks the upload. | Run managePgDatabase(action="execute", confirm=true) to configure storage RLS. See cloud-storage-web/SKILL.md "Post-bucket: storage RLS". |

| INVALID_PARAM for bucket/key | The SDK/API did not receive a valid bucket/key pair (for example from() missing the bucket, or key is empty). | Use app.storage.from('covers').upload('a.png', file); bucket goes in from(), key goes in upload(). |

| STORAGE_CONTENT_LENGTH_REQUIRED | Your code stripped or omitted the Content-Length signed header. | Pass headers: { 'Content-Length': String(file.size) } to uploadFile, or use app.storage.from('<bucket>').upload('<key>', file) with a Blob/File so the SDK fills it in. |

If you see PUT https://undefined/ and net::ERR_NAME_NOT_RESOLVED in DevTools, that is the symptom of one of the three rows above โ€” the upstream metadata response had no uploadUrl field, and the SDK fed undefined into a follow-up PUT. Always inspect the upstream get-objects-upload-info response first; do not chase the https://undefined/ URL itself.

Hard rule: never let an upload error be silently swallowed. If uploadCoverImage() rejects, the surrounding createArticle() flow MUST reject too โ€” do not insert into PG with a fabricated cover URL, do not show a success toast, and do not retry with a guessed bucket name.

ExecutePGSql / DDL Troubleshooting

HTTP API Fallback

Frontend Guardrails

Avoid dynamic helper traps:

Quick Checks

Reference index

All packaged reference files (required for skill lint reachability):

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.