### Server Startup Output Source: https://github.com/zhenruyan/postgrebase/blob/master/README_zh.md Example of the console output after starting the server. ```text PostgreBase — AI原生的无代码API开发工具 ├─ REST API: http://127.0.0.1:8090/api/ ├─ MCP SSE: http://127.0.0.1:8090/api/mcp/sse └─ Admin UI: http://127.0.0.1:8090/_/ ``` -------------------------------- ### Install dbx package Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Use the go get command to add the dbx package to your Go project. ```bash go get github.com/pocketbase/dbx ``` -------------------------------- ### Server Startup Endpoints Source: https://github.com/zhenruyan/postgrebase/blob/master/README.md Example output displayed by the server upon successful startup. ```text ├─ REST API: http://127.0.0.1:8090/api/ ├─ MCP SSE: http://127.0.0.1:8090/api/mcp/sse └─ Admin UI: http://127.0.0.1:8090/_/ ``` -------------------------------- ### Development Commands Source: https://github.com/zhenruyan/postgrebase/blob/master/js-sdk/README.md Standard commands for installing dependencies, building, and testing the SDK. ```bash # Install dependencies npm install # Build npm run build # Run tests npm test # Development mode (watch) npm run dev ``` -------------------------------- ### Working with DateTime Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/development.md Usage examples for the types.DateTime wrapper. ```go now := types.NowDateTime() t := now.Time() // returns time.Time zero := types.DateTime{} zero.IsZero() // true ``` -------------------------------- ### PostgreBase Startup Output Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/README.md Example of the console output displayed upon successful server initialization. ```text PostgreBase — AI-Native No-Code API Platform ├─ REST API: http://127.0.0.1:8090/api/ ├─ MCP SSE: http://127.0.0.1:8090/api/mcp/sse └─ Admin UI: http://127.0.0.1:8090/_/ ``` -------------------------------- ### Development commands for PostgreBase UI Source: https://github.com/zhenruyan/postgrebase/blob/master/ui/README.md Use these commands to install dependencies, start the development server, or build the production bundle. ```sh # install dependencies npm install # start a dev server with hot reload at localhost:3000 npm run dev # or generate production ready bundle in dist/ directory npm run build ``` -------------------------------- ### Run PostgreBase with MySQL Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/getting-started.md Start the server using a MySQL connection string. ```bash ./pb serve --dataDsn "mysql://user:password@tcp(127.0.0.1:3306)/dbname" ``` -------------------------------- ### Start PostgreBase Server Source: https://github.com/zhenruyan/postgrebase/blob/master/npm/README.md Launch the server with different database backends and optional Redis caching. ```bash # SQLite (local development) postgrebase serve --dataDsn "sqlite://./data.db" # PostgreSQL (production) postgrebase serve --dataDsn "postgres://user:pass@localhost:5432/db?sslmode=disable" # MySQL postgrebase serve --dataDsn "mysql://user:pass@tcp(localhost:3306)/db" # With Redis cache postgrebase serve --dataDsn "postgres://..." --redisDsn "redis://localhost:6379/0" ``` -------------------------------- ### Build the Admin UI Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/faq.md Steps to install dependencies and compile the Admin UI, followed by building the Go binary. ```bash cd ui npm install npm run build cd .. go build -o pb ./build/ ``` -------------------------------- ### Build and Run PostgreBase Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/README.md Commands to build the binary and start the server with PostgreSQL and Redis configurations. ```bash # Build CGO_ENABLED=0 go build -o pb ./build/ # Run with PostgreSQL ./pb serve --dataDsn "postgresql://user:pass@127.0.0.1:5432/db?sslmode=disable" # Run with Redis cache ./pb serve --dataDsn "postgres://..." --redisDsn "redis://localhost:6379/0" ``` -------------------------------- ### Install PostgreBase CLI Source: https://github.com/zhenruyan/postgrebase/blob/master/npm/README.md Install the PostgreBase installer globally via npm. ```bash npm install -g postgrebase-installer ``` -------------------------------- ### Run PostgreBase with PostgreSQL Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/getting-started.md Start the server using a PostgreSQL connection string. ```bash ./pb serve --dataDsn "postgresql://user:password@127.0.0.1:5432/dbname?sslmode=disable" ``` -------------------------------- ### Install MySQL driver Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Install the necessary MySQL driver package for database connectivity. ```bash go get github.com/go-sql-driver/mysql ``` -------------------------------- ### Install and Import PostgreBase in Node.js Source: https://github.com/zhenruyan/postgrebase/blob/master/js-sdk/README.md Install the package via npm and import it using ES modules or CommonJS. ```sh npm install postgrebase --save ``` ```js // Using ES modules (default) import PostgreBase from 'postgrebase' // OR if you are using CommonJS modules const PostgreBase = require('postgrebase/cjs') ``` -------------------------------- ### Start MCP Server Source: https://github.com/zhenruyan/postgrebase/blob/master/npm/README.md Run the built-in Model Context Protocol server in stdio mode with optional authentication. ```bash # Start MCP server (stdio mode) postgrebase mcp --dataDsn "sqlite://./dev.db" --mcp-no-auth # With authentication postgrebase mcp --dataDsn "postgres://..." --mcp-token "YOUR_TOKEN" ``` -------------------------------- ### Perform Basic SDK Operations Source: https://github.com/zhenruyan/postgrebase/blob/master/js-sdk/README.md Example usage for listing records and authenticating users or admins. ```js import PostgreBase from 'postgrebase'; const pb = new PostgreBase('http://127.0.0.1:8090'); ... // list and filter "example" collection records const result = await pb.collection('example').getList(1, 20, { filter: 'status = true && created > "2022-08-01 10:00:00"' }); // authenticate as auth collection record const userData = await pb.collection('users').authWithPassword('test@example.com', '123456'); // or as super-admin const adminData = await pb.admins.authWithPassword('test@example.com', '123456'); // and much more... ``` -------------------------------- ### Run PostgreBase with SQLite Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/getting-started.md Start the server using a local SQLite database file. ```bash # Using sqlite:// prefix ./pb serve --dataDsn "sqlite://./pb_data/dev.db" # Or just pass a .db file path ./pb serve --dataDsn "./pb_data/dev.db" ``` -------------------------------- ### npm Installer Commands Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/development.md Commands for managing and publishing npm packages. ```bash make npm-version # Sync version to npm installer package make npm-packages # Build platform-specific npm packages make npm-pack # Pack main + all platform packages make npm-publish-all # Publish main + all platform packages make npm-publish-pre # Publish pre-release packages ``` -------------------------------- ### Filter Syntax Examples Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/api-reference.md Examples of valid filter expressions for record queries. ```text status = "active" created > "2024-01-01" title ~ "search term" && status != "draft" price >= 10 && price <= 100 ``` -------------------------------- ### Start PostgreBase Nodes Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/high-availability.md Launch multiple instances pointing to the same shared database and Redis cluster. ```bash # Node 1 ./pb serve \ --dataDsn "postgres://app:secret@pg-cluster:5432/postgrebase?sslmode=disable" \ --redisDsn "redis://redis-cluster:6379/0" \ --dir /shared/postgrebase-data # Node 2 (same config) ./pb serve \ --dataDsn "postgres://app:secret@pg-cluster:5432/postgrebase?sslmode=disable" \ --redisDsn "redis://redis-cluster:6379/0" \ --dir /shared/postgrebase-data ``` -------------------------------- ### Production Configuration with PostgreSQL Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/configuration.md Example command for running PostgreBase in production using a PostgreSQL database and a custom data directory. ```bash ./pb serve \ --dataDsn "postgres://app:secret@db.example.com:5432/postgrebase?sslmode=disable" \ --dir /var/data/postgrebase ``` -------------------------------- ### Run PostgreBase with Redis Cache Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/getting-started.md Start the server with an optional Redis cache layer. ```bash ./pb serve --dataDsn "postgres://..." --redisDsn "redis://127.0.0.1:6379/0" ``` -------------------------------- ### Production Configuration with MySQL and Redis Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/configuration.md Example command for running PostgreBase in production using MySQL and an external Redis cache. ```bash ./pb serve \ --dataDsn "mysql://app:secret@tcp(db.example.com:3306)/postgrebase" \ --redisDsn "redis://redis.example.com:6379/0" \ --dir /var/data/postgrebase ``` -------------------------------- ### Build query conditions Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Examples of various expression types for building WHERE or HAVING clauses using dbx. ```go // id=100 dbx.NewExp("id={:id}", dbx.Params{"id": 100}) // id=100 AND status=1 dbx.HashExp{"id": 100, "status": 1} // status=1 OR age>30 dbx.Or(dbx.HashExp{"status": 1}, dbx.NewExp("age>30")) // name LIKE '%admin%' AND name LIKE '%example%' dbx.Like("name", "admin", "example") ``` -------------------------------- ### Run PostgreBase in single-instance mode Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/proposal/vector-embedded-raft-proposal.md Starts the service locally without cluster protocol overhead, using local sqlite-vec and memory/Redis caching. ```bash pb serve --dataDsn "postgres://..." --dir ./pb_data ``` -------------------------------- ### Local Development Configuration Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/configuration.md Example command for running PostgreBase in local development mode with SQLite and debug logging enabled. ```bash ./pb serve --dataDsn "sqlite://./pb_data/dev.db" --debug ``` -------------------------------- ### Run PostgreBase in multi-instance mode Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/proposal/vector-embedded-raft-proposal.md Starts multiple instances that automatically enter Raft cluster mode to synchronize metadata, cache states, and SQLite operations. ```bash pb serve --dataDsn "postgres://..." --listen :8090 pb serve --dataDsn "postgres://..." --listen :8091 pb serve --dataDsn "postgres://..." --listen :8092 ``` -------------------------------- ### HA Cluster Node Configuration Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/configuration.md Example command for running a PostgreBase node in a high-availability cluster environment. ```bash ./pb serve \ --dataDsn "postgres://app:secret@pg-cluster:5432/postgrebase?sslmode=disable" \ --redisDsn "redis://redis-cluster:6379/0" ``` -------------------------------- ### GET /api/collections Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/api-reference.md List all collections. ```APIDOC ## GET /api/collections ### Description List all collections. ### Method GET ### Endpoint /api/collections ``` -------------------------------- ### GET /api/mcp-tokens Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/mcp.md Lists all MCP tokens. ```APIDOC ## GET /api/mcp-tokens ### Description Retrieves a list of all MCP tokens (masked). ### Method GET ### Endpoint /api/mcp-tokens ``` -------------------------------- ### Application Initialization Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/index.html Sets up the initial theme, language, and document routing upon DOM content load. ```javascript document.addEventListener('DOMContentLoaded', () => { // Apply stored theme applyTheme(getStoredTheme()); const route = getHashRoute(); if (route && DOCS[route.lang]) { currentLanguage = route.lang; currentDoc = route.doc; } updateLanguageButtons(); updateNavigation(); loadDocument(currentDoc, !route); window.addEventListener('hashchange', handleHashChange); }); ``` -------------------------------- ### GET /api/health Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/api-reference.md Checks if the server is running. ```APIDOC ## GET /api/health ### Description Returns 200 OK when the server is running. ### Method GET ### Endpoint /api/health ``` -------------------------------- ### Uninstall PostgreBase CLI Source: https://github.com/zhenruyan/postgrebase/blob/master/npm/README.md Remove the global PostgreBase installer package. ```bash npm uninstall -g postgrebase-installer ``` -------------------------------- ### Static Build (No CGO) Source: https://github.com/zhenruyan/postgrebase/blob/master/README_zh.md Build the binary without CGO dependencies. ```bash CGO_ENABLED=0 go build -o pb ./build/ ``` -------------------------------- ### GET /api/mcp/sse Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/mcp.md Establishes an SSE event stream for MCP communication. ```APIDOC ## GET /api/mcp/sse ### Description Establishes an SSE event stream for MCP communication. ### Method GET ### Endpoint http://localhost:8090/api/mcp/sse ``` -------------------------------- ### Initialize PostgreBase in Browser Source: https://github.com/zhenruyan/postgrebase/blob/master/js-sdk/README.md Initialize the SDK using a script tag or ES modules in a browser environment. ```html ``` ```html ``` -------------------------------- ### GET /api/mcp-tokens Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/mcp.md Lists all MCP tokens (masked). Requires admin authentication. ```APIDOC ## GET /api/mcp-tokens ### Description Lists all MCP tokens (masked). Requires admin authentication. ### Method GET ### Endpoint /api/mcp-tokens ``` -------------------------------- ### Build and execute a SELECT query Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Demonstrates chaining query methods to build a SELECT statement and executing it with One(). ```go db, _ := dbx.Open("mysql", "user:pass@/example") err := db.Select("id", "name"). From("users"). Where(dbx.HashExp{"id": 100}). One(&user) ``` -------------------------------- ### Configure SQL Logging in dbx Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Demonstrates how to assign log functions to DB instances for tracking query and execution events. ```go package main import ( "context" "database/sql" "log" "time" "github.com/pocketbase/dbx" ) func main() { db, _ := dbx.Open("mysql", "user:pass@/example") // simple logging db.LogFunc = log.Printf // or you can use the following more flexible logging db.QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) { log.Printf("[%.2fms] Query SQL: %v", float64(t.Milliseconds()), sql) } db.ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) { log.Printf("[%.2fms] Execute SQL: %v", float64(t.Milliseconds()), sql) } // ... } ``` -------------------------------- ### Using the dbx Query Builder Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Shows how to use the fluent API to build SELECT and INSERT queries programmatically. ```go package main import ( "github.com/pocketbase/dbx" _ "github.com/go-sql-driver/mysql" ) func main() { db, _ := dbx.Open("mysql", "user:pass@/example") // build a SELECT query // SELECT `id`, `name` FROM `users` WHERE `name` LIKE '%Charles%' ORDER BY `id` q := db.Select("id", "name"). From("users"). Where(dbx.Like("name", "Charles")). OrderBy("id") // fetch all rows into a struct array var users []struct { ID, Name string } q.All(&users) // build an INSERT query // INSERT INTO `users` (`name`) VALUES ('James') db.Insert("users", dbx.Params{ "name": "James", }).Execute() } ``` -------------------------------- ### Build PostgreBase from source Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/getting-started.md Commands to clone the repository and compile the binary. ```bash git clone https://github.com/zhenruyan/postgrebase.git cd postgrebase go build -o pb ./build/ ``` ```bash CGO_ENABLED=0 go build -o pb ./build/ ``` -------------------------------- ### Generated SQL output Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md The resulting SQL statement generated by the previous query builder example. ```sql SELECT `id`, `name` FROM `users` WHERE `id`={:p0} ``` -------------------------------- ### Build and Run Postgrebase Commands Source: https://github.com/zhenruyan/postgrebase/blob/master/AGENTS.md Commands for building the binary and running the server with different database backends and MCP configurations. ```bash # Build (static, no CGO) CGO_ENABLED=0 go build -o pb ./build/ # Run with SQLite (local development) ./pb serve --dataDsn "sqlite://./pb_data/dev.db" ./pb serve --dataDsn "./pb_data/dev.db" # shorthand # Run with PostgreSQL (production) ./pb serve --dataDsn "postgres://user:pass@127.0.0.1:5432/db?sslmode=disable" # Run with MySQL ./pb serve --dataDsn "mysql://user:pass@tcp(127.0.0.1:3306)/db" # Run with Redis cache ./pb serve --dataDsn "postgres://..." --redisDsn "redis://localhost:6379/0" # Run MCP stdio server ./pb mcp --dataDsn "sqlite://./dev.db" --mcp-no-auth ./pb mcp --dataDsn "postgres://..." --mcp-token "TOKEN" # Rebuild Admin UI cd ui && npm install && npm run build && cd .. go build -o pb ./build/ # must rebuild to embed updated dist/ ``` -------------------------------- ### GET /api/collections/{collection}/records Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/api-reference.md List records from a specific collection with optional filtering and pagination. ```APIDOC ## GET /api/collections/{collection}/records ### Description List records from a specific collection with optional filtering and pagination. ### Method GET ### Endpoint /api/collections/{collection}/records ### Parameters #### Path Parameters - **collection** (string) - Required - The collection name or ID #### Query Parameters - **page** (integer) - Optional - Page number - **perPage** (integer) - Optional - Records per page - **sort** (string) - Optional - Sort field and direction - **filter** (string) - Optional - Filter expression - **expand** (string) - Optional - Expand relations - **fields** (string) - Optional - Select specific fields ``` -------------------------------- ### 运行 PostgreBase 容器 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/faq.md 使用 Docker 运行 PostgreBase,支持 SQLite 和 PostgreSQL 两种数据库配置。 ```bash # SQLite docker run -p 8090:8090 -v pb_data:/pb/pb_data postgrebase serve --dataDsn "sqlite:///pb/pb_data/dev.db" # PostgreSQL docker run -p 8090:8090 postgrebase serve --dataDsn "postgres://user:pass@host:5432/db?sslmode=disable" ``` -------------------------------- ### 使用 Makefile 构建 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/development.md 通过 Makefile 执行常见的构建、测试和格式化任务。 ```makefile make build # 构建当前平台 make build-all # 构建所有平台(Linux、macOS、Windows) make dist # 构建并打包可分发归档 make lint # 运行 linter make fmt # 格式化代码 ``` -------------------------------- ### Static Analysis Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/development.md Run Go vet for static code analysis. ```bash go vet ./... ``` -------------------------------- ### Open a database connection Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Establishes a connection to the database using a driver name and data source name. Note that the connection is lazy and only established upon the first query execution. ```go db, err := dbx.Open("mysql", "user:pass@hostname/db_name") ``` -------------------------------- ### Scroll Spy Setup Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/index.html Initializes an IntersectionObserver to track heading visibility and update the table of contents active state. ```javascript = '#' + heading.id; a.textContent = heading.textContent; a.onclick = function(e) { e.preventDefault(); heading.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.replaceState(null, '', '#' + heading.id); }; li.appendChild(a); tocList.appendChild(li); }); // Scroll spy setupScrollSpy(); } function setupScrollSpy() { const tocItems = document.querySelectorAll('.toc__item'); const headings = document.querySelectorAll('.content-card h2, .content-card h3'); if (tocItems.length === 0) return; const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { const id = entry.target.id; tocItems.forEach(item => { item.classList.toggle('active', item.getAttribute('href') === '#' + id); }); } }); }, { rootMargin: '-80px 0px -70% 0px', threshold: 0 }); headings.forEach(h => observer.observe(h)); } ``` -------------------------------- ### Compile PostgreBase from Source Source: https://github.com/zhenruyan/postgrebase/blob/master/README_zh.md Standard build command for the PostgreBase binary. ```bash git clone https://github.com/zhenruyan/postgrebase.git cd postgrebase go build -o pb ./build/ ``` -------------------------------- ### Build Docker Image Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/development.md Command to build the project container image. ```bash docker build -t postgrebase . ``` -------------------------------- ### Docker Deployment Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/getting-started.md Commands to build the Docker image and run the server with different backends. ```bash docker build -t postgrebase . ``` ```bash docker run -p 8090:8090 -v pb_data:/pb/pb_data postgrebase serve --dataDsn "sqlite:///pb/pb_data/dev.db" ``` ```bash docker run -p 8090:8090 postgrebase serve --dataDsn "postgres://user:pass@host:5432/dbname?sslmode=disable" ``` ```bash docker run -p 8090:8090 postgrebase serve --dataDsn "postgres://..." --redisDsn "redis://host:6379/0" ``` -------------------------------- ### Build and Run PostgreBase with Docker Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/faq.md Commands to build the Docker image and run the container using either SQLite or PostgreSQL as the backend database. ```bash docker build -t postgrebase . ``` ```bash # SQLite docker run -p 8090:8090 -v pb_data:/pb/pb_data postgrebase serve --dataDsn "sqlite:///pb/pb_data/dev.db" # PostgreSQL docker run -p 8090:8090 postgrebase serve --dataDsn "postgres://user:pass@host:5432/db?sslmode=disable" ``` -------------------------------- ### Accessing MySQL Data with dbx Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Demonstrates connecting to a MySQL database and executing raw SQL queries to fetch data into structs or maps. ```go package main import ( "github.com/pocketbase/dbx" _ "github.com/go-sql-driver/mysql" ) func main() { db, _ := dbx.Open("mysql", "user:pass@/example") // create a new query q := db.NewQuery("SELECT id, name FROM users LIMIT 10") // fetch all rows into a struct array var users []struct { ID, Name string } q.All(&users) // fetch a single row into a struct var user struct { ID, Name string } q.One(&user) // fetch a single row into a string map data := dbx.NullStringMap{} q.One(data) // fetch row by row rows2, _ := q.Rows() for rows2.Next() { rows2.ScanStruct(&user) // rows.ScanMap(data) // rows.Scan(&id, &name) } } ``` -------------------------------- ### JavaScript SDK Commands Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/development.md Commands for building and publishing the JS SDK. ```bash make sdk-build # Build the JavaScript SDK make sdk-test # Run JS SDK tests make sdk-pack # Pack JS SDK for publishing make sdk-publish # Publish JS SDK to npm make sdk-publish-pre # Publish JS SDK pre-release ``` -------------------------------- ### 添加新 MCP 工具 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/development.md 在 mcp/tools.go 中实现工具处理方法。 ```go func (s *Server) toolMyNewTool(args map[string]interface{}) (*ToolCallResult, error) { // 解析参数 // 使用 s.app.Dao() 访问数据 return &ToolCallResult{Content: []Content{{Type: "text", Text: result}}}, nil } ``` -------------------------------- ### Configure Claude Desktop for PostgreBase Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/mcp.md JSON configuration snippet for integrating PostgreBase as an MCP server within Claude Desktop. ```json { "mcpServers": { "postgrebase": { "command": "/path/to/pb", "args": ["mcp", "--dataDsn", "sqlite:///path/to/dev.db", "--mcp-no-auth"] } } } ``` -------------------------------- ### Initialize Prism Syntax Highlighter Source: https://github.com/zhenruyan/postgrebase/blob/master/ui/index.html Configures the Prism library to operate in manual mode for syntax highlighting. ```javascript window.Prism = window.Prism || {}; window.Prism.manual = true; ``` -------------------------------- ### 启动 SQLite 服务 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/getting-started.md 使用 sqlite:// 前缀或直接指定 .db 文件路径启动本地开发服务。 ```bash # 使用 sqlite:// 前缀 ./pb serve --dataDsn "sqlite://./pb_data/dev.db" # 或者直接传 .db 文件路径 ./pb serve --dataDsn "./pb_data/dev.db" ``` -------------------------------- ### Project Directory Structure Source: https://github.com/zhenruyan/postgrebase/blob/master/README.md Overview of the repository layout and core modules. ```text postgrebase/ ├── build/ # Main server entry point (main.go) ├── core/ # Application logic, DB connection, caching ├── daos/ # Data access objects (CRUD operations) ├── models/ # Data models and schema definitions ├── apis/ # HTTP API handlers (REST + MCP routes) ├── mcp/ # MCP server: protocol, tools, resources, transports ├── migrations/ # Database migrations (Postgres/MySQL/SQLite) ├── cmd/ # CLI commands (serve, mcp, admin) ├── dbx/ # Database query builder (fork of ozzo-dbx) ├── tools/ # Shared utilities (security, types, search, etc.) ├── ui/ # Admin UI (Svelte + Vite) ├── vendor/ # Go dependencies (preserved for offline builds) └── postgrebase.go # Root package: CLI setup, config, bootstrap ``` -------------------------------- ### 记录操作 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/development.md 通过 DAO 层对记录进行增删改查操作。 ```go // 获取 record, err := dao.FindRecordById(collectionId, recordId) // 设置值 record.Set("title", "New Title") // 读取值 title := record.GetString("title") // 保存(创建或更新) err := dao.SaveRecord(record) // 删除 err := dao.DeleteRecord(record) ``` -------------------------------- ### Retrieve query results Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Demonstrates various methods to populate results into structs, maps, slices, or individual variables. ```go type User struct { ID int Name string } var ( users []User user User row dbx.NullStringMap id int name string err error ) q := db.NewQuery("SELECT id, name FROM users LIMIT 10") // populate all rows into a User slice err = q.All(&users) fmt.Println(users[0].ID, users[0].Name) // populate the first row into a User struct err = q.One(&user) fmt.Println(user.ID, user.Name) // populate the first row into a NullString map err = q.One(&row) fmt.Println(row["id"], row["name"]) var ids []int err = q.Column(&ids) fmt.Println(ids) // populate the first row into id and name err = q.Row(&id, &name) // populate data row by row rows, _ := q.Rows() for rows.Next() { _ = rows.ScanMap(&row) } ``` -------------------------------- ### npm 安装器命令 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/development.md 管理 npm 包的构建、打包与发布。 ```bash make npm-version # 同步版本到 npm 安装器包 make npm-packages # 构建平台特定 npm 包 make npm-pack # 打包主包和所有平台包 make npm-publish-all # 发布主包和所有平台包 make npm-publish-pre # 发布预发布包 ``` -------------------------------- ### Run Project Tests Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/faq.md Command to execute tests across the core tool, model, and DAO packages. ```bash go test ./tools/... ./models/... ./daos/... ``` -------------------------------- ### Build with Makefile Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/development.md Common build and maintenance tasks managed via Makefile. ```bash make build # Build for current platform make build-all # Build for all platforms (Linux, macOS, Windows) make dist # Build and package distributable archives make lint # Run linter make fmt # Format code ``` -------------------------------- ### Load and Render Documentation Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/index.html Fetches a markdown file, parses it, and updates the content area with sanitized HTML. Requires marked and DOMPurify libraries. ```javascript async function loadDocument(docId, updateHash = true) { const contentDiv = document.getElementById('content'); contentDiv.classList.remove('loaded'); contentDiv.innerHTML = `
Loading...
`; try { const response = await fetch(getDocPath(currentLanguage, docId)); if (!response.ok) { throw new Error(`Document not found (${response.status})`); } const text = await response.text(); // Render markdown with marked + sanitize const html = marked.parse(text, { breaks: false, gfm: true }); contentDiv.innerHTML = DOMPurify.sanitize(html, { ADD_ATTR: ['target'] }); currentDoc = docId; if (updateHash) { setHashRoute(currentLanguage, docId); } // Update active nav item document.querySelectorAll('.nav-drawer__item').forEach(item => { item.classList.toggle('active', item.getAttribute('data-doc') === docId); }); // Post-processing: syntax highlight, copy buttons, TOC, internal links, prev/next enhanceCodeBlocks(); buildTableOfContents(); handleInternalLinks(); buildPrevNextNav(); // Scroll to top or to hash anchor const route = getHashRoute(); if (route && route.doc !== docId) { // nope } window.scrollTo({ top: 0, behavior: 'smooth' }); closeDrawer(); // Trigger fade-in requestAnimationFrame(() => { contentDiv.classList.add('loaded'); }); } catch (error) { contentDiv.innerHTML = `

