Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# PostgreSQL Explorer - Copilot Instructions

## Project Overview
VS Code extension for PostgreSQL database management featuring interactive SQL notebooks, real-time dashboard, AI chat assistant, and tree-based database explorer. Uses `pg` client for PostgreSQL connections.

## Architecture

### Core Components
- **`src/extension.ts`**: Entry point - initializes services (singletons), registers all commands, providers, and tree views
- **`src/services/ConnectionManager.ts`**: Singleton managing PostgreSQL connections with connection pooling keyed by `{connectionId}:{database}`
- **`src/services/SecretStorageService.ts`**: Singleton wrapping VS Code SecretStorage for credential management
- **`src/providers/DatabaseTreeProvider.ts`**: Tree view provider showing connections → databases → schemas → objects hierarchy
- **`src/providers/NotebookKernel.ts`**: Executes SQL cells in `.pgsql` notebooks, provides SQL completions
- **`src/providers/ChatViewProvider.ts`**: AI chat assistant using modular services from `src/providers/chat/`

### Command Pattern
Commands live in `src/commands/{domain}.ts` with SQL templates extracted to `src/commands/sql/{domain}.ts`:
```typescript
// src/commands/tables.ts - uses NotebookBuilder pattern
import { TableSQL } from './sql';
await new NotebookBuilder(metadata)
.addMarkdown(MarkdownUtils.header('...') + MarkdownUtils.infoBox('...'))
.addSql(TableSQL.delete(schema, table))
.show();
```

### Helper Utilities (`src/commands/helper.ts`)
- `getDatabaseConnection(item)` - validates item, gets connection with password, returns `{connection, client, metadata}`
- `NotebookBuilder` - fluent API for creating notebooks with `.addMarkdown()`, `.addSql()`, `.show()`
- `MarkdownUtils` - `header()`, `infoBox()`, `warningBox()`, `dangerBox()`, `operationsTable()`
- `ErrorHandlers.handleCommandError(err, action)` - standardized error handling

### Styling System (`src/common/`)
- **`htmlStyles.ts`**: CSS variables, `MarkdownBuilder` for consistent markdown formatting
- **`notebookTemplates.ts`**: `NotebookCellBuilder` and `CommonNotebookTemplates` for reusable notebook patterns
- **`rendererUtils.ts`**: Webview component builders using VS Code theme variables

## Key Patterns

### Singleton Services
```typescript
// Always access via getInstance()
ConnectionManager.getInstance().getConnection(config);
SecretStorageService.getInstance().getPassword(connectionId);
```

### Tree Item Structure
`DatabaseTreeItem` has: `type` (connection|database|schema|table|column|etc), `connectionId`, `databaseName`, `schema`, `label`

### Notebook Metadata
Notebooks store `PostgresMetadata` with `connectionId`, `databaseName`, `host`, `port`, `username`, `password`

## Development Workflow

```bash
npm run watch # Development - auto-recompile TypeScript
npm run compile # One-time build
npm run test # Unit tests with Mocha + Chai + Sinon
npm run coverage # Tests with coverage report
F5 # Launch Extension Development Host
```

### Testing
Tests in `src/test/unit/` mock VS Code API via `src/test/unit/mocks/vscode.ts`. Use `module-alias` in `src/test/setup.ts`.

### Debug Output
```typescript
import { outputChannel } from './extension';
outputChannel.appendLine('Debug message');
```

## File Organization

| Path | Purpose |
|------|---------|
| `src/commands/{domain}.ts` | Command implementations (tables, views, functions, etc.) |
| `src/commands/sql/{domain}.ts` | SQL template functions - pure, no VS Code deps |
| `src/providers/` | VS Code providers (tree, notebook kernel, chat, completions) |
| `src/providers/chat/` | Modular chat services (AiService, DbObjectService, SessionService) |
| `src/services/` | Business logic singletons |
| `src/common/` | Shared types, styles, templates |
| `src/dashboard/` | Dashboard webview components |

## Adding New Features

### New Database Object Command
1. Add SQL templates in `src/commands/sql/{object}.ts`
2. Implement command in `src/commands/{object}.ts` using `NotebookBuilder`
3. Register command in `src/extension.ts` and `package.json` contributes.commands
4. Add tree view context menu in `package.json` contributes.menus

### New Tree Item Type
1. Add type string to `DatabaseTreeItem` switch cases in `DatabaseTreeProvider.ts`
2. Add icon mapping and children fetching logic
3. Add context menu contributions in `package.json`
58 changes: 29 additions & 29 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ name: Publish Extension

