Agent skill

Postgresql Development Cloudbase

by TencentCloudBase in TencentCloudBase/CloudBase-AI-Toolkit

A skill your agent uses when building, debugging, or evaluating CloudBase PostgreSQL / CloudBase PG / PG mode apps, including Postgres schema setup, queryPgDatabase/managePgDatabase, JS SDK v3…

MITAuto-check passedDatabases

Install Postgresql Development Cloudbase

skills CLI
$ npx skills add TencentCloudBase/CloudBase-AI-Toolkit --skill postgresql-development-cloudbase -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install TencentCloudBase/CloudBase-AI-Toolkit postgresql-development-cloudbase --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/TencentCloudBase/CloudBase-AI-Toolkit.git skills-src && mkdir -p .claude/skills && cp -r skills-src/config/source/skills/postgresql-development-cloudbase .claude/skills/postgresql-development-cloudbase && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
postgresql-development-cloudbase
GitHub stars
1.1k
Used in
2 other repos
Token cost
~8.3k tokens
SKILL.md length
3,664 words
Files
10 (incl. references)
Skills in repo
49
Repo updated
First seen
Licence
MIT

At a glance

A skill your agent uses when building, debugging, or evaluating CloudBase PostgreSQL / CloudBase PG / PG mode apps, including Postgres schema setup, queryPgDatabase/managePgDatabase, JS SDK v3…

  • Works in 12 steps: Inspect the existing app surfaces first:… → Check PG state through MCP: use… → Understand PG roles before writing code:… → …
  • Evaluating CloudBase PostgreSQL / CloudBase PG / PG mode apps
  • SKILL.md covers Sibling skills (local only), Activation Contract, Required Flow and Exploration Budget, plus 7 more sections
  • Needs VITE_PUBLISHABLE_KEY

What it does

Postgresql Development Cloudbase is an agent skill from TencentCloudBase/CloudBase-AI-Toolkit. 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 CloudBase PG.

Its SKILL.md is about 8.3k tokens, which your agent loads only when the skill is triggered. The skill folder holds 10 other files, including reference files (for example `references/app-workflow.md`, `references/auth-and-rls.md` and `references/http-api.md`).

It sits in Databases, covering REST APIs and NoSQL databases. It works with PostgreSQL. The repository describes itself as: Backend for AI coding agents on CloudBase — database, auth, functions via Plugin, Skills & MCP. The licence is MIT.

When your agent uses it

  • Evaluating CloudBase PostgreSQL / CloudBase PG / PG mode apps
  • Including Postgres schema setup
  • QueryPgDatabase/managePgDatabase
  • JS SDK v3 app.rdb() CRUD/RPC

Example prompts

  • “/postgresql-development-cloudbase”

Workflow steps