Error Loading Document

${error.message}

`; } } ``` -------------------------------- ### Prepare and execute a query multiple times Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Prepares a SQL statement for repeated execution with different parameters to improve performance. ```go q := db.NewQuery("SELECT id, name FROM users WHERE id={:id}") q.Prepare() defer q.Close() q.Bind(dbx.Params{"id": 100}) err := q.One(&user) q.Bind(dbx.Params{"id": 200}) err = q.One(&user) // ... ``` -------------------------------- ### MCP SSE 传输模式接口 Source: https://github.com/zhenruyan/postgrebase/blob/master/README_zh.md 运行 ./pb serve 后可用的 HTTP 接口地址。 ```http GET http://localhost:8090/api/mcp/sse # SSE 事件流 POST http://localhost:8090/api/mcp/message # 发送 JSON-RPC 请求 POST http://localhost:8090/api/mcp/stream # Streamable HTTP(单次请求/响应) ``` -------------------------------- ### 构建与运行 PostgreBase Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/README.md 展示如何构建项目并使用 PostgreSQL 或 Redis 缓存启动服务。 ```bash # 构建 CGO_ENABLED=0 go build -o pb ./build/ # 使用 PostgreSQL 运行 ./pb serve --dataDsn "postgresql://user:pass@127.0.0.1:5432/db?sslmode=disable" # 启用 Redis 缓存 ./pb serve --dataDsn "postgres://..." --redisDsn "redis://localhost:6379/0" ``` -------------------------------- ### JavaScript SDK 命令 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/development.md 管理 JS SDK 的构建与发布。 ```bash make sdk-build # 构建 JavaScript SDK make sdk-test # 运行 JS SDK 测试 make sdk-pack # 打包 JS SDK make sdk-publish # 发布 JS SDK 到 npm make sdk-publish-pre # 发布 JS SDK 预发布版本 ``` -------------------------------- ### Configure Node.js Polyfills Source: https://github.com/zhenruyan/postgrebase/blob/master/js-sdk/README.md Load fetch and EventSource polyfills for Node.js environments. ```js // npm install cross-fetch --save import 'cross-fetch/polyfill'; ``` ```js // for server: npm install eventsource --save import eventsource from 'eventsource'; // for React Native: npm install react-native-sse --save import eventsource from "react-native-sse"; global.EventSource = eventsource; ``` -------------------------------- ### MCP Stdio 模式启动命令 Source: https://github.com/zhenruyan/postgrebase/blob/master/README_zh.md 通过 stdin/stdout 通信运行 MCP 服务器的 CLI 命令。 ```bash ./pb mcp --dataDsn "sqlite://./dev.db" --mcp-token "YOUR_TOKEN" # 或禁用认证(不推荐用于生产) ./pb mcp --dataDsn "sqlite://./dev.db" --mcp-no-auth ``` -------------------------------- ### Import MySQL driver Source: https://github.com/zhenruyan/postgrebase/blob/master/dbx/README.md Import the MySQL driver in your Go source code to register it with the database/sql package. ```go import _ "github.com/go-sql-driver/mysql" ``` -------------------------------- ### Git 贡献工作流命令 Source: https://github.com/zhenruyan/postgrebase/blob/master/README_zh.md 用于创建特性分支的 Git 命令示例。 ```bash git checkout -b feature/amazing-feature ``` ```bash git commit -m 'Add some amazing feature' ``` ```bash git push origin feature/amazing-feature ``` -------------------------------- ### 启动 PostgreBase 集群节点 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/high-availability.md 通过命令行参数配置多个实例连接至相同的数据库和 Redis 集群,确保数据一致性。 ```bash # 节点 1 ./pb serve \ --dataDsn "postgres://app:secret@pg-cluster:5432/postgrebase?sslmode=disable" \ --redisDsn "redis://redis-cluster:6379/0" \ --dir /shared/postgrebase-data # 节点 2(相同配置) ./pb serve \ --dataDsn "postgres://app:secret@pg-cluster:5432/postgrebase?sslmode=disable" \ --redisDsn "redis://redis-cluster:6379/0" \ --dir /shared/postgrebase-data ``` -------------------------------- ### 使用 DateTime 类型 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/development.md 处理时间类型及其格式化。 ```go now := types.NowDateTime() t := now.Time() // 返回 time.Time zero := types.DateTime{} zero.IsZero() // true ``` -------------------------------- ### Migrate Realtime Subscription Methods Source: https://github.com/zhenruyan/postgrebase/blob/master/js-sdk/CHANGELOG.md Mapping of deprecated pb.realtime methods to the new pb.collection service structure. ```js pb.realtime.subscribe('example', callback) => pb.collection('example').subscribe("*", callback) pb.realtime.subscribe('example/RECORD_ID', callback) => pb.collection('example').subscribe('RECORD_ID', callback) pb.realtime.unsubscribe('example') => pb.collection('example').unsubscribe("*") pb.realtime.unsubscribe('example/RECORD_ID') => pb.collection('example').unsubscribe('RECORD_ID') (no old equivalent) => pb.collection('example').unsubscribe() ``` -------------------------------- ### 配置 Nginx 负载均衡 Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/zh/high-availability.md 使用 Nginx 将流量分发至多个 PostgreBase 实例,并配置必要的头部信息以支持 SSE 实时通信。 ```nginx upstream postgrebase { least_conn; server 10.0.0.1:8090; server 10.0.0.2:8090; server 10.0.0.3:8090; } server { listen 80; server_name api.example.com; location / { proxy_pass http://postgrebase; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # SSE 支持 proxy_set_header Connection ''; proxy_http_version 1.1; chunked_transfer_encoding off; proxy_buffering off; proxy_cache off; } } ``` -------------------------------- ### Migrate User Handlers to Collection Methods Source: https://github.com/zhenruyan/postgrebase/blob/master/js-sdk/CHANGELOG.md Updates for moving pb.users.* handlers to the pb.collection('users').* namespace. ```javascript pb.users.listAuthMethods() => pb.collection('users').listAuthMethods() pb.users.authViaEmail(email, password) => pb.collection('users').authWithPassword(usernameOrEmail, password) pb.users.authViaOAuth2(provider, code, codeVerifier, redirectUrl) => pb.collection('users').authWithOAuth2(provider, code, codeVerifier, redirectUrl, createData = {}) pb.users.refresh() => pb.collection('users').authRefresh() pb.users.requestPasswordReset(email) => pb.collection('users').requestPasswordReset(email) pb.users.confirmPasswordReset(resetToken, newPassword, newPasswordConfirm) => pb.collection('users').confirmPasswordReset(resetToken, newPassword, newPasswordConfirm) pb.users.requestVerification(email) => pb.collection('users').requestVerification(email) pb.users.confirmVerification(verificationToken) => pb.collection('users').confirmVerification(verificationToken) pb.users.requestEmailChange(newEmail) => pb.collection('users').requestEmailChange(newEmail) pb.users.confirmEmailChange(emailChangeToken, password) => pb.collection('users').confirmEmailChange(emailChangeToken, password) pb.users.listExternalAuths(recordId) => pb.collection('users').listExternalAuths(recordId) pb.users.unlinkExternalAuth(recordId, provider) => pb.collection('users').unlinkExternalAuth(recordId, provider) ``` -------------------------------- ### Registering a New MCP Tool Handler Source: https://github.com/zhenruyan/postgrebase/blob/master/AGENTS.md Implement a handler method in mcp/tools.go using the provided signature to process tool calls. ```go func (s *Server) toolMyNewTool(args map[string]interface{}) (*ToolCallResult, error) { // parse args // use s.app.Dao() for data access // return &ToolCallResult{Content: []Content{{Type: "text", Text: result}}} } ``` -------------------------------- ### Configure Nginx Load Balancer Source: https://github.com/zhenruyan/postgrebase/blob/master/docs/en/high-availability.md Set up Nginx to distribute traffic across multiple PostgreBase nodes with support for SSE. ```nginx upstream postgrebase { least_conn; server 10.0.0.1:8090; server 10.0.0.2:8090; server 10.0.0.3:8090; } server { listen 80; server_name api.example.com; location / { proxy_pass http://postgrebase; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # SSE support proxy_set_header Connection ''; proxy_http_version 1.1; chunked_transfer_encoding off; proxy_buffering off; proxy_cache off; } } ```