Communitygithub.com

Neon Postgres

在 TanStack Start 应用中使用 Neon Postgres 数据库。当应用需要存储或查询数据、持久化状态或保存每个用户的数据时触发。关键词包括“数据库”、“Postgres”、“Neon”、“保存数据”、“存储数据”、“持久化”、“表”、“SQL”、“查询”、“迁移”。

Neon Postgres 是什么?

该技能为 TanStack Start 应用提供了开箱即用的双模式数据库集成:在配置了环境变量(如已部署)时使用真正的 Neon Postgres,在未配置时(如沙盒实时预览)自动回退到本地的 PGLite(嵌入式 WASM Postgres),确保预览始终正常渲染。开发者只需使用 `@/lib/db` 导出的 `getSql()` 和 `dbSource`,两种模式共享相同的 API。技能涵盖了数据库的开启配置、环境变量管理(禁止手动创建 .env 文件)、迁移文件管理、权限隔离(用户数据查询必须结合认证中间件)、以及预览与生产环境之间的差异提醒(如 bigint 精度、PGLite 内存特性、Neon 无会话状态等)。此技能仅专注于数据库本身,用户账户和登录功能由独立的 `auth` 技能提供。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/evalix098/tiktoklive/tree/HEAD/.grok/skills/neon

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Neon Postgres 是做什么的?

数据库是可选集成的(AGENTS.md §0.5):仅在应用需要存储超出浏览器会话期限或在设备间共享的数据时使用。否则,不要添加迁移,不要导入 @/lib/db,并使用 localStorage / zustand 保持状态。

此模板提供了一个现成的双模式数据库集成:

  • 已配置(环境变量已设置,例如已部署):真实 Neon Postgres。
  • 未配置(沙盒实时预览):数据库回退到本地 PGLite(嵌入式 WASM Postgres),因此预览始终能渲染。针对 @/lib/db 辅助工具进行开发;两种模式使用相同的 API。

相关包已预安装,无需通过 npm install 安装:pg(node-postgres,常规 Postgres 驱动)和 @electric-sql/pglite(本地数据库回退)。

关于用户账户、登录和读取当前用户,请参见独立的 auth 技能——此技能仅涉及数据库。

开启数据库

在 .grok/app-env.json 中将 deploy.database 设置为 true:

{ "VITE_AUTH_ENABLED": "false", "deploy": { "database": true } }