on:
push:
branches:
- main
tags:
- 'v*'
workflow_dispatch:
Expand All @@ -13,42 +11,43 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'yarn'

- name: Configure Git
cache: 'npm'

- name: Get version from tag
id: version
run: |
git config --global user.name 'GitHub Actions'
git config --global user.email 'actions@github.com'
# Extract version from git tag (remove 'v' prefix)
TAG_VERSION=${GITHUB_REF_NAME#v}
echo "VERSION=$TAG_VERSION" >> $GITHUB_OUTPUT

- name: Increment version
if: startsWith(github.ref, 'refs/tags/v')
run: |
npm version patch --no-git-tag-version
VERSION=$(node -p "require('./package.json').version")
echo "NEW_VERSION=v$VERSION" >> $GITHUB_ENV
# Verify package.json version matches tag
PKG_VERSION=$(node -p "require('./package.json').version")
echo "Tag version: $TAG_VERSION"
echo "Package.json version: $PKG_VERSION"

- name: Commit version update
if: startsWith(github.ref, 'refs/tags/v')
run: |
git add package.json
git commit -m "Bump version to ${{ env.NEW_VERSION }}"
git push
if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then
echo "::warning::Tag version ($TAG_VERSION) doesn't match package.json version ($PKG_VERSION)"
fi

# Set VSIX filename
EXTENSION_NAME=$(node -p "require('./package.json').name")
echo "VSIX_FILE=${EXTENSION_NAME}-${PKG_VERSION}.vsix" >> $GITHUB_OUTPUT

- name: Install dependencies
run: |
yarn install --frozen-lockfile
yarn global add @vscode/vsce@2.22.0 ovsx
run: npm ci

- name: Build
run: yarn run vscode:prepublish
run: npm run vscode:prepublish

- name: Package Extension
run: vsce package
run: npx @vscode/vsce package

- name: Upload VSIX as Artifact
uses: actions/upload-artifact@v4
Expand All @@ -58,15 +57,16 @@ jobs:
retention-days: 90

- name: Publish to VS Code Marketplace
if: startsWith(github.ref, 'refs/tags/v')
run: vsce publish -p ${{ secrets.VSCE_PAT }}
run: |
echo "Publishing ${{ steps.version.outputs.VSIX_FILE }} to VS Code Marketplace..."
npx @vscode/vsce publish --packagePath ${{ steps.version.outputs.VSIX_FILE }} -p ${{ secrets.VSCE_PAT }}

- name: Publish to Open VSX Registry
if: startsWith(github.ref, 'refs/tags/v')
run: ovsx publish *.vsix -p ${{ secrets.OVSX_PAT }}
run: |
echo "Publishing ${{ steps.version.outputs.VSIX_FILE }} to Open VSX Registry..."
npx ovsx publish ${{ steps.version.outputs.VSIX_FILE }} -p ${{ secrets.OVSX_PAT }}

- name: Create Release
if: startsWith(github.ref, 'refs/tags/v')
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand Down
202 changes: 202 additions & 0 deletions MARKETPLACE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
<div align="center">

# 🐘 PostgreSQL Explorer

### *Professional Database Management for VS Code*

**A comprehensive PostgreSQL database management extension featuring interactive SQL notebooks, real-time monitoring dashboard, AI-powered assistance, and advanced database operations—all within VS Code.**

</div>

---

## 📸 Screenshots

### 📊 Real-Time Database Dashboard
![Dashboard](resources/screenshots/pg-exp-dash.png)
*Monitor connections, queries, and performance metrics in real-time*

### 🔗 Connection Management
![Connection Management](resources/screenshots/pg-exp-connection.png)
*Manage multiple database connections with an intuitive interface*

### 📓 Interactive SQL Notebooks
![SQL Notebooks](resources/screenshots/pg-exp-view.png)
*Write and execute queries with rich output formatting*

### 🛠️ Object Creation
![Object Creation](resources/screenshots/pg-exp-create.png)
*Create database objects with intelligent templates*

---

## ✨ Key Features

| Feature | Description |
|---------|-------------|
| 🔌 **Secure Connections** | Manage multiple connections with VS Code SecretStorage encryption |
| 📊 **Live Dashboard** | Real-time metrics, active query monitoring, and performance graphs |
| 📓 **SQL Notebooks** | Interactive notebooks with rich output, AI assistance, and export options |
| 🌳 **Database Explorer** | Browse tables, views, functions, types, extensions, and roles |
| 🛠️ **Object Operations** | Full CRUD operations, scripts, VACUUM, ANALYZE, REINDEX |
| 🤖 **AI-Powered** | GitHub Copilot, OpenAI, Anthropic, and Google Gemini integration |
| ⌨️ **Developer Tools** | IntelliSense, keyboard shortcuts, PSQL terminal access |

---

## 🎯 Why PostgreSQL Explorer?

<table>
<tr>
<td width="50%">

### 🎨 Modern Interface
- Beautiful, intuitive UI designed for developers
- Real-time dashboard with live metrics
- Context-aware operations
- Seamless VS Code integration

</td>
<td width="50%">

### ⚡ Powerful Features
- Interactive SQL notebooks
- 🤖 AI-powered Copilot & agentic support
- Advanced query management
- Complete CRUD operations

</td>
</tr>
<tr>
<td>

### 🔐 Secure & Reliable
- VS Code SecretStorage for credentials
- Safe connection management
- Transaction support
- Data integrity protection

</td>
<td>

### 🚀 Developer Friendly
- 🤖 GitHub Copilot integration
- Keyboard shortcuts
- IntelliSense support
- PSQL terminal integration

</td>
</tr>
</table>

---

## 🌳 Database Explorer

Navigate your database with an intuitive hierarchical tree view:

```
📁 Connection
└── 🗄️ Database
└── 📂 Schema
├── 📊 Tables
├── 👁️ Views
├── 🔄 Materialized Views
├── ⚙️ Functions
├── 🏷️ Types
├── 🔗 Foreign Tables
├── 🧩 Extensions
└── 👥 Roles
```

---

## 🤖 AI-Powered Assistance

Leverage AI to write, optimize, and debug your queries faster:

- **Smart Completions** — Context-aware SQL suggestions
- **Query Explanation** — Understand complex queries in plain English
- **Query Optimization** — Get performance improvement suggestions
- **Error Detection** — Real-time syntax and logical error detection
- **Natural Language to SQL** — Describe what you need, let AI write the SQL

**Supported AI Providers:**
- GitHub Copilot (VS Code LM)
- OpenAI
- Anthropic Claude
- Google Gemini
- Custom Endpoints

---

## 🚀 Quick Start

### Installation

1. Open VS Code → Press `Ctrl+Shift+X`
2. Search for **PostgreSQL Explorer**
3. Click **Install**

Or install via command line:
```bash
code --install-extension ric-v.postgres-explorer
```

### First Connection

1. Click the PostgreSQL icon in the Activity Bar
2. Click **Add Connection** or use `Ctrl+Shift+P` → `PostgreSQL: Add Connection`
3. Enter your connection details and click **Save**
4. Click on your connection to connect and start exploring!

---

## 📊 Complete Database Operations

| Object Type | Operations |
|-------------|------------|
| 📊 **Tables** | View, Edit, Insert, Update, Delete, Truncate, Drop, VACUUM, ANALYZE, REINDEX |
| 👁️ **Views** | View Definition, Edit, Query Data, Drop |
| 🔄 **Materialized Views** | Refresh, View Data, Edit, Drop |
| ⚙️ **Functions** | View, Edit, Call with Parameters, Drop |
| 🏷️ **Types** | View Properties, Edit, Drop |
| 🔗 **Foreign Tables** | View, Edit, Drop |
| 🧩 **Extensions** | Enable, Disable, Drop |
| 👥 **Roles** | Grant/Revoke Permissions, Edit, Drop |

---

## ⌨️ Keyboard Shortcuts

| Shortcut | Action |
|----------|--------|
| `Ctrl+Enter` | Execute current cell |
| `Shift+Enter` | Execute and move to next |
| `F5` | Refresh current item |
| `Ctrl+Shift+P` | Command palette |

---

## 📚 Resources

- 📖 [Full Documentation](https://dev-asterix.github.io/yape-postgres-ext-vsc/)
- 🐛 [Report Issues](https://github.com/dev-asterix/yape-postgres-ext-vsc/issues)
- 💡 [Request Features](https://github.com/dev-asterix/yape-postgres-ext-vsc/issues/new?template=feature_request.md)
- ⭐ [Star on GitHub](https://github.com/dev-asterix/yape-postgres-ext-vsc)

---

## 📝 License

This extension is licensed under the [MIT License](https://github.com/dev-asterix/yape-postgres-ext-vsc/blob/main/LICENSE).

---

<div align="center">

**Made with ❤️ for the PostgreSQL Community**

Also available on [Open VSX](https://open-vsx.org/extension/ric-v/postgres-explorer)

</div>
Loading