12 steps, taken from the first numbered list in SKILL.md.

  1. Inspect the existing app surfaces first: src/lib/backend.*, src/lib/auth.*, src/lib/*service.*, route guards, and the handlers bound to…
  2. Check PG state through MCP: use queryPgDatabase for schema/read-only inspection and managePgDatabase for DDL/DML. Do not switch to MySQL…
  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…
  4. Use schema management (managePgDatabase) before writing CRUD code. Schema DDL (CREATE / ALTER / DROP / TRUNCATE) must go through the…
  5. Check username-password auth before coding login
  6. Implement Web auth state with auth.getSession() before writing CRUD
  7. Implement browser-side business data with the CloudBase JS SDK v3 PostgreSQL API first: app.rdb().from(table). Use the latest…
  8. Do not manually fetch a CloudBase Auth bearer token from browser code for PG CRUD. In particular, do not call non-canonical helpers such…
  9. Use the official CloudBase PG SQL auth helpers in policies: auth.uid() for JWT sub, auth.role() for anon / authenticated / service_role…
  10. 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…
  11. Keep cover images in CloudBase Storage. Store only the final file URL or file metadata in PG.
  12. Verify both layers before claiming done: project build/typecheck and browser E2E for login/CRUD, then read back rows with queryPgDatabase…

What it can do on your machine

Read from SKILL.md and the folder at commit ea2c202. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript and sql).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • docs.cloudbase.net
    • console.cloud.tencent.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • VITE_PUBLISHABLE_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Postgresql Development Cloudbase loads about 8.3k tokens when it runs, and up to ~24k if it reads all its reference files. Until then it costs about 87 tokens; SKILL.md has 3,664 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~87
When it runs · the whole SKILL.md, loaded when a task matches
~8.3k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~24k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from TencentCloudBase/CloudBase-AI-Toolkit at commit ea2c202, republished under its MIT licence (© TencentCloudBase). 3,664 words, ~8,258 tokens.

Download SKILL.mdSave it as .claude/skills/postgresql-development-cloudbase/SKILL.md (or your agent's skills folder). This skill also uses 9 other files; get the full folder from GitHub.
name
postgresql-development-cloudbase
description
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 CloudBase PG.
version
2.34.8
alwaysApply
false

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
  • The task says CloudBase PG, PostgreSQL, Postgres, PG mode, RLS, JS SDK v3 PostgreSQL, app.rdb(), queryPgDatabase, or managePgDatabase.
  • A Web app or CMS must persist business data in CloudBase PostgreSQL instead of NoSQL or MySQL.
Then also read
  • Access-pattern design or slow-query work -> ../postgresql-best-practices-cloudbase/SKILL.md
  • Web auth provider readiness -> ../auth-tool-cloudbase/SKILL.md
  • Web login implementation -> ../auth-web-cloudbase/SKILL.md
  • General Web implementation and verification -> ../web-development/SKILL.md
  • Browser storage upload -> ../cloud-storage-web/SKILL.md
  • Raw HTTP API details only when SDK coverage is blocked -> ../http-api-cloudbase/SKILL.md
  • PG reference index -> references/index.md
  • PG mode overview -> references/pg-mode-overview.md
  • Auth / GRANT / RLS details -> references/auth-and-rls.md
  • End-to-end PG app closure -> references/app-workflow.md
  • PG storage details — MUST read before writing any bucket / upload / URL code -> references/storage-pg.md
  • HTTP API fallback -> references/http-api.md
  • Troubleshooting -> references/troubleshooting.md
Do NOT use first
  • relational-database-mcp-cloudbase / queryMysqlDatabase / manageMysqlDatabase: those are MySQL-oriented.
  • cloudbase-document-database-web-sdk / collection APIs for business data that must live in CloudBase PG.

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.

  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).
    • PG mode is a new-environment mode selected when creating a CloudBase environment with PostgreSQL. Do not try to "upgrade" a legacy environment in place; create/select a PG-mode environment instead.
    • If RuntimeBackends.postgresql === false, STOP — this is a legacy NoSQL-only env: switch to cloudbase-document-database-web-sdk for browser data and cloud-storage-web (with app.uploadFile()) for uploads. Do not write app.rdb() code, do not enable RLS, do not create a pgstore bucket here.
    • If both postgresql and nosql are true (the common case in a PG environment), they coexist. Apply this skill to NEW business data the task asks you to put in PG (e.g. articles / role tables explicitly described as PG). Existing NoSQL collections, the bucket reported in EnvInfo.Storages[], and any managePermissions(resourceType="noSqlDatabase") rules continue to govern the legacy NoSQL data — do NOT migrate or rewrite them unless the task explicitly asks.
    • RuntimeBackends.mysql === false is the only hard "do not use" signal: when MySQL is absent, do not use manageMysqlDatabase / queryMysqlDatabase and do not consult the relational-database-mcp-cloudbase skill; those are MySQL-specific and have nothing to do with CloudBase PG.
    • Note: in a PG env, EnvInfo.Storages[] is the legacy NoSQL bucket. It still works for legacy app.uploadFile() flows but is NOT a usable pgstore bucket — never reuse it as the <bucket> segment in app.storage.from('<bucket>').upload('<key>', file).

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. Do not switch to MySQL tools. 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:

    • managePgDatabase(action=migrationDetail, migrationVersion=...) — inspect a single migration
    • managePgDatabase(action=fetchMigration) — pull remote history SQL into cloudbase/migrations/ (CLI tcb db pg migration fetch parity). Optional migrationVersion for one file; omit for full history. Existing local files are skipped unless force=true (overwrite / checksum realign). Prefer this over hand-copying SQL from migrationDetail to avoid checksum drift.
    • managePgDatabase(action=repairMigration, migrationVersion=..., migrationName=..., repairStatus=..., repairReason=...) — repair history records

    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:

    • ALTER TABLE to add/rename/drop columns (via applyMigration with a new version), or
    • DROP TABLE IF EXISTS ... CASCADE and recreate via applyMigration (only when data loss is acceptable, e.g. disposable/evaluation environments).
    • Do NOT rely on CREATE TABLE IF NOT EXISTS silent skip — it will cause all downstream CRUD queries to fail with wrong field names.
    • After DDL, re-query the schema and compare every column name used by frontend code, insert/update payloads, filters, ordering, and RLS policies.
  5. Check username-password auth before coding login:

    • Call queryAppAuth(action="getLoginConfig").
    • If loginMethods.usernamePassword !== true, call manageAppAuth(action="patchLoginStrategy", patch={ usernamePassword: true }).
    • In Web login code, use auth.signInWithPassword({ username, password }) for plain usernames like admin or editor.
    • Do not assume auth.signUp({ username, password }) can directly create username/password users. Confirm queryAppAuth sdkHints and the installed @cloudbase/js-sdk behavior first; if direct username signup is unsupported, implement registration through a backend/management boundary instead of exposing secret keys in the browser.
  6. Implement Web auth state with auth.getSession() before writing CRUD:

    • Route guards must check data.session, not auth.getUser() and not deprecated getLoginState().
    • Treat login as successful only when signInWithPassword(...) returns no error and includes data.session.
    • Get the UID for author_id / role rows from data.session.user.id (fall back to sub/uid only after inspecting the actual session object).
    • Do not use auth.getUser() as proof of login; it can return a non-null wrapper or anonymous-looking user data when there is no real username/password session.
  7. 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).

  8. 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.

  9. 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:

    • Log in through the real app path.
    • Insert a test row using author_id = session.user.id.
    • Read it back with queryPgDatabase.
    • If INSERT/SELECT fails, inspect the exact RLS error and fix the policy or switch to a server/RPC boundary. Do not leave browser-facing tables with broken RLS.
    • ⚠️ auth.uid() returns text, not uuid. Prefer owner columns as varchar(64) / text. If comparing to a uuid column, use auth.uid()::uuid (only when JWT sub is a valid UUID) or you will get operator does not exist: uuid = text. This differs from Supabase. See references/auth-and-rls.md.
    • ⚠️ Do NOT use current_user or current_setting(...) in RLS policies. current_user in PostgreSQL returns the database role name (e.g. authenticated), NOT the CloudBase auth user ID. Always use auth.uid() for user identity checks. If you are unsure whether the auth helpers are available, run SELECT proname FROM pg_proc WHERE pronamespace = 'auth'::regnamespace to list all available auth.* functions.
  10. 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>.

  11. Keep cover images in CloudBase Storage. Store only the final file URL or file metadata in PG.

  12. 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

  • Optimize for a working user flow before broad research.
  • If the task is a Web app with PG-backed CRUD, read references/app-workflow.md and follow that closure path before looking up optional HTTP API details.
  • Do not query the same documentation family more than twice for the same question. If the second lookup does not unblock you, inspect the installed SDK surface or the exact runtime error instead.
  • Once you choose app.rdb() for browser CRUD, stop researching raw PG HTTP APIs unless app.rdb() is missing or demonstrably fails.
  • After a DDL failure, retry SQL at most twice. Then call queryPgDatabase(action="objects") to find the schema-qualified table name, then queryPgDatabase(action="schema", objectName="public.your_table"), read the exact error, and simplify the schema or permission plan.
  • Avoid long task-management loops for targeted repairs. Read the active files, execute the minimum platform setup, edit code, and verify.
  • File read budget: Do NOT read the same file more than 2 times. If you need to re-read a file after 2 reads, use Grep for targeted search or Read with explicit offset/limit to target specific line ranges. Move on to editing or verifying instead of re-reading.
Show full SKILL.md (1,591 more words)Show less

Data Model Rules

  • Use CloudBase Auth / CloudBase PG built-in auth identity as the user source. Do not copy an extra identity table unless the app needs one.

  • Keep business roles in PG when the app needs admin/editor behavior, e.g. user_roles with uid, username, and role. The uid value must be the same value the Web session uses as session.user.id, and must match any database policy expression you use.

  • Keep content tables in PG, e.g. articles or posts with owner UID columns.

  • Prefer snake_case physical columns (author_id, author_name, cover_image, created_at, updated_at) for PG tables. If UI fields are camelCase, map them explicitly at the service boundary.

  • Treat the schema returned by queryPgDatabase(action="schema", objectName="public.your_table") as the source of truth. objectName is required and must be schema-qualified; if you do not know it yet, call queryPgDatabase(action="objects") first. If an existing table has authorid/updatedat, either use those exact column names in code or explicitly migrate/drop-recreate the table before writing code that expects author_id/updated_at.

  • CREATE TABLE IF NOT EXISTS does not change an existing incompatible schema. In evaluation or disposable environments, prefer a deliberate DROP TABLE IF EXISTS ... CASCADE followed by CREATE TABLE ... when you need a known schema.

  • After DDL, query the table schema again and compare every column used by frontend code, insert/update payloads, filters, ordering, and RLS policies.

  • Backend permission must exist in the database or server/RPC layer. Hiding buttons in the UI is not enough.

  • Do not leave a browser-facing table with RLS enabled and zero policies. PostgreSQL denies user reads/writes by default in that state, so app.rdb().from("articles").insert(...) can fail while the UI only shows a generic save failure. If you enable RLS, create and verify SELECT/INSERT/UPDATE/DELETE policies before testing the app.

  • Use CloudBase PG's official SQL auth helpers in policies: auth.uid() (JWT sub, returns text not uuid), auth.role() (anon / authenticated / service_role), auth.jwt() (full claims), and auth.email() when relevant. Prefer owner columns such as owner_id varchar(64) DEFAULT auth.uid() so the database, not the browser, assigns ownership. If an owner column is already uuid, compare with auth.uid()::uuid (only when sub is a valid UUID).

  • Standard owner-table template — copy this shape for any user-owned business table:

    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()
    );
    • owner_id is TEXT, not uuid — auth.uid() returns text (e.g. EchhGXFadSANiCSaVim2wQ); declaring it uuid fails at table-create time with a type mismatch.
    • owner_id carries DEFAULT auth.uid() — ownership is decided server-side. App code must not send it; the INSERT policy rejects any forged owner value.
  • Seeding demo data: RLS denies anonymous browser writes. Insert demo/seed rows through the management plane — managePgDatabase(action="execute", confirm=true) with an explicit owner_id value (e.g. 'system-demo'); do not rely on DEFAULT auth.uid() for seed rows, and never ship seed INSERTs in frontend code.

  • If you need detailed GRANT/RLS rules, read references/rls-patterns.md before writing policies.

  • For admin/editor flows, make admin able to operate all rows and editor only rows where owner UID matches the current user.

JS SDK v3 PostgreSQL Patterns

Table name rules (important):

  • ✅ db.from("articles") — recommended
  • ✅ db.from("public.articles") — also valid (single schema prefix)
  • ❌ db.from("public.public.articles") — WRONG, double schema prefix, will fail with PGRST205
  • objectName="public.articles" in queryPgDatabase() is the MCP tool format — do NOT copy this into db.from().

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

ts
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():

ts
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):

ts
// 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-pg API — copy these, do not re-derive from .d.ts). Source: webv3-pg/postgresql/fetch.md — fetch / insert / update / delete / upsert / filters / modifiers / rpc share the same path prefix, one page per verb(URL 加 .md 可取 raw markdown 原文):

ts
// 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:

ts
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-infoMeaningFix
STORAGE_BUCKET_NOT_FOUNDThe bucket in the path does not exist in this PG environment.Create the bucket via management surface, then retry.
STORAGE_PERMISSION_DENIEDThe 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/keyThe 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_REQUIREDYour 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

  • ExecutePGSql / managePgDatabase(action="execute") is an admin/control-plane path. Do not expose Tencent Cloud SecretKey or CloudBase API Key in frontend code.
  • Execute one SQL statement per call. Split batches explicitly instead of sending semicolon-joined multi-statements.
  • Some DDL (CREATE / ALTER / DROP / GRANT / REVOKE / TRUNCATE / COMMENT) can fail directly with transient InternalError. If that happens, retry once by wrapping the DDL in DO $$ BEGIN EXECUTE '...'; END $$ and escaping single quotes inside the string.
  • When validating permissions, use the user-facing role (anon or authenticated) when the tool/API supports a role parameter. Default admin execution can hide missing GRANT/RLS policies.

HTTP API Fallback

  • PG HTTP API is in the CloudBase relational database HTTP API family, together with MySQL. In MCP docs/search this appears under mysqldb.
  • Before writing raw fetch() code, query OpenAPI docs: searchKnowledgeBase(mode="openapi", apiName="mysqldb", query="PostgreSQL fetch insert update rpc").
  • Do not construct /api/v1/rdb/rest or /api/v1/rdb/rest/rpc from memory. A guessed path that returns 404 is a hard blocker; switch back to JS SDK v3 or read the OpenAPI contract.
  • If environment variables expose TCB_HTTP_API_BASE_URL / VITE_TCB_HTTP_API_BASE_URL, treat them as the base only. The path, method, headers, and auth model must still come from OpenAPI docs or an existing working helper.

Frontend Guardrails

Avoid dynamic helper traps:

  • Do not write function getAuth() { return (await import("./backend")).auth; }; either use a top-level static import or make the function async.
  • Do not write typeof import !== "undefined" in Vite; use import.meta.env directly.
  • Do not keep editing after Vite reports a transform error. Fix syntax first, rerun build, then test the browser flow.
  • Do not spend time reverse-engineering unrelated SDK internals when a documented v3 surface exists. Use the documented app.rdb() / app.storage.from() APIs first.

Quick Checks

  • PG schema exists and matches the service code.
  • Username login is enabled and code uses username APIs, not email APIs.
  • Data writes reach CloudBase PG via JS SDK v3 app.rdb() or a documented HTTP API path, not local state, mock arrays, or guessed 404 endpoints.
  • Browser PG code must not depend on user.getIdToken() or invented token helpers. If raw HTTP is unavoidable, first inspect the installed CloudBase Web SDK/auth API and prove the request succeeds with the current user session.
  • Editor permission is enforced outside the UI.
  • A pgstore bucket that matches the upload path (e.g. covers) exists BEFORE any browser upload runs. If it does not, create it via a management surface; the v3 SDK will not create one for you.
  • Storage upload returns a usable URL and that URL is persisted with the article. Upload errors must propagate — do not insert an article row with a placeholder cover URL.

Reference index

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

© TencentCloudBase, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 9 other files (references) in config/source/skills/postgresql-development-cloudbase of TencentCloudBase/CloudBase-AI-Toolkit.

  • SKILL.md
  • references/app-workflow.md
  • references/auth-and-rls.md
  • references/http-api.md
  • references/index.md
  • references/pg-mode-overview.md
  • references/realtime.md
  • references/rls-patterns.md
  • references/storage-pg.md
  • references/troubleshooting.md

Open the folder on GitHubat commit ea2c202

Used in 2 other repositories

We found 5 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 2 other GitHub owners. This page covers the copy in TencentCloudBase/CloudBase-AI-Toolkit, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Postgresql Development Cloudbase next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Postgresql Development Cloudbase compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Postgresql Development Cloudbase this skillTencentCloudBase/CloudBase-AI-Toolkit1.1k2 repos~8.3kAutomated safety check: PassMIT
Database Design Patternscuriositech/some_claude_skills243—~3.1kAutomated safety check: PassMIT
Databaseaiskillstore/marketplace4303 repos~1.2kAutomated safety check: PassNone
Prisma Database Setupcurvenote/curvenote1693 repos~1.4kAutomated safety check: PassMIT
Rhctlsaidake/rhctl106—~4kAutomated safety check: NotesApache-2.0
Actions And Pg Migrationzkldi/Tachi237—~2.3kAutomated safety check: PassNone

Similar skills

  • Database Design Patterns

    curiositech/some_claude_skills

    Schema design, normalization decisions, indexing strategies, and migration safety for relational databases.

    243 GitHub stars~3.1k tokensUpdated 1 mo ago
    DatabasesAuto-check passed
  • Database

    aiskillstore/marketplace

    Database development and operations workflow covering SQL, NoSQL, database design, migrations, optimization, and data engineering.

    430 GitHub starsUsed in 3 repos~1.2k tokens
    DatabasesAuto-check passed
  • Prisma Database Setup

    curvenote/curvenote

    Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.).

    169 GitHub starsUsed in 3 repos~1.4k tokens
    DatabasesAuto-check passed
  • Rhctl

    saidake/rhctl

    Run and author rhctl CLI workflows and remote environment scripts under scripts/ (PostgreSQL, JetStream, Docker, Redis, MongoDB, AWS LocalStack, execute/upload/patch).

    106 GitHub stars~4k tokensUpdated yesterday
    DatabasesAuto-check: notes
  • Patterns for writing actions (MakeAction/MakeAnonAction), using the Postgres DB (Kysely), and migrating Express routes from MongoDB to Postgres in the Tachi server.

    237 GitHub stars~2.3k tokensUpdated 2 days ago
    DatabasesAuto-check passed
  • Npgsqlrest

    NpgsqlRest/NpgsqlRest

    Build and modify REST APIs with NpgsqlRest — exposing PostgreSQL as HTTP endpoints from two sources (database functions/procedures/tables/views, and plain .sql files), driven by SQL comment…

    132 GitHub stars~7k tokensUpdated 4 days ago
    DatabasesAuto-check: notes

More from TencentCloudBase/CloudBase-AI-Toolkit

All 49 skills in this repo
  • AI Model Nodejs

    TencentCloudBase/CloudBase-AI-Toolkit

    A skill your agent uses for Node.js backend AI via @cloudbase/node-sdk (=3.16.0) — cloud functions, CloudRun, Express/Koa/NestJS, serverless APIs, scheduled jobs, LLM proxies, agent orchestration.

    1.1k GitHub starsUsed in 3 repos~5k tokens
    Auto-check passed
  • HTTP API Cloudbase

    TencentCloudBase/CloudBase-AI-Toolkit

    CloudBase official HTTP API client guide. An agent skill from TencentCloudBase/CloudBase-AI-Toolkit.

    1.1k GitHub starsUsed in 3 repos~2.1k tokens
    Auto-check passed
  • Cloud API Recipe Authoring

    TencentCloudBase/CloudBase-AI-Toolkit

    Author or revise a cloud-api-operations recipe (config/source/skills/cloud-api-operations/references/recipes/).

    1.1k GitHub stars~3.7k tokensUpdated yesterday
    Auto-check passed
  • Manage Local Skills

    TencentCloudBase/CloudBase-AI-Toolkit

    Analyze, standardize, validate, and sync locally maintained skills into agent skill directories with a skills CLI-aligned workflow.

    1.1k GitHub stars~1.2k tokensUpdated yesterday
    Auto-check passed
  • Cloudbase Agent Python

    TencentCloudBase/CloudBase-AI-Toolkit

    Build production-ready AI agent backends using the CloudBase Agent Python SDK — create agents with LangGraph/CrewAI/LlamaIndex, serve them via FastAPI with AG-UI protocol streaming +…

    1.1k GitHub starsUsed in 2 repos~2.9k tokens
    Auto-check: notes
  • Cloudbase

    TencentCloudBase/CloudBase-AI-Toolkit

    A skill your agent uses when you develop, design, build, deploy, debug, migrate, or troubleshoot CloudBase (腾讯云开发, 云开发, TCB, 微信云开发) projects — Web, 微信小程序, 小程序, uni-app, mobile (iOS, Android…

    1.1k GitHub starsUsed in 1 repo~4.7k tokens
    Auto-check passed

Works with

Categories

Questions about Postgresql Development Cloudbase

What does Postgresql Development Cloudbase do?

A skill your agent uses when building, debugging, or evaluating CloudBase PostgreSQL / CloudBase PG / PG mode apps, including Postgres schema setup, queryPgDatabase/managePgDatabase, JS SDK v3…. Postgresql Development Cloudbase is an agent skill from TencentCloudBase/CloudBase-AI-Toolkit.rdb() CRUD/RPC, PG HTTP API fallback, RLS-style permissions, username-password auth, and Web CMS/admin CRUD flows backed by CloudBase PG.

When should I use Postgresql Development Cloudbase?

Postgresql Development Cloudbase fits situations like: evaluating CloudBase PostgreSQL / CloudBase PG / PG mode apps; including Postgres schema setup; queryPgDatabase/managePgDatabase; JS SDK v3 app.rdb() CRUD/RPC.

How do I install Postgresql Development Cloudbase in Claude Code?

Run `npx skills add TencentCloudBase/CloudBase-AI-Toolkit --skill postgresql-development-cloudbase -a claude-code`. Or copy the skill folder (config/source/skills/postgresql-development-cloudbase in TencentCloudBase/CloudBase-AI-Toolkit) into .claude/skills/postgresql-development-cloudbase in your project. Claude Code loads it when a task matches its description.

How do I install Postgresql Development Cloudbase in Codex?

Run `npx skills add TencentCloudBase/CloudBase-AI-Toolkit --skill postgresql-development-cloudbase -a codex`. Or copy the skill folder (config/source/skills/postgresql-development-cloudbase in TencentCloudBase/CloudBase-AI-Toolkit) into .agents/skills/postgresql-development-cloudbase in your project. Codex loads it when a task matches its description.

Can I use Postgresql Development Cloudbase in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add TencentCloudBase/CloudBase-AI-Toolkit --skill postgresql-development-cloudbase -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/postgresql-development-cloudbase, .gemini/skills/postgresql-development-cloudbase, .github/skills/postgresql-development-cloudbase and .opencode/skills/postgresql-development-cloudbase in your project.

What does Postgresql Development Cloudbase need to run?

Going by SKILL.md and its folder, Postgresql Development Cloudbase needs credentials named VITE_PUBLISHABLE_KEY.

Does Postgresql Development Cloudbase access the network?

SKILL.md names 2 domains. As links in the text: docs.cloudbase.net and console.cloud.tencent.com. This is read from the text; nothing was executed.

Is Postgresql Development Cloudbase safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Postgresql Development Cloudbase use?

Postgresql Development Cloudbase is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Postgresql Development Cloudbase use?

About 8.3k tokens (SKILL.md is roughly 33k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 15k tokens, read only when the agent opens those files.

What are the alternatives to Postgresql Development Cloudbase?

Skills that share tags, products or a category with Postgresql Development Cloudbase: Database Design Patterns (curiositech/some_claude_skills, 243 stars), Database (aiskillstore/marketplace, 430 stars), Prisma Database Setup (curvenote/curvenote, 169 stars) and Rhctl (saidake/rhctl, 106 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Postgresql Development Cloudbase?

TencentCloudBase (a GitHub organization) maintains it in TencentCloudBase/CloudBase-AI-Toolkit, which has 1,132 GitHub stars. The repository holds 49 skills in this directory. The repository was last updated on October 6, 2026.

Source: TencentCloudBase/CloudBase-AI-Toolkit on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.