这将通知平台为已部署的应用配置 Neon;如果保持 false,则部署不会获得 DATABASE_URL,应用将静默运行在可丢弃的 PGLite 上,其数据在重启后丢失。如果存在 migrations/*.sql 或登录功能,则无论此标志如何都会配置数据库;此标志适用于那些查询 @/lib/db 但不包含迁移或登录的应用。它不是 VITE_ 键,也不会传递到浏览器。

环境变量——不要创建 .env 文件

永远不要为数据库编写 .env / .env.local / .env.example 文件。 在沙盒实时预览中,保持 DATABASE_URL 未设置——@/lib/db 会自动使用嵌入式 PGLite。当应用部署后,平台会注入 DATABASE_URL(Neon);您不需要自己配置或编写它。

变量位置用途
DATABASE_URL服务器部署时的 Neon 连接字符串(可选——若未设置则使用 PGLite 回退)

切勿硬编码它;切勿将非 VITE_ 的变量暴露给客户端。

数据库(仅服务器端)

@/lib/db 导出了 getSql() 和 dbSource:当设置了 DATABASE_URL 时,使用常规 Postgres 驱动(node-postgres,pg);当未设置时,使用本地 PGLite 回退。两种方式共享相同的 API——一个标签模板(以及 .query()),返回 rows[]。仅在 createServerFn 处理器或服务器加载器中调用,绝不要在客户端组件中调用。在 migrations/ 中定义模式,不要内联。

import { createServerFn } from "@tanstack/react-start";
import { getSql } from "@/lib/db";

export const listPosts = createServerFn({ method: "GET" }).handler(async () => {
  const sql = await getSql();
  // 指定行的类型——服务器函数的返回值必须是可证明可序列化的。
  return sql<{ id: number; title: string }>`select id, title from posts order by id desc`;
  // 或者:return sql.query<{ id: number; title: string }>("select id, title from posts where id = $1", [id]);
});

每个用户的数据(仅在应用拥有登录功能后使用)。 常规驱动具有完全数据库访问权限,因此请在服务器端将每个查询限定为已认证的用户——永远不要信任客户端发送的 ID。使用预置的 authMiddleware 来获取已验证的 context.userId,然后基于它进行过滤。完整模式(中间件、从客户端代码调用、失败即关闭语义)在 auth 技能中:

import { authMiddleware } from "@/lib/auth/middleware";

export const listTodos = createServerFn({ method: "GET" })
  .middleware([authMiddleware])
  .handler(async ({ context }) => {
    const sql = await getSql();
    return sql<{ id: number; title: string }>`select id, title from todos where user_id = ${context.userId} order by id desc`;
  });
// 写入操作也必须限定作用域:`... where id = ${id} and user_id = ${context.userId}`

在没有登录功能的情况下(默认情况),不要使用 authMiddleware / requireUserId。 它们回退到的开发者用户仅是一个预览用的便利。已部署应用的 VITE_AUTH_ENABLED 由平台设置,而非此工作区设置(目前部署器始终将其设为 "true"),因此一旦部署,两者都会拒绝所有访客——而一个未启用认证的应用也没有为其提供登录路由。仅使用数据库的应用应保持其数据无归属:没有 user_id 列,或使用一个常量值。作为开启登录功能(auth 技能中的升级步骤)的一部分,请添加中间件,并在此过程中重新限定或删除这些行。

在无归属模式下,行通过您的公共服务器函数是全局可读和全局可写的:绝不要在此模式下持久化个人或敏感数据(姓名、电子邮件、关于个人的自由文本),并避免具有破坏性的批量写入操作(全部删除、全部覆盖)——如果应用需要这些操作,请建议开启登录功能。

迁移

migrations/*.sql 是唯一的模式来源。它们会应用于部署时的 Neon(npm run build 会针对 DATABASE_URL 运行 db:migrate,因此 Vercel 部署时模式已就绪)以及启动时自动应用于 PGLite 预览,因此开发环境与生产环境保持一致。

两个应用器都不会进入子目录,因此位于 migrations/auth/0001_auth.sql 的 Better Auth 模式不会被应用,除非应用开启登录功能并将其复制到上层(不要编辑它——参见 auth 技能)。将您的应用的模式放在从 0002 开始的新序号文件中:

-- migrations/0002_schema.sql —— 示例用于待办事项应用;请使用您的应用的表
create table if not exists todos (
  id         serial primary key,
  user_id    text not null,
  title      text not null,
  done       boolean not null default false,
  created_at timestamptz not null default now()
);
create index if not exists todos_user_id_idx on todos (user_id);

永远不要编辑已应用的文件——它通过名称在 _migrations 表中跟踪,不会重新运行(而是添加一个新文件;新文件会在下一次请求时应用于正在运行的预览)。优先使用幂等语句(... if not exists)。包含每个用户数据的表应具有 user_id text not null 列(TEXT 类型,而非 UUID——预览开发用户 ID 是字符串 'dev-user')。

预览 ↔ 生产一致性

getSql() 会规范化结果类型,以使两个后端返回一致的、JSON 安全的形状:bigint/count(*) → number,date → 'YYYY-MM-DD' 字符串,interval → 文本,numeric → 字符串。需要尊重的其他差异:

  • 超过 2^53 的 bigint 作为数字会丢失精度——如果您需要极大的整数,请将其转换为 ::text(行计数没问题)。
  • 预览数据库在内存中运行:在开发服务器重启时清除,单连接(无锁争用或并发写入冲突),并且不加载任何扩展——不要使用 create extension;坚持使用核心 Postgres。
  • Neon 的池化端点不保留会话状态——不要依赖 SET、LISTEN/NOTIFY 或会话级咨询锁。
  • 保持 user_id 列为 text 类型——预览使用 'dev-user',生产环境使用 Better Auth 的文本 ID;uuid 列会破坏预览的插入操作。
  • 部署的 Neon 查询会经过网络(并且可能会冷启动恢复)——避免那些在进程内预览数据库中感觉轻松但会带来 N+1 查询性能问题的模式。

Individual skills in this repo

This repo contains 17 individual skills — each has its own dedicated page.

evalix098/tiktoklive

Add user accounts and sign-in to this TanStack Start app. Use when the app needs authentication, sign-in, user accounts, protected routes, or per-user data. Triggers on "auth", "login", "log in", "sign in", "sign up", "account", "users", "authentication", "protected", "who is logged in", "current user", "per-user".

evalix098/tiktoklive

Build browser games and interactive/canvas/3D experiences in this TanStack Start + React app. Use for any game, simulation, or WebGL/Canvas experience — 2D or 3D, single-player. Covers the game loop & timing, 3D orientation/camera conventions, collision, performance, assets, audio, save, game feel, and per-genre playbooks. For WASD / vehicle / flight **input signs and inverted A/D**, open the **`controls`** skill — do not rely on this file or racing-kart alone. Triggers on "game", "minecraft", "fps", "platformer", "racing", "tetris", "snake", "shooter", "3d", "three.js", "canvas", "voxel", "physics".

evalix098/tiktoklive

Player-facing input signs for browser games: WASD, vehicles, flight, FPS mouse-look, and the #1 failure mode (inverted A/D). Mandatory control self-tests and a tiny test interface so you can verify A turns left before shipping. Load for ANY game with movement, steering, flying, driving, tanks, boats, mechs, drones, planes, karts, third-person follow cams — not only racing. Triggers on "controls", "WASD", "inverted", "steer", "flight", "airplane", "kart", "vehicle", "yaw", "roll", "pitch", "mouse look", "A/D".

evalix098/tiktoklive

Design and build polished, non-generic UI for this TanStack Start + React + Tailwind v4 + shadcn/Radix app. Use whenever you create or restyle any interface surface — pages, landing pages, dashboards, forms, modals, nav, and game overlays (start screens, HUD, menus). Covers design tokens, layout, typography, color, spacing, motion, and the anti-"AI-slop" rules that keep output from looking generic. Triggers on "design", "UI", "make it look good", "polish", "landing page", "theme", "style", "redesign", "ugly", "clean up".

evalix098/tiktoklive

Deep guide for game ANIMATION assets: motion cycles, action keyframes, effect sequences, and animation sprite sheets — built around a video-first pipeline. In this app-builder sandbox, execute via the video2dsprite / generate2dsprite skills (magenta + scripts), not ad-hoc ffmpeg. Use whenever generating anything that moves: walk/run cycles, attacks, idles, FX, flags, fire, animation sheets. Complements game-asset-core.

evalix098/tiktoklive

Core discipline for ANY game-asset generation with Imagine tools: the engine-ready defaults users don't state, spec checklists, style anchoring, read-back verification, honest defect flagging. Use whenever generating any game art (sprites, sheets, animations, tiles, UI, FX) — then ALSO load the matching specialist skill: game-animation-frames for anything that moves, game-tilesets for tiles/terrain, game-character-consistency for recurring characters, game-ui-icons for UI and icons.

evalix098/tiktoklive

Deep guide for CHARACTER IDENTITY across images: turnarounds (front/side/ back), state and damage variants, palette swaps, equipment changes, and same-character-in-context sets. Use whenever generating character turnarounds, character sheets, variants of an existing sprite, or any same-subject multi-image set. Complements game-asset-core.

evalix098/tiktoklive

Deep guide for game TILE assets: seamless tileable textures, terrain transition tilesets, autotiles, and ground/platform tiles. Use whenever generating tileable textures, tilesets, terrain transitions, or seamless patterns. Complements game-asset-core.

evalix098/tiktoklive

Deep guide for game UI assets: buttons with interaction states, panels, bars, wordmark logos, and icon sets. Use whenever generating game UI elements, HUD assets, inventory icons, icon sets, buttons, or title logos. Complements game-asset-core.

evalix098/tiktoklive

Generate production-oriented 2D game maps with `imagine_text_to_image`: RPG/top-down maps, side-scroller parallax stages, tilemaps, layered raster maps, prop packs, collision zones, and walkable areas. Use when building browser games that need real map art (not pure code-drawn tiles), layered props, or map collision metadata. Triggers on "map", "level", "stage", "tilemap", "overworld", "dungeon", "side scroller background", "prop pack", "2D map".

evalix098/tiktoklive

Generate and postprocess 2D game sprites and animation sheets: pixel-art characters, NPCs, creatures, spells, projectiles, impacts, props, summons, and transparent PNG/GIF exports. Use when building browser games that need real sprite sheets (not code-drawn placeholders), matching a map art style, or producing magenta-background sheets for chroma-key cleanup. Triggers on "sprite", "sprite sheet", "animation sheet", "pixel art character", "walk cycle", "attack animation", "projectile sprite", "2D game asset".

evalix098/tiktoklive

How to use the Imagine tools in Grok Build: imagine_text_to_image, imagine_image_to_image, imagine_reference_to_image, imagine_text_to_video, imagine_image_to_video, imagine_reference_to_video, and render_file for chat previews. When to build a visual with code instead of generating it, prompt-craft, reference-first handling of real people, factual grounding, and asset-consistency. Load this whenever generating or editing an image or video is on the table. Tool-usage-driven, not triggered by a user merely mentioning images.

evalix098/tiktoklive

Peer-to-peer realtime multiplayer over WebRTC data channels: every user of the deployed app connects directly to every other user (full mesh), the server only brokers the handshake at /api/rtc. Lowest possible latency, zero per-message server cost. Use for 2-8 player co-op/casual realtime: shared cursors, drawing, party games, casual action. Triggers: p2p, peer to peer, webrtc, low latency multiplayer, direct connection.

evalix098/tiktoklive

Share-link previews and app identity for apps on *.grok.me: the injector-owned og:image card, the SVG favicon, and PWA icons for installable apps. Use when scaffolding, renaming, or restyling the app — and for share / unfurl / OG / Twitter card questions. A custom 1200×630 card from the app's own art is the default — games of every kind (DOM board/word games included), whimsical apps, creative tools, and brand-forward pages; only plain utilities keep the placeholder. Always run the brand-asset pass as a `task` subagent and never wait for it. Triggers on "share", "rename", "app name", "OG", "Open Graph", "twitter card", "unfurl", "og:image", "og:type", "x:game:image", "x-banner", "link preview", "social card", "thumbnail", "preview image", "favicon", "app icon", "PWA", "manifest", "installable", "home screen", "SEO", "meta description".

evalix098/tiktoklive

Official Three.js API and TSL (Three.js Shading Language) reference for LLM code generation. Load when writing or debugging three.js / WebGL / WebGPU / custom materials / shaders / GLTF / advanced three APIs beyond basic game loop/controls. Prefer building-games for game correctness (loop, WASD, camera, orientation); use this skill for full API/TSL depth. Triggers on "three.js", "threejs", "WebGPU", "TSL", "NodeMaterial", "shader", "GLTF", "MeshStandard", "OrbitControls", "WebGLRenderer".

evalix098/tiktoklive

Grok Build only. Turn a 2D character still into denser animation sprites via imagine_text_to_image base → imagine_image_to_video (6s/10s run-in-place) → ffmpeg frames → magenta chroma-key → dense sampled strips/grids/GIFs. Use when the user wants video-to-sprite, smoother run/walk cycles, or denser intermediate poses. Prefer generate2dsprite for crisp production pixel sheets. Triggers on "video to sprite", "imagine_image_to_video sprite", "dense walk cycle", "smooth run animation from video".

evalix098/tiktoklive

Call the xAI API (Grok) from this app's server code using the injected XAI_API_KEY: chat/LLM features, image and video generation (Imagine), and voice (text-to-speech). Use when the app needs any "AI" / "assistant" / "chatbot" / "Grok" functionality, runtime image/video generation, or speech. Triggers on "AI", "LLM", "chatbot", "assistant", "Grok", "xAI", "generate text", "summarize", "generate image", "AI video", "voice", "text to speech", "TTS", "OpenAI" (use xAI instead).

相关技能