# DBCode - Complete Documentation > Database management inside VS Code. Query, edit, and visualize data without leaving your editor. Generated: 2026-08-12 --- ## Overview DBCode is a VS Code extension that brings full database management capabilities directly into your code editor. It supports 50+ databases and works with VS Code and all major forks including Cursor, Windsurf, Positron, Trae, Kiro, Antigravity, and VSCodium. Website: https://dbcode.io Documentation: https://dbcode.io/docs Install: https://dbcode.io/install --- ## Supported Databases (0+) --- ## Docs ### Documentation export const databaseCount = await getSupportedDatabaseCount(); Database management inside VS Code. Connect, query, edit, and ship without leaving your editor. Pick a section to dive in, or [jump to the install guide](/docs/get-started/install). ## Explore the docs --- ## Docs > Accounts ### index --- title: Accounts description: How to Sign in, Sign up, and manage your account. sidebar: hidden: true order: 11 --- --- ## Docs > Accounts > Container Deployment ### Container Deployment When deploying DBCode in containers, dev environments, or other automated setups, you can use environment variables to handle licensing without manual user interaction. This is designed for team subscriptions where an administrator pre-configures environments for team members. ## Overview Two environment variables control DBCode behavior in container environments: | Environment Variable | Purpose | |---|---| | `DBCODE_ACTIVATION_TOKEN` | Automatically activates a license on startup | | `DBCODE_REQUIRE_LICENSE` | Blocks all DBCode functionality until a valid license is present | Both are optional and can be used independently or together. ## Activation Tokens An activation token lets DBCode automatically obtain a license when it starts up. The token is tied to a specific team member's seat and is generated by a team owner or admin. ### How It Works 1. A team admin generates an activation token for a seat member 2. The token is set as the `DBCODE_ACTIVATION_TOKEN` environment variable in the container 3. On startup, DBCode exchanges the token for a license (7-day expiry) 4. When the license nears expiry, DBCode automatically re-activates using the same token 5. If the token is revoked, the license is cleared on the next renewal attempt ### Requirements - A team subscription with 2 or more seats - The person generating the token must be the account owner or an admin - The container must have outbound network access to `https://dbcode.io` ### Generating a Token **1. Open DBCode in Visual Studio Code** Launch Visual Studio Code and click the DBCode icon from the Activity Bar on the left. **2. Navigate to the Account Tab** In the DBCode sidebar, click on the **Account** tab and expand your license details. **3. Open the Seats Section** Expand the **Seats** section to see your team members. **4. Generate Token** Right-click on the team member you want to generate a token for and select **Generate Activation Token**. The token will be copied to your clipboard. :::caution Each time you generate a new token for a seat, the previous token for that seat is automatically revoked. Only one active token exists per seat at any time. ::: ### Setting the Environment Variable Set the token in your container configuration. The exact method depends on your container platform: **Docker:** ```bash docker run -e DBCODE_ACTIVATION_TOKEN=eyJhbGciOi... your-image ``` **Docker Compose:** ```yaml services: dev-environment: image: your-image environment: - DBCODE_ACTIVATION_TOKEN=eyJhbGciOi... ``` **Kubernetes:** ```yaml env: - name: DBCODE_ACTIVATION_TOKEN valueFrom: secretKeyRef: name: dbcode-secrets key: activation-token ``` The token is a JWT string and should be treated as a secret. Store it in your platform's secret management system rather than in plain text configuration files. ### Revoking a Token Right-click on the team member in the Seats section and select **Revoke Activation Token**. The token is invalidated immediately on the server. The next time the extension tries to refresh the license (on any API call or permission sync), it detects the revocation and clears the license. ### Token Lifecycle - **Set once:** The token does not expire. Set it in your container config and it works until revoked. - **Renewal:** When the 7-day license nears expiry, DBCode re-activates using the token automatically. No manual renewal needed. - **Revocation:** Generating a new token or explicitly revoking one invalidates the previous token. The next time the extension attempts to refresh the license, it detects the revocation, clears the license, and blocks access. - **Container restarts:** The license is cached locally. On restart, DBCode uses the cached license and re-activates if it has expired. ### Team Roles When a license is activated via token, [team roles](/docs/accounts/team-roles) are automatically applied. If the seat member has a role assigned (e.g., restricted, no-export), those restrictions are enforced in the container environment. Role changes made by the admin take effect within 12 hours. ## Require License Mode Setting `DBCODE_REQUIRE_LICENSE=true` prevents DBCode from functioning without a valid license. When set and no license is available, all functionality is blocked, including connecting to databases, running queries, and browsing schemas. This is useful for enforcing company policy in managed environments where you want to ensure team members only use DBCode with a properly licensed and configured account. ### Setting the Environment Variable ```bash DBCODE_REQUIRE_LICENSE=true ``` ### Combining with Activation Tokens The typical setup uses both variables together: ```bash DBCODE_ACTIVATION_TOKEN=eyJhbGciOi... DBCODE_REQUIRE_LICENSE=true ``` This ensures the license is automatically activated and that DBCode cannot be used if the activation fails (e.g., network issues, revoked token). ### Behavior When Blocked When `DBCODE_REQUIRE_LICENSE` is set and no valid license is found: - An error message is displayed: "DBCode requires a valid license to operate in this environment" - All database connections are blocked - All features (including core features) are unavailable - The extension sidebar remains visible but non-functional If a license is obtained later (via activation token, sign-in, or offline license), the block is lifted and full functionality is restored. ## Comparison with Other Activation Methods | Method | Best For | Network Required | Machine Bound | |---|---|---|---| | **Activation Token** | Containers, automated environments | Yes (on startup + on expiry) | No (new license per machine) | | **Sign In** (GitHub/Microsoft) | Interactive development | Yes (on sign-in) | No | | **Offline License** | Air-gapped machines | Only during activation | Yes | For air-gapped containers with no network access, activation tokens will not work. Use [offline license activation](/docs/accounts/offline-license) instead, though note that offline licenses are machine-bound and will not persist across ephemeral containers. ## Troubleshooting ### "Activation token exchange failed" - Verify the container has outbound HTTPS access to `dbcode.io` - Check that the token was copied correctly (it should start with `eyJ`) - Verify the token has not been revoked (ask your team admin to generate a new one) ### "Activation token has been revoked" A new token was generated for the same seat, or the token was explicitly revoked by an admin. Get a new token from your team admin and update the environment variable. ### "DBCode requires a valid license" This appears when `DBCODE_REQUIRE_LICENSE=true` is set and no license could be obtained. Check: - Is `DBCODE_ACTIVATION_TOKEN` also set? - Can the container reach `dbcode.io`? - Is the team subscription active? ### License Not Renewing If the license stops working: - Verify the container can still reach `dbcode.io` - Check that the activation token has not been revoked (ask your team admin) - Restart VS Code to trigger an immediate re-activation attempt ### Team Roles Not Applied If feature restrictions from team roles are not being enforced: - Roles require network access to sync - Restart VS Code to force an immediate permission sync - Verify the seat has a role assigned in the [team seats](/docs/accounts/team-seats) panel ## Need Help? If you encounter issues with container deployment, contact [help@dbcode.io](mailto:help@dbcode.io) for assistance. --- ## Docs > Accounts > Offline License ### Offline License Activation In air-gapped systems or corporate environments where direct access to authentication providers (like Microsoft, GitHub, and Google) or to DBCode servers is restricted, you can use the offline license activation process. ## Overview The offline license activation process involves the following steps: 1. Generate a machine key on the air-gapped or restricted machine 2. Use the activation URL on a connected device to sign in and generate a license 3. Install the license on the air-gapped machine ## Flow Diagram ![Offline License Activation Flow Diagram](./flow.svg) ## Step-by-Step Instructions ### Step 1: Generate Key (on the air-gapped machine) 1. Open Visual Studio Code 2. Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) 3. Type and select **DBCode: Generate Key for License** 4. An activation URL will be displayed along with your machine key 5. Copy this URL to transfer to a connected device (via USB drive, etc.) ### Step 2: Generate a License (on a connected device) 1. Open a web browser on any device with internet access 2. Visit the activation URL you copied in Step 1 3. Sign in using one of the following providers: - **GitHub** - Use your GitHub account - **Google** - Use your Google account - **Microsoft** - Use your Microsoft account 4. After signing in, your license will be automatically generated and displayed 5. Copy the license key shown on the page 6. Transfer this license to your air-gapped machine (via USB drive, etc.) ### Step 3: Install the License (on the air-gapped machine) 1. Open Visual Studio Code on your air-gapped machine 2. Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) 3. Type and select **DBCode: Install License** 4. Enter the license key that you copied from the web activation page 5. If successful, you will see a confirmation message that the license has been installed ## Troubleshooting ### Invalid License If you receive an "Invalid License" error: - Verify that you've copied the entire license without any missing characters - Check that the machine key used to generate the license matches the current machine - Ensure your subscription is active - Make sure you're using the license on the same machine where the key was generated ### Expired License Offline licenses are tied to your subscription period. If your subscription expires or renews, you'll need to: 1. Generate a new machine key on your air-gapped machine 2. Visit the activation URL on a connected device 3. Sign in and generate a new license 4. Install the new license on the air-gapped machine ### Machine Key Changes If your machine's hardware configuration changes significantly, a new machine key might be generated. In this case: 1. Generate a new machine key using **DBCode: Generate Key for License** 2. Use the new activation URL to generate a new license 3. Install the new license on your machine ### Can't Access the Activation URL If you cannot access the activation URL on a connected device: - Verify the URL was copied correctly and includes the full `machineId` parameter - Try accessing the URL from a different browser or device - Ensure the connected device has internet access :::caution Offline licenses are machine-bound and will not persist across ephemeral containers where the machine ID changes on each boot. For container and automated deployments, use [activation tokens](/docs/accounts/container-deployment) instead. ::: ## License Management - Each license is valid for a single machine and is tied to your machine's unique identifier - You can generate one offline license every 30 days - Licenses are valid for the duration of your subscription period - If you need to generate licenses more frequently, please contact [help@dbcode.io](mailto:help@dbcode.io) --- ## Docs > Accounts > Sign In ### Sign In Sign in to DBCode using Visual Studio Code's built-in authentication with GitHub or Microsoft, keeping your credentials secure. When you sign in for the first time, your free trial begins. After the trial ends, you'll need a license to access DBCode's full features. ### How to Sign In **1. Open DBCode in Visual Studio Code** - Launch Visual Studio Code and click the DBCode icon from the Activity Bar on the left. **2. Navigate to the Account Tab** - In the DBCode sidebar, locate and click on the **Account** tab. ![Account Tab](./account-tab.png) **3. Select the Sign-In Option** - Click on the **Sign-In** button within the **Account** tab. ![Sign In Button](./sign-in.png) **4. Choose How to Sign In** - Pick an option from the prompt. **Sign in with GitHub** and **Sign in with Microsoft** use Visual Studio Code's built-in authentication; **Sign in via the Web** works with Microsoft, Google, GitHub, or email. **Offline Activation** generates a machine key for air-gapped setups. ![Select how to sign in](./select-provider.png) **5. Complete the Sign-In** - Approve any permission prompt Visual Studio Code shows, then finish signing in with your chosen provider. ### Changing Your Sign-In Method To switch to a different sign-in provider, sign out and sign back in. You'll be presented with all available options. ### **How to Sign Out** **1. Open DBCode in Visual Studio Code** - Launch Visual Studio Code and click the DBCode icon in the Activity Bar. **2. Access the Account Tab** - Go to the **Account** tab in the DBCode sidebar. **3. Click Sign-Out** - Click the **Sign-Out** icon next to your account details. ![Sign Out Button](./sign-out.png) - You will be logged out successfully. --- ## Docs > Accounts > Team Roles ### Team Roles Team roles let you control which DBCode features your team members can use. Each team member is assigned a role that determines their access level. This is useful for enforcing company policies around data handling, AI usage, and information sharing. ## How Roles Work Every team member has exactly one role. The role determines two things: 1. **Team management access** - whether they can manage seats and assign roles (admin only) 2. **Feature access** - which DBCode features they can use When a feature is restricted by a role, the team member sees it as disabled with a "Restricted by your team role" message. Features are never hidden, just disabled, so there is no confusion about what is available. ## Built-in Roles DBCode includes four built-in roles that cover common configurations: | Role | Team Management | Feature Restrictions | |------|----------------|---------------------| | **admin** | Can manage team members and assign roles | None (full access) | | **member** | No management access | None (full access) | | **no-export** | No management access | Data Export, Data Copy, Data Share | | **restricted** | No management access | AI, History Sync, Data Export, Data Copy, Data Share | Built-in roles cannot be modified or deleted. They serve as ready-made configurations for common use cases. ## Custom Roles If the built-in roles don't fit your needs, you can create custom roles with any combination of restrictions. Custom roles can restrict the following features: | Feature | Key | What It Controls | |---------|-----|-----------------| | **AI** | `ai` | All AI features (or restrict individually below) | | **AI Completions** | `ai.completions` | Inline SQL completions as you type | | **AI Analysis** | `ai.analysis` | Query explanations and execution plan analysis | | **AI Query Builder** | `ai.queryBuilder` | AI-assisted query construction | | **AI Explore** | `ai.explore` | AI-powered data exploration | | **AI Grid** | `ai.grid` | AI assistance in the data grid | | **History Sync** | `historySync` | Cloud sync of query history across devices | | **Data Export** | `dataExport` | Export to CSV, Excel, JSON, Parquet, and other formats | | **Data Copy** | `dataCopy` | Copy cells and rows from the data grid to clipboard | | **Data Share** | `dataShare` | Share data and reports via shareable links | Restricting a parent feature (like AI) automatically restricts all its sub-features. You can also restrict sub-features individually if you want more granular control. For example, you might allow AI completions but restrict AI analysis. ## Managing Roles ### Viewing Roles In the Account tab, expand your license details. If you have a team subscription and are an owner or admin, you will see a **Roles** section listing all available roles (built-in and custom). ### Creating a Custom Role 1. Click the **+** icon next to the Roles heading 2. A role editor will open. Enter a name for your role 3. Uncheck the features you want to restrict 4. Click **Create** ### Editing a Custom Role 1. Click the **pencil** icon next to the role you want to edit, or click the role name 2. The role editor will open showing the current configuration 3. Modify the name or feature restrictions as needed 4. Click **Save** ### Deleting a Custom Role 1. Click the **trash** icon next to the custom role you want to delete 2. Confirm the deletion When a custom role is deleted, any team members assigned to that role will revert to full access (equivalent to the member role). ### Viewing Built-in Roles Click any built-in role to open the role editor in read-only mode. This lets you see exactly what each built-in role restricts without being able to modify it. ## Assigning Roles To assign a role to a team member: 1. In the Seats section, find the team member 2. Click the **shield** icon next to their name 3. Select a role from the list The role takes effect on the team member's next extension activation or within 12 hours (the permission refresh interval). Restarting VS Code will apply the change immediately. ### Changing Roles Assigning a new role replaces the previous one. For example, changing someone from admin to no-export removes their team management access and adds the export restrictions. ### The Owner Role The account owner always has full access and their role cannot be changed. The owner is the person who created the subscription. ## Policy Tool, Not a Security Boundary Team roles are a policy enforcement tool designed to help organizations manage how their team uses DBCode. They prevent accidental misuse and help enforce company guidelines around data handling and AI usage. :::caution Roles are **not** a security boundary. They enforce policy within the extension, but a user could work around restrictions by: - Signing out of their team account - Using another database client or tool - Accessing the database directly outside of DBCode For sensitive data protection, always use database-level access controls (grants, row-level security, network restrictions, etc.) as your primary security mechanism. Roles complement database security but do not replace it. ::: Think of roles as the equivalent of a company policy document, but enforced automatically within the tool, rather than relying on people to remember and follow the rules. ## How Restrictions Are Enforced When a feature is restricted: - **AI features** - Completions stop appearing, AI assist commands show a restriction message - **History Sync** - The sync toggle is disabled, local history continues to work normally - **Data Export** - Export menu items and commands show a restriction message - **Data Copy** - Clipboard copy from the data grid is blocked - **Data Share** - Share options show a restriction message In all cases, the user sees "Restricted by your team role" so they understand why the feature is unavailable. ## Storage and Privacy Role definitions and assignments are stored in your Stripe subscription metadata alongside your existing team seat data. No separate database or third-party service is involved. Role assignments are cached locally on each team member's machine and refreshed every 12 hours. ## Requesting Additional Features If you need to restrict features not currently available in the role system, let us know at [help@dbcode.io](mailto:help@dbcode.io?subject=Restrict team features). We are actively expanding the list of features that can be managed through roles. --- ## Docs > Accounts > Team Seats ### Managing Team Seats If you have a team subscription, you can add, edit, and remove team members, change their roles, and adjust the number of seats on your subscription. ## Prerequisites - A team subscription (2 or more seats) - You must be the account owner or an admin ## Opening the Seats Section In the DBCode sidebar, open the **Account** tab and expand **License**. If you have a team subscription, you will see a **Seats** entry showing your current allocation (for example, "3 / 5" means 3 of 5 seats assigned). Expand it to see your team members. ![Account Tab](./account-tab.png) ## Adding a Team Member 1. Click the **+** icon next to the Seats heading 2. Enter the team member's email address and press Enter The new seat appears in the list. Adding fails if you have already assigned every seat in your subscription, see [Adding More Seats](#adding-more-seats) below. ## Editing a Team Member's Email 1. Click the **pencil** icon next to the team member 2. Update the email address and press Enter ## Removing a Team Member 1. Click the **trash** icon next to the team member 2. Confirm the deletion The team member loses access on their next extension activation, or within 12 hours. ## Team Roles Each seat is assigned a role that controls feature access. Roles are shown next to each email in the Seats section. To change a member's role, click the **shield** icon next to their name and select a role from the list. DBCode includes built-in roles (admin, member, no-export, restricted) and supports custom roles. See [Team Roles](/docs/accounts/team-roles) for the full list of features that can be restricted and how to create custom roles. Role changes take effect on the team member's next extension activation, or within 12 hours. ## Adding More Seats Seat count, payment details, plan changes, and cancellation are all handled through the **Stripe customer portal**. There are two ways to open it: ### From the Account tab (online licenses) 1. In the Account tab, expand **License** 2. Click the **pencil** (edit) icon next to the License entry 3. The Stripe customer portal opens in your browser 4. Update your subscription quantity ### Direct link (offline licenses, or as a fallback) If the edit icon is not available (for example on an [offline license](/docs/accounts/offline-license)), open the portal directly from the [Stripe customer portal](https://billing.stripe.com/p/login/7sI9CvdM73SJ7M45kk). Enter the email address on your subscription and Stripe will email you a one-time link to access the portal. Billing is prorated automatically. After the change goes through in Stripe, click the **refresh** icon at the top of the Account view to pull the new seat count into the extension. The license also refreshes on its own periodically, but the manual refresh is the fastest way. Once the new total is showing, use the **+** icon under Seats to assign them. ## Managed Team Members If you were invited to someone else's team account, you will see "Managed by: [owner's email]" in your License details. What you can do depends on your role: - **Admin** - can add, edit, and remove team members, but cannot change roles or access billing - **Member** - cannot manage the team, only uses the subscription benefits ## Troubleshooting ### "A valid email is required" when adding or editing a seat Check the address is correctly formatted with no extra spaces or characters, and that the domain is valid. ### Adding a seat fails Likely causes: - All seats in your subscription are already assigned. Add more seats through the [customer portal](#adding-more-seats) - The email address is already on another seat - Your subscription is no longer active If none of those apply, sign out and back in to refresh your license, then try again. ### Changes don't appear The Seats section refreshes automatically after each change made inside DBCode. For changes made outside the extension (such as updating seat count in the Stripe portal), click the **refresh** icon at the top of the Account view to pull the latest license. If something still looks stale, sign out and back in. ### Can't change roles or manage seats Only the account owner can change roles. Admins can add, edit, and remove seats but cannot change roles. If you are an admin and the seat management options are missing, the owner may have changed your role, check with them. Signing out and back in refreshes your permissions. --- ## Docs > Ai ### Models and Configuration DBCode uses AI models to provide inline code completion, natural language query generation, execution plan analysis, and other intelligent features. You can bring your own model, use GitHub Copilot, or rely on DBCode's hosted models. ## AI Providers DBCode supports three AI providers, checked in order on startup: 1. **Custom Model** — any OpenAI-compatible API you configure (Ollama, OpenAI, Groq, etc.) 2. **GitHub Copilot** — if installed and active in VS Code 3. **DBCode AI** — hosted models, always available as fallback DBCode automatically detects the best available provider. If you've configured a custom model endpoint, it becomes the primary provider. Otherwise, GitHub Copilot is used if available, with DBCode AI as the final fallback. ### Switching Providers To change providers at any time: 1. Open the Command Palette (F1 or Cmd/Ctrl+Shift+P) 2. Run: **DBCode: Choose AI Provider** 3. Select your preferred provider ### Provider Fallback If your active provider fails (server unreachable, model error, etc.), DBCode offers to fall back to the next available provider: - For **inline completions**, the fallback happens silently with an info notification. - For **interactive features** like execution plan analysis, a confirmation dialog is shown before switching. To disable fallback and lock to your custom model, enable `dbcode.ai.customModel.only`. ## Custom Model Use your own AI model — local (Ollama, LM Studio) or cloud (OpenAI, Groq, Together) — via any OpenAI-compatible endpoint. See the dedicated [Custom Provider](/docs/ai/custom-provider) guide for full setup instructions. **Quick setup:** ```json { "dbcode.ai.customModel.endpoint": "http://localhost:11434", "dbcode.ai.customModel.model": "qwen2.5-coder:7b" } ``` For cloud APIs that require authentication, run **DBCode: Set Custom Model API Key** from the Command Palette. The key is stored securely in your OS keychain via VS Code's SecretStorage. ## GitHub Copilot **Requirements:** - GitHub Copilot extension installed in VS Code - Active GitHub Copilot subscription (Individual, Business, or Enterprise) When available, DBCode uses Copilot's models to provide schema-aware SQL suggestions and execution plan analysis. ### Changing the Copilot Model 1. Open the Command Palette (F1 or Cmd/Ctrl+Shift+P) 2. Run: **DBCode: Change AI Model** 3. Select from the available Copilot models Your selection is saved to `dbcode.ai.modelId`. ### Provide Schema Context to GitHub Copilot When using Copilot for inline completion, DBCode provides your database schema for more accurate SQL suggestions. **To enable this (recommended):** 1. Open Settings (Cmd/Ctrl+,) 2. Search for `github.copilot.enable` 3. Add `sql` to the object with a value of `false` This tells Copilot to defer to DBCode for SQL file completions, allowing DBCode to provide schema context. ```json { "github.copilot.enable": { "*": true, "sql": false } } ``` When you first enable inline completion with Copilot installed, DBCode will prompt you to configure this automatically. ## DBCode Hosted Models When neither a custom model nor GitHub Copilot is available, DBCode uses its own hosted models. **Important:** Hosted models are used for **inline completion and execution plan analysis only**. They are not used for Copilot Tools or MCP. DBCode uses purpose-specific models running on [Cloudflare Workers AI](https://developers.cloudflare.com/workers-ai/): | Feature | Model | Purpose | |---------|-------|---------| | Inline Completion | **Llama 3.1 8B** (Cloudflare Workers AI) | Fast, schema-aware SQL completions | | Execution Plan Analysis | **GPT-oss 120B** (Cloudflare Workers AI) | Deep analysis of query performance | ### Limitations - Require internet connectivity - Inline completions are simpler compared to Copilot or larger custom models - Execution plan analysis quality depends on the complexity of the plan ## Inline Completion Inline completion can be enabled or disabled independently: 1. Open Settings (Cmd/Ctrl+,) 2. Search for `dbcode.ai.inlineCompletion` 3. Uncheck to disable When disabled, DBCode won't provide automatic SQL suggestions as you type. You can still use Copilot Tools and MCP for natural language queries. ## AI Features Model Usage Different features use different providers depending on your configuration: | Feature | Provider | Data Shared | |---------|----------|-------------| | Inline Completion | Custom Model, Copilot, or DBCode AI | Schema only | | Execution Plan Analysis | Custom Model, Copilot, or DBCode AI | Execution plan, SQL query, and schema | | Copilot Tools | GitHub Copilot only | Schema AND actual data | | MCP | External client's model | Schema AND actual data | When a custom model is configured, it is used for inline completion and execution plan analysis. Copilot Tools and MCP are unaffected — they always use their respective model sources. See [Privacy and Security](/docs/ai/privacy-and-security) for detailed information on what data is sent to each provider. ## Troubleshooting ### "No language models found" Error This may appear when: - GitHub Copilot is not installed and no custom model is configured **Solution:** Configure a [Custom Provider](/docs/ai/custom-provider), install GitHub Copilot, or DBCode will fall back to its hosted model automatically. ### Model Selection Dialog Keeps Appearing 1. Check that GitHub Copilot extension is still installed 2. Verify your Copilot subscription is active 3. Try clearing `dbcode.ai.modelId` in settings to allow automatic selection ### Inline Completions Not Working 1. Verify inline completion is enabled: `dbcode.ai.inlineCompletion` 2. Ensure the file has a database connection assigned 3. Check your internet connection (all providers except local custom models require connectivity) 4. If using Copilot, verify it's configured to let DBCode handle SQL files (see [Provide Schema Context](#provide-schema-context-to-github-copilot)) ## Related Documentation - [Custom Provider](/docs/ai/custom-provider) - Use your own AI model - [Privacy and Security](/docs/ai/privacy-and-security) - Data handling and privacy considerations - [Inline Completion](/docs/query/inline-completion) - Using inline SQL suggestions - [Copilot Tools](/docs/ai/copilot-tools) - Natural language database queries - [MCP](/docs/ai/mcp) - Connecting external AI clients --- ### Privacy and Security When using AI features in DBCode, it's important to understand what information is shared, where it goes, and what privacy protections apply. This guide covers the security model for all DBCode AI features. ## What Information is Shared DBCode's AI features share different types of information depending on which feature you use. Understanding what gets shared helps you make informed security decisions. ### Schema Information (Inline Completion, Schema Queries) For inline completion and when asking Copilot/MCP to read table structures, DBCode shares simplified database schema information: - Table and view names - Column names and data types - Primary key definitions - Foreign key relationships - Comments on tables and columns (if present) **No actual data values are sent** for these features. ### Schema AND Data Values (Copilot Tools, MCP Query Execution) When you ask Copilot Tools or MCP clients to execute queries, DBCode sends: - **Schema information** (as above) - **Actual query results** including data values from your database This allows the AI to analyze your data, answer questions about specific records, and help you interpret results. ### What is NEVER Shared Regardless of which feature you use, DBCode NEVER sends: - Database credentials or passwords - Connection strings or server addresses - User information or access control settings - Data you didn't explicitly ask the AI to query ### Examples: What Gets Sent **For Inline Completion (schema only):** When you use inline completion, DBCode sends a simplified CREATE TABLE representation: ```sql CREATE TABLE users ( id INTEGER PRIMARY KEY, email VARCHAR(255), created_at TIMESTAMP ); CREATE TABLE orders ( id INTEGER PRIMARY KEY, user_id INTEGER, total DECIMAL(10,2), status VARCHAR(50) ); ALTER TABLE orders ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id); ``` **For Copilot Tools / MCP Query Execution (schema AND data):** When you ask Copilot to execute a query like "Show me the top 5 orders", DBCode sends: 1. The schema (as above) 2. The actual query results: ```json { "columns": ["id", "user_id", "total", "status"], "rows": [ [1, 123, 299.99, "completed"], [2, 456, 149.50, "pending"], [3, 123, 89.99, "completed"], ... ] } ``` This includes actual data values from your database. ## Data Flow by Feature Different DBCode features send schema information to different destinations. Understanding the flow helps you assess your security posture. ### Inline Completion **Data Flow:** 1. You type in a SQL file or notebook 2. DBCode retrieves schema for the active database connection 3. Schema is sent to one of: - **Your custom model endpoint** (if configured, see [Custom Provider](/docs/ai/custom-provider)), OR - **GitHub Copilot's API** (if Copilot is installed and active), OR - **DBCode's hosted model** (fallback) 4. Model generates SQL suggestion 5. Suggestion appears in your editor **Privacy Model:** - Custom model: Data goes to whichever endpoint you configured. For local models (Ollama, LM Studio), data never leaves your machine. - GitHub Copilot: Follows GitHub's privacy policies ([GitHub Copilot Trust Center](https://resources.github.com/copilot-trust-center/)) - DBCode hosted models: Follows DBCode's privacy policy (see [DBCode Hosted Models Privacy](#dbcode-hosted-models-privacy)) - Schema is cached locally to reduce API calls - Cache is cleared when database schema changes ### Copilot Tools **Data Flow:** ``` DBCode → GitHub Copilot API (using your authenticated account) → Response ``` 1. You ask GitHub Copilot a question in chat 2. Copilot uses DBCode tools to request information 3. DBCode sends data directly to GitHub Copilot's API: - **Schema information** (table/column names) when reading table structures - **Actual data values** when executing queries (SELECT, INSERT, UPDATE, DELETE, DDL) 4. Copilot generates response using your GitHub account context **Privacy Model:** - DBCode does not run its own intermediary service - Your data never passes through DBCode's servers - it goes directly to GitHub Copilot - Data is sent using your authenticated GitHub account - Follows GitHub's privacy policies ([GitHub Copilot Trust Center](https://resources.github.com/copilot-trust-center/)) - Data (both schema and query results) sent on-demand when you explicitly ask Copilot **Important:** Unlike inline completion (which only sends schema), Copilot Tools can send actual data values when you ask it to execute queries and return results. ### MCP (Model Context Protocol) **Data Flow:** 1. An MCP client connects to DBCode: either the editor's built-in MCP host (VS Code Copilot, Cursor) via DBCode's auto-registered stdio bridge, or an external client (Claude Desktop, Copilot CLI, etc.) via DBCode's HTTP server. 2. AI asks DBCode for information using MCP tools. 3. DBCode provides data only when explicitly requested: - **Schema information** (table/column names) when reading table structures - **Actual data values** when executing queries 4. AI generates response using whatever model the client provides. **Access gating:** - **In VS Code and Cursor (auto-registered):** The IPC channel is reachable only by same-user processes on your machine. - **HTTP server (external clients):** gated by `dbcode.ai.mcp.authorization`: OAuth (default) or None. With OAuth, the editor shows a per-client approval dialog on first connection; the client receives a token it reuses for subsequent requests. **Why `None` exists, and when not to use it.** A few MCP clients still cannot complete an OAuth flow against a localhost server. `None` is there for them, and for scripted local development. It means any process on your machine that can reach the port can call the tools, which includes running queries against your connections. Treat it the way you would treat an unauthenticated local database: - Leave it on `OAuth` unless a client genuinely cannot do OAuth. - Never combine `None` with `dbcode.ai.mcp.allowExternalConnections`, which binds the server beyond loopback. That pair exposes your connections to your network. - On a shared or multi-user machine, `None` is not appropriate at all. - Pin it in policy if you want it unavailable: set `dbcode.ai.mcp.authorization` to `OAuth` in a machine-scoped settings file so a user cannot lower it. **Privacy Model:** - Follows the connected client's privacy policy (varies by client: Copilot, Claude, GPT-4, etc.). - Data (both schema and query results) is sent on-demand when the AI executes tools. **Note:** MCP allows you to use different AI models (Claude, GPT-4, etc.) through whatever client you connect. The model used is determined by your MCP client, not by DBCode. Like Copilot Tools, MCP can send actual data values when executing queries. ## DBCode Hosted Models Privacy DBCode uses purpose-specific hosted models for six features. Every one of them runs on [Cloudflare Workers AI](https://developers.cloudflare.com/workers-ai/), on Cloudflare's own infrastructure. There is no third-party model provider and no model gateway that can route your request elsewhere: the model ids below are Cloudflare-hosted (`@cf/…`) and are called through the Workers AI binding. **Important:** Copilot Tools and MCP never use these hosted models. They require GitHub Copilot or an external AI client respectively, and their data goes to that client's model, not to ours. ### Models Used | Feature | Model | Model id | |---------|-------|----------| | Inline Completion | Llama 3.1 8B (fp8) | `@cf/meta/llama-3.1-8b-instruct-fp8-fast` | | Execution Plan Analysis | GPT-oss 120B | `@cf/openai/gpt-oss-120b` | | AI Query Builder | GPT-oss 120B | `@cf/openai/gpt-oss-120b` | | AI Assist | GPT-oss 120B | `@cf/openai/gpt-oss-120b` | | AI Data Grid | GPT-oss 120B | `@cf/openai/gpt-oss-120b` | | AI Data Explore | GPT-oss 120B | `@cf/openai/gpt-oss-120b` | Inline completion uses the smaller, faster model because it runs as you type. The rest use the larger reasoning model. ### Data Flow ``` DBCode → dbcode.io API → Cloudflare Workers AI → Response ``` Nothing else sits in that path. Requests are attributed per feature in Cloudflare AI Gateway for usage analytics only; the gateway does not select or substitute the model. ### What Data Is Sent **Inline Completion:** - Database schema (table/column names, types, relationships) - The SQL prefix and suffix around your cursor position **Execution Plan Analysis:** - The query execution plan (EXPLAIN/ANALYZE output) - The original SQL query - Database schema (when available) - Database dialect (e.g., PostgreSQL, MySQL) **AI Query Builder, AI Assist:** - Database schema and dialect - Your natural-language prompt **AI Data Grid, AI Data Explore:** - Database schema and dialect - Your natural-language prompt - **Query results**: the actual data values for the rows in the grid or chart you are working on ### Data Handling - Data is sent to DBCode's API, then to Cloudflare Workers AI over encrypted HTTPS - No persistent storage of schema, queries, or execution plans by DBCode or Cloudflare - Requests are processed and discarded - No model training using customer data - Complies with [DBCode's privacy policy](https://dbcode.io/legal/privacy-policy) ### When Hosted Models Are Used **Inline Completion** uses the hosted model automatically when: - GitHub Copilot extension is not installed - GitHub Copilot subscription is inactive or expired - You explicitly choose the hosted model over Copilot **Execution Plan Analysis** uses the hosted model when: - You request AI analysis from the Plan Explorer **AI Query Builder, AI Assist, AI Data Grid and AI Data Explore** use the hosted model when you invoke that feature and no custom provider is configured. Each one is an explicit action: nothing is sent in the background. **Note:** If you want to use Copilot Tools or MCP features, you must have GitHub Copilot installed (for Copilot Tools) or an external AI client configured (for MCP). Hosted models cannot be used for these features. ### Turning Them Off Every hosted-model feature can be disabled, or pointed at infrastructure you control: - `dbcode.ai.inlineCompletion` turns inline completion off. - `dbcode.ai.customModel.endpoint` plus `dbcode.ai.customModel.only` sends every AI request to an endpoint you choose, including a local one such as Ollama, and the `only` flag stops DBCode falling back to the hosted model if yours is unreachable. See [Custom Provider](/docs/ai/custom-provider). - Not invoking the feature means no request. None of these run on a timer or in the background. For a single list of every domain DBCode can contact, and how to switch each one off, see [Network Egress](/docs/security/network-egress). ### Privacy Considerations Hosted models send data to DBCode's servers and to Cloudflare Workers AI. Consider this when deciding whether to use AI features with sensitive databases. ## Disabling AI Features You can selectively disable AI features while keeping other DBCode functionality. ### Disable Inline Completion **Via Settings:** 1. Open Settings (Cmd/Ctrl+,) 2. Search for `dbcode.ai.inlineCompletion` 3. Uncheck the checkbox **Via settings.json:** ```json { "dbcode.ai.inlineCompletion": false } ``` ### Disable Copilot Tools Copilot Tools are only active when you explicitly use them. If you want to prevent accidental usage: 1. Don't enable agent mode in GitHub Copilot chat 2. Don't drag DBCode tables/databases into Copilot chat 3. Copilot Tools won't be invoked unless explicitly requested ### Disable MCP DBCode exposes MCP through two paths: **HTTP server** (off by default, only used for external clients like Claude Desktop, Copilot CLI, Dev Containers, LAN). To keep it disabled: 1. Leave `dbcode.ai.mcp.autoStart` set to `false`. 2. Don't run `DBCode: MCP Start HTTP Server` from the command palette. 3. Remove any MCP client configurations pointing to `http://localhost:5002/mcp`. **Auto-registered path** (used by VS Code Copilot and Cursor's built-in chat). Tool execution is gated by your DBCode sign-in: a signed-out user can't run any MCP tool. To stop MCP from being available at all, sign out of DBCode, or uninstall/disable the DBCode extension. In both paths, DBCode does not send schema or data unless an AI client explicitly invokes a tool. ## Data Residency ### DBCode Hosted Models DBCode's hosted models run on Cloudflare Workers AI, on Cloudflare's own infrastructure (no third-party model provider). Data flows through: 1. DBCode's API (hosted on Cloudflare Workers) 2. Cloudflare Workers AI Check [Cloudflare's Workers AI data usage policy](https://developers.cloudflare.com/workers-ai/platform/data-usage/) for current data handling and residency information. ### GitHub Copilot Data sent to GitHub Copilot is processed according to GitHub's infrastructure. Check [GitHub's Copilot Trust Center](https://resources.github.com/copilot-trust-center/) for current data residency and privacy information. ### MCP Clients Data residency for MCP depends on which external AI client you use. Each client (Cursor, Claude Desktop, etc.) has its own infrastructure and data handling policies. ## Frequently Asked Questions ### Does DBCode send my query results to AI models? It depends on which feature you use: - **Inline Completion:** No - only schema (table structure) is sent - **Copilot Tools:** Yes - when you ask Copilot to execute queries, actual data values are sent to GitHub Copilot - **MCP:** Yes - when the AI executes queries, actual data values are sent to the external client's model You have full control - data is only sent when you explicitly ask the AI to execute a query. ### Can I use AI features offline? It depends on your provider: - **Custom model (local)**: Yes - if you're running a local model server like Ollama or LM Studio, no internet connection is needed - **Custom model (cloud)**: No - requires connection to the remote API - **GitHub Copilot**: No - requires connection to GitHub's Copilot API - **DBCode hosted model**: No - requires connection to DBCode's servers - **MCP**: No - requires connection to both DBCode's MCP server and the external AI client's services ### What happens if my database credentials are in environment variables or connection strings? Database credentials are never sent to AI models. Only schema information is transmitted. Connection credentials remain local to your VS Code instance. ### Does enabling Copilot Tools mean my schema is always being sent to GitHub? No. Schema is sent only when you explicitly ask Copilot to read your database structure or execute queries. It's not automatically transmitted. ### How is the MCP server authenticated? DBCode's MCP server uses OAuth 2.1 by default. You must approve each client that wants to connect via an approval dialog in VS Code. This ensures only authorized AI clients can access your schema. ### Can I see what schema information will be sent? Yes, in the panel itself, before you send anything. Every AI panel lists what it is about to include on a line directly beneath the input box: the model it will use, and each piece of context it will attach. Context entries are links. Click **schema** and the exact DDL that will be sent opens inline, so you are reading the real payload rather than an approximation of it. Click it again to collapse. The schema is sent as simplified `CREATE TABLE` statements: table names, column names, types and relationships. No rows. Where a feature also sends data values, AI Data Grid and AI Data Explore, those appear as their own context entry on the same line and are previewable the same way. If a context entry is not listed there, it is not being sent. ### What if I have table/column names that reveal sensitive business information? This is a valid concern. Table names like `secret_projects` or column names like `classified_clearance_level` may reveal information you don't want shared. Options: 1. Use generic aliases in development databases 2. Disable AI features for those specific databases 3. Review your organization's policies on what can be shared with external AI services ## Related Documentation - [Models and Configuration](/docs/ai/models-and-configuration) - How to configure and select AI models - [Custom Provider](/docs/ai/custom-provider) - Use your own AI model - [Inline Completion](/docs/query/inline-completion) - Using inline SQL suggestions - [Copilot Tools](/docs/ai/copilot-tools) - Natural language database queries - [MCP](/docs/ai/mcp) - Connecting external AI clients ## External Resources - [GitHub Copilot Trust Center](https://resources.github.com/copilot-trust-center/) - [DBCode Privacy Policy](https://dbcode.io/legal/privacy-policy) --- ## Docs > Ai > Ai Assist ### AI Assist for Data Grid AI Assist is a single conversational panel in the data grid. There's no mode to switch - ask for whatever you want, and the panel decides what to do. It answers **data requests** (which rows, aggregates, or derived results to fetch) by writing SQL, and **presentation requests** (how the currently loaded data is displayed) by changing the grid or chart directly, all in the same conversation. ![AI Assist panel open in the data grid sidebar with a natural language prompt](./ai-assist-panel.png) ## Getting Started 1. Open a table, or run a query so results appear in the data grid 2. Open the AI Assist panel from the grid sidebar (sparkle icon) 3. Type a natural language request and press Enter AI Assist uses the same AI provider configured in your [AI settings](/docs/ai/models-and-configuration). Any model that supports structured JSON output works - including GitHub Copilot, OpenAI, Anthropic, Ollama, and custom providers. ## How AI Assist Decides What To Do Whether AI Assist can write SQL depends on where the loaded data came from: - **When the data can be re-queried** - an open table, or query results tied to a table - AI Assist writes SQL for data requests and applies grid or chart changes for presentation requests. SQL is used for anything about which data appears, because a query runs against the whole table on the database, not just the rows currently loaded in the grid. - **When the data can't be re-queried** - for example, the result of combining data client-side, or other computed data - SQL isn't available. Data requests get a short explanation of what isn't possible instead of a query. Presentation requests still work normally on the loaded rows. The panel shows a note: "The AI works on the loaded rows only - this data can't be re-queried." ## Presentation Requests AI Assist works through AG Grid's state API, so anything the grid supports can be controlled via natural language: - **Filter:** "Only show orders over $100" or "Filter to US and UK customers" - **Sort:** "Sort by date, newest first" or "Sort by revenue descending" - **Group:** "Group by category" or "Group by country, then by city" - **Aggregate:** "Sum the amounts per group" or "Show average price by category" - **Pivot:** "Pivot by month" or "Pivot by quarter with revenue totals" - **Column visibility:** "Hide the ID column" or "Only show name, email, and status" - **Column pinning:** "Pin the name column to the left" - **Column sizing:** "Make the description column wider" - **Charts:** "Chart this as a bar chart" or "Create a pie chart of revenue by region" Each change applies instantly and is logged as a turn in the conversation. ### Example Conversation ``` You: "Sort by total_spend descending" → Grid sorts the total_spend column in descending order You: "Only show the top countries" → Grid applies a filter to the country column You: "Group by region and sum total_spend" → Grid groups rows by region with aggregated totals You: "Chart this as a bar chart" → A bar chart opens with the current grouped data ``` ## Data Requests When the loaded data can be re-queried, ask for different or additional data and AI Assist writes real SQL against the table you have open. ### Conversational Follow-ups AI Assist remembers the conversation, so follow-up requests refine the previous query instead of starting over. Ask for a weekly report, then follow up with "now monthly instead of weekly" or "only for the last quarter", and the AI adjusts the existing SQL rather than rebuilding it from scratch. ### Reviewing and Running SQL Every answer to a data request shows the generated SQL. Nothing runs automatically - you choose what happens next: - **Run here** executes the query on the same connection and swaps the results into the grid in place. An **AI results** chip appears in the grid toolbar while AI-generated results are showing. Click the chip's close button to restore the original table rows. - **Open in editor** exports the SQL to a new editor tab instead of running it. ### Fixing Failed Queries If a run fails, the database error is shown directly in the conversation with a one-click **Fix it** button that asks the AI to correct the query using that error message. ### Permissions Running SQL from AI Assist follows the same statement permissions as running SQL from the editor. If your connection's role requires confirmation for, or denies, statements like UPDATE or DELETE, those same rules apply here. ## Context Awareness When you open the AI Assist panel, it gathers what it needs to answer both kinds of requests: - **The grid's structured schema** - column names, data types, and available operations - so it can generate valid grid and chart changes - **The table's schema DDL**, plus any tables it has foreign key relationships with, when the data can be re-queried. If the AI needs more context, it can request the definitions of additional tables. - **The SQL dialect** of the connection - **Your current filter and sort settings** (including the values you filtered by), so the AI knows what you're looking at **No row data is ever sent.** The AI never sees your actual query results - only schema, operation definitions, and your current view settings. ## Suggested Actions The panel suggests one-click prompts based on your current columns. Suggestions for presentation changes (summarizing, charting a metric, filtering by a common value) always appear; suggestions for data requests (cohort analysis, top-N rankings, monthly trends) only appear when the data can be re-queried. Use the **Reset grid** button, next to **New conversation** at the bottom of the panel, to return the grid to its original state at any time. ## Team Roles Access to AI Assist in the data grid is controlled by the **Grid** AI permission in [team roles](/docs/accounts/team-roles). If your role restricts it, the panel shows a restriction message instead of the AI Assist UI. ## Privacy AI Assist sends the grid's **structured schema** (column names, data types, available operations) and, when the data can be re-queried, the table's **schema DDL** (plus related tables, fetched as needed) and your current **filter and sort settings** to your configured AI provider. **No table rows are ever sent.** Queries only run against your database when you click Run here. See [AI Privacy and Security](/docs/ai/privacy-and-security) for more details on how DBCode handles AI data. --- ## Docs > Ai > Copilot Tools ### Copilot Tools ## What are Copilot Tools? Copilot Tools in DBCode allow you to interact with your databases using simple natural language. Instead of writing complex SQL queries or remembering connection details, you can simply ask questions about your data and get immediate results. With DBCode's Copilot Tools integration, you can: - **Find connections** - Copilot can discover your available database connections automatically - **Read database schemas** - Ask about tables, columns, and relationships without memorizing your schema. On document databases like MongoDB, the same tools return collections and their fields - **Execute queries** - Ask questions about your data in plain English and get the query written and executed for you - **Make changes** - Data updates and schema changes run through separate tools, so read-only questions stay read-only - **Copy data between connections** - Run a query on one connection and insert the results into a table on another, like pulling a slice of production data into your dev database. Uses [Import Data](/docs/data/import), a **Pro** feature - **Interpret results** - Get insights and explanations of query results in natural language ## Get Started Simply use the agent mode in Copilot to enable the tools in your Copilot chat window. Once activated, you can start asking questions about your data in natural language. Not using Copilot? The same tools are available to other AI assistants through DBCode's [MCP server](/docs/ai/mcp). ## Working with Schema Context In agent mode, Copilot chains the tools on its own: it lists your connections, reads the schema for the database you're asking about, then writes and runs the query against your real table and column names. You don't need to feed it the schema first. Two things still help: 1. **Name the connection and database** when you have more than one: "on my PostgreSQL Dev connection" saves Copilot from guessing which to use. 2. **Set a default connection for the workspace** and you can skip even that. Copilot picks up the default automatically when you don't mention a connection. ## Example Prompts Here are some examples of what you can ask: **Schema exploration:** - "What tables exist in the sales_db database on my PostgreSQL connection?" - "Show me the schema of the users table in the sales_db database on my MariaDB Dev connection" - "List all tables and their columns from my_database on my SQL Server connection" **Queries:** - "Find all records created in the last 30 days in sales_db on my PostgreSQL connection" - "Calculate the total count grouped by status" - "Show me the top 10 items by revenue" - "Write a query to find inactive accounts" **Copying data:** - "Copy last week's orders from my Production connection into the orders table on my Dev connection" - "Pull 500 rows of the customers table from staging into my local Postgres so I can test against real shapes" **Connection management:** - "Find connections to my PostgreSQL database" - "What databases are available on my MySQL connection?" ## Privacy and Security Copilot Tools share information with GitHub Copilot when you explicitly request it: - **Database schema** (table/column names) when asking about database structure - **Actual data values** when asking Copilot to execute queries and return results **Important:** Unlike inline completion (which only sends schema), Copilot Tools can access and share actual data from your database when you ask it to run queries. Only use Copilot Tools with databases containing data you're comfortable sharing with GitHub Copilot. One exception: the copy data tool moves rows directly between your connections and reports only row counts back to Copilot. The copied rows themselves never pass through the model. See [AI Privacy and Security](/docs/ai/privacy-and-security) for detailed information on what data is shared and security considerations. --- ## Docs > Ai > Custom Provider ### Custom AI Provider DBCode can use any OpenAI-compatible API as its AI provider for inline completion and execution plan analysis. This lets you use local models (Ollama, LM Studio), cloud APIs (OpenAI, Groq, Together), or any service that exposes the standard `/v1/chat/completions` endpoint. ## Why Use a Custom Provider - **Privacy:** Run models locally so no data leaves your machine. - **Model choice:** Pick the model that best fits your needs — small and fast for completions, large and capable for analysis. - **Cost control:** Use free local models or your own API keys instead of a Copilot subscription or DBCode's hosted models. - **Flexibility:** Switch models per-request from the AI assistant panel without changing your default. ## Setup ### 1. Configure the Endpoint Open Settings (Cmd/Ctrl+,) and set: - **`dbcode.ai.customModel.endpoint`** — The base URL of your API server. **Examples:** | Provider | Endpoint | |----------|----------| | Ollama (local) | `http://localhost:11434` | | LM Studio (local) | `http://localhost:1234` | | OpenAI | `https://api.openai.com` | | Groq | `https://api.groq.com/openai` | | Together | `https://api.together.xyz` | ### 2. Configure the Model - **`dbcode.ai.customModel.model`** — The model identifier. **Examples:** | Provider | Model | |----------|-------| | Ollama | `codellama:7b-instruct`, `qwen2.5-coder:7b` | | OpenAI | `gpt-4o`, `gpt-4o-mini` | | Groq | `llama-3.3-70b-versatile` | | Together | `meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo` | ### 3. Set an API Key (if required) Local servers like Ollama and LM Studio typically don't require authentication. Cloud providers do. 1. Open the Command Palette (F1 or Cmd/Ctrl+Shift+P) 2. Run: **DBCode: Set Custom Model API Key** 3. Enter your API key The key is stored securely in VS Code's SecretStorage (your OS keychain). It is never written to settings files. If you send a request without a key and the server returns a 401 or 403 error, DBCode will automatically prompt you to enter one. ### Settings Reference | Setting | Description | Default | |---------|-------------|---------| | `dbcode.ai.customModel.endpoint` | OpenAI-compatible API base URL | — | | `dbcode.ai.customModel.model` | Model name / identifier | — | | `dbcode.ai.customModel.timeout` | Request timeout in seconds | `30` | | `dbcode.ai.customModel.only` | Disable fallback to other providers | `false` | **Example `settings.json`:** ```json { "dbcode.ai.customModel.endpoint": "http://localhost:11434", "dbcode.ai.customModel.model": "qwen2.5-coder:7b" } ``` ## Provider Hierarchy and Fallback When a custom provider is configured, DBCode uses it as the primary AI provider. If it fails (server unreachable, model not found, etc.), DBCode offers to fall back through the provider chain: 1. **Custom Model** — your configured endpoint 2. **GitHub Copilot** — if installed and active 3. **DBCode AI** — hosted model, always available For inline completions, the fallback happens silently with an info notification. For interactive features like execution plan analysis, DBCode shows a confirmation dialog before switching. To prevent fallback and use only your custom model, enable **`dbcode.ai.customModel.only`**. ## Choosing a Provider You can switch providers at any time: 1. Open the Command Palette (F1 or Cmd/Ctrl+Shift+P) 2. Run: **DBCode: Choose AI Provider** 3. Select Custom Model, Copilot, or DBCode AI ## Changing Models To change the model within your current provider: 1. Open the Command Palette 2. Run: **DBCode: Change AI Model** 3. Enter the new model name (custom) or select from the list (Copilot) When changing models from the AI assistant panel during an analysis, the change only applies to that request — your default settings are not modified. ## Troubleshooting ### "Cannot reach custom model" Error DBCode probes the endpoint on startup by calling `/v1/models` (or `/api/tags` for Ollama). If neither responds: - Verify the server is running and accessible at the configured URL - Check for firewall or proxy issues - Ensure the URL includes the protocol (`http://` or `https://`) ### Authentication Errors (401 / 403) - Run **DBCode: Set Custom Model API Key** to set or update your key - Verify the key is valid for the configured endpoint - If the key was rotated, clear the old one and re-enter it ### Slow Responses - Increase `dbcode.ai.customModel.timeout` (default is 30 seconds) - For local models, consider a smaller/faster model for inline completions - Use a larger model selectively for plan analysis by changing the model from the AI assistant panel ### Model Not Found (404) - Verify the model name matches exactly what the server expects - For Ollama, run `ollama list` to see available models - For cloud APIs, check the provider's documentation for valid model identifiers ## Related Documentation - [Models and Configuration](/docs/ai/models-and-configuration) — Provider selection and model settings - [Privacy and Security](/docs/ai/privacy-and-security) — What data is sent to AI models - [Execution Plans](/docs/query/execution-plans) — AI-assisted plan analysis --- ## Docs > Ai > Mcp ### Model Context Protocol (MCP) Model Context Protocol (MCP) lets AI tools query your databases through DBCode. The AI can list connections, read schemas, and run queries on your behalf. The MCP server is free for everyone. In **VS Code** and **Cursor**, DBCode registers itself with the editor's MCP host automatically. There is nothing to configure: install DBCode and the tools appear in the chat picker. ## VS Code & Cursor (auto-registered) When DBCode loads in VS Code or Cursor, it registers itself with the editor's MCP host. No `mcp.json` to edit. No port to configure. Each editor window connects independently. ### VS Code 1. Install DBCode. 2. Open Copilot Chat in agent mode. 3. Click the tools icon at the bottom of the chat input: `DBCode` appears as a server with its tools listed underneath. 4. Ask Copilot to do something with your data ("list my dbcode connections", "show me the schema for orders in my postgres database"). You'll be asked to sign in to DBCode the first time, if you aren't already. You can also confirm registration via the command palette: run `MCP: List Servers` and look for `DBCode`. ### Cursor 1. Install DBCode. 2. Open Cursor's MCP settings or tools picker: `DBCode` is listed automatically. 3. Use a chat that allows MCP tools and ask a database question. First use triggers a DBCode sign-in if needed. You don't need to add anything to `.cursor/mcp.json` for DBCode. Cursor discovers the server through DBCode's extension registration. ### Other editors If your editor doesn't support the MCP extension API, DBCode skips auto-registration silently. You can use the [HTTP server](#external-clients-http-server) approach below, or upgrade your editor. ## Scoping what an agent can do Everything here is free, so an agent's access is as narrow as you decide: - [Read-only connections and roles](/docs/connections/roles) set what the agent can reach at the connection level. - [Missing WHERE detection](/docs/query/missing-where-detection) catches a destructive query whether a human or an agent wrote it. ## External clients (HTTP server) DBCode also ships a localhost HTTP MCP server. Use it when: - Connecting from **Claude Desktop**, **Claude Code**, **GitHub Copilot CLI**, or another MCP client that isn't a VS Code-family editor. - Running DBCode on your **host machine** while AI clients run in **Dev Containers** or on **other machines on your LAN**. - Using an editor that doesn't support automatic MCP registration. The HTTP server is **off by default**: it's a separate path from the auto-registered bridge above. Enable it explicitly when you need it. ### Settings Open [DBCode MCP Settings](vscode://settings/dbcode.ai.mcp) and review: - `dbcode.ai.mcp.autoStart` (**MCP HTTP Server Auto Start**): start the HTTP server every time DBCode loads. - `dbcode.ai.mcp.port` (**MCP HTTP Server Port**): default `5002`. - `dbcode.ai.mcp.authorization` (**MCP HTTP Server Authorization**): `OAuth` (default, recommended) or `None`. - `dbcode.ai.mcp.allowExternalConnections` (**MCP HTTP Server Allow External Connections**): required for Dev Containers / LAN access. Forces OAuth. These settings only affect the HTTP server. The auto-registered stdio path used by VS Code and Cursor is unaffected. ### Start the HTTP server Open the command palette (F1 or Cmd/Ctrl+Shift+P) and run: `DBCode: MCP Start HTTP Server` The server listens on: ``` http://localhost:5002/mcp ``` In OAuth mode the discovery endpoint is also available: ``` http://localhost:5002/.well-known/oauth-authorization-server ``` To stop it, run `DBCode: MCP Stop HTTP Server`. ### Authentication #### OAuth (default, recommended) Clients discover the authorization and token endpoints via `/.well-known/oauth-authorization-server` and complete a standard Authorization Code + PKCE flow. On first connection VS Code shows an approval dialog (client ID, redirect URI, requested scopes). Approving mints an access token the client reuses for subsequent requests. Denying aborts the handshake. Most modern MCP clients handle OAuth automatically. Configure the endpoint as `http://localhost:5002/mcp` with HTTP transport and you're done. #### None All requests to `/mcp` are accepted without credentials. Only suitable for local development or trusted environments. Don't combine `None` with `allowExternalConnections`: DBCode refuses and falls back to localhost. ### External connections (Dev Containers, LAN) By default the HTTP server only accepts connections from the same machine (`localhost`). To expose it beyond that, enable `dbcode.ai.mcp.allowExternalConnections`. This requires `OAuth` authorization. #### Dev Containers Run DBCode in a VS Code window on your host. From inside a Dev Container, point the MCP client at `host.docker.internal`: ```json { "mcpServers": { "dbcode": { "url": "http://host.docker.internal:5002/mcp" } } } ``` One host server can serve multiple Dev Containers without running a DBCode instance inside each one. #### LAN access From other machines on your network, replace `localhost` with your host's IP address. Make sure your firewall permits incoming traffic on the MCP port. ### stdio-only clients Some MCP clients want a command to spawn instead of an HTTP URL. Use [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) as a thin stdio→HTTP bridge: ```bash npx -y mcp-remote http://localhost:5002/mcp ``` `mcp-remote` handles OAuth on the client's behalf: no manual token generation needed. ## Example client configurations ### Claude Desktop Claude Desktop reads MCP servers from `claude_desktop_config.json`. Add the `mcp-remote` command so Claude can negotiate OAuth automatically: ```json { "mcpServers": { "dbcode": { "command": "npx", "args": [ "-y", "mcp-remote", "http://localhost:5002/mcp" ] } } } ``` On macOS the file lives at `~/Library/Application Support/Claude/claude_desktop_config.json`. On Windows use `%APPDATA%/Claude/claude_desktop_config.json`. Restart Claude Desktop after editing. ### GitHub Copilot CLI Copilot CLI supports MCP via both HTTP and stdio. Add DBCode interactively or by editing the config file directly. #### Interactive setup Run `/mcp add` inside a Copilot CLI session, then provide: - **Server Name**: `dbcode` - **Server Type**: HTTP - **URL**: `http://localhost:5002/mcp` - **Tools**: `*` Save with Ctrl+S. #### Direct configuration Edit `~/.copilot/mcp-config.json`: ```json { "mcpServers": { "dbcode": { "type": "http", "url": "http://localhost:5002/mcp", "tools": ["*"] } } } ``` If HTTP transport fails on your version, fall back to stdio via `mcp-remote`: ```json { "mcpServers": { "dbcode": { "type": "local", "command": "npx", "args": ["-y", "mcp-remote", "http://localhost:5002/mcp"], "tools": ["*"] } } } ``` Use `/mcp show` to verify the server is connected and `/mcp show dbcode` to list available tools. ### Claude Code Claude Code supports MCP servers via the `claude mcp` CLI or by editing `.mcp.json` directly. Make sure the DBCode HTTP server is running first (`DBCode: MCP Start HTTP Server`). #### CLI setup Add DBCode as an HTTP server with one command: ```bash claude mcp add --transport http dbcode http://localhost:5002/mcp ``` By default this writes to the local scope (current project only). To share the server across all projects on your machine, use `--scope user`. To check in the config so teammates pick it up, use `--scope project` (writes to `.mcp.json` at the project root). Verify it's connected: ```bash claude mcp list claude mcp get dbcode ``` #### Direct configuration For project-scoped setup, create `.mcp.json` at the repo root: ```json { "mcpServers": { "dbcode": { "type": "http", "url": "http://localhost:5002/mcp" } } } ``` Inside a Claude Code session, run `/mcp` to see connected servers and approve the OAuth handshake the first time. Use `/mcp` again to list available tools or reauthenticate. #### stdio fallback If your version of Claude Code has trouble with HTTP transport, fall back to stdio via `mcp-remote`: ```bash claude mcp add dbcode -- npx -y mcp-remote http://localhost:5002/mcp ``` ### Cursor Cursor auto-registers DBCode: no `.cursor/mcp.json` entry needed. DBCode will appear in Cursor's MCP UI as soon as the extension is installed. If you ever need to configure it manually as a fallback, start the HTTP server and add: ```json { "mcpServers": { "dbcode": { "url": "http://localhost:5002/mcp" } } } ``` Place this at `.cursor/mcp.json` for project-specific use or `~/.cursor/mcp.json` globally. See the [official Cursor MCP documentation](https://docs.cursor.com/context/model-context-protocol) for more. ### VS Code VS Code auto-registers DBCode: no manual configuration needed. If you ever need to configure it manually, start the HTTP server and add the URL to your `mcp.json` the same way as Cursor above. ## Working with database schema When using DBCode through MCP, the AI doesn't automatically know your database structure. You need to explicitly ask it to read your schema before writing queries. ### Understanding the workflow DBCode provides tools that allow the AI to: - List available database connections (`dbcode-get-connections`) - Retrieve databases from a connection (`dbcode-get-databases`) - Read complete table schemas including columns, keys, and indexes (`dbcode-get-tables`) - Execute queries with the proper context (`dbcode-execute-query`, `dbcode-execute-dml`, `dbcode-execute-ddl`) - Disconnect to release file locks for file-based databases (`dbcode-disconnect`) The AI uses these tools when you ask it to, but you need to guide it through the process. ### Prompting best practices **Instead of this (will likely fail or guess incorrectly):** ``` "Show me all records created last month" ``` **Use this (provides proper context):** ``` "First, read the tables and columns from my_database on my PostgreSQL connection. Then show me all records created last month." ``` ### Example prompts **Schema exploration:** - "What database connections do I have available?" - "List all tables in the production database on my PostgreSQL connection" - "Show me the complete schema for a specific table, including all columns and foreign keys" **Queries with context:** - "Read the schema from my database, then find all records created in the last 30 days" - "First get the table structure from analytics_db, then calculate totals grouped by category" - "What tables exist in my database? After showing me, write a query to find active items" - "Get the schema first, then show me the top performing entries by metric" **Multi-step workflows:** - "Connect to my MySQL database, read the schema, and then show me how the main tables are related" - "List my connections, then for the PostgreSQL one, read all tables and identify which contain timestamps" - "Find my database connections, pick the production one, read its schema, then analyze the data structure" By explicitly asking the AI to read your schema first, you ensure it generates queries using your actual table and column names rather than making assumptions. ## Copying data between connections The `dbcode-copy-data` tool copies query results from one connection into a table on another connection. The headline use case is pulling rows from a production database into a development or staging database for testing. The destination table must already exist. If it doesn't, ask the AI to create it first with `dbcode-execute-ddl`. Column aliases in the source query define the destination column mapping: DBCode first tries an exact name match, then a case-insensitive match. Aliasing source columns to match destination column names is the recommended way to control mapping. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `sourceConnectionId`, `sourceConnectionName` | string | Yes | The connection to read from (both the id and name, as returned by `dbcode-get-connections`). | | `sourceDatabase` | string | Yes | The database to read from. | | `query` | string | Yes | The SELECT statement whose results are copied. Column aliases become the destination column names. | | `destConnectionId`, `destConnectionName` | string | Yes | The connection to write to. | | `destDatabase` | string | Yes | The destination database. | | `destSchema` | string | No | The destination schema, for databases that support schemas. Defaults to the connection's default schema. | | `destTable` | string | Yes | The destination table name. | | `duplicates` | `error` \| `skip` \| `replace` | No | How to handle rows that conflict with existing data. Default: `error`. | | `onError` | `halt` \| `continue` | No | Whether to stop or skip bad rows when an insert fails. Default: `halt`. | **Duplicate handling** - `error` - the operation stops on the first key conflict (default). - `skip` - conflicting rows are ignored and the copy continues. On MySQL, `INSERT IGNORE` is used internally, which suppresses errors beyond key conflicts (such as invalid values); test on a sample first. - `replace` - conflicting rows are overwritten. Requires a primary key on the destination table. **Row limit and large datasets** The tool is capped at 1,000,000 source rows per call. For larger datasets, narrow the source query into key ranges and call the tool repeatedly with `duplicates=skip` - skipping duplicates makes re-runs safe to resume from where a previous call left off. **Progress** If the MCP client sends a `progressToken`, the tool streams incremental progress as batches are inserted. **Return value** The tool returns a status summary: rows read, rows written, rows failed, duration, and a capped sample of error messages. It never returns the copied rows themselves. ## Privacy and security MCP shares information with connected AI clients only when explicitly requested through MCP tools: - **Database schema** (table/column names) when the AI asks about database structure. - **Actual data values** when the AI executes queries and returns results. **Important:** Unlike inline completion (which only sends schema), MCP tools can read and share actual data from your database when the AI executes queries. Only use MCP with databases containing data you're comfortable sharing with your AI client. In VS Code and Cursor, you'll be prompted to sign in to DBCode the first time you use an MCP tool. The HTTP server has its own authorization (OAuth by default: your editor shows an approval dialog the first time each client connects). If you're on a shared multi-user Windows machine (RDS, Citrix, classroom), prefer the HTTP server with OAuth over the auto-registered path. Privacy guarantees depend on the AI client you connect (Cursor, Claude Desktop, Copilot CLI, etc.). Each client handles data according to its own privacy policy. See [AI Privacy and Security](/docs/ai/privacy-and-security) for detailed information on what data is shared, authentication, and security considerations. --- ## Docs > Ai > Query Builder Ai ### AI Assist for Query Builder The [Query Builder](/docs/query/query-builder) includes an AI input bar that lets you describe what you want in plain English. The AI reads your current query model and database schema, then updates the visual canvas — adding tables, joins, columns, filters, and grouping automatically. ![Query Builder with AI input bar showing a natural language prompt](./ai-input.png) ## Using AI in the Query Builder 1. Open the [Query Builder](/docs/query/query-builder) from any database 2. Type a natural language request in the input bar at the top 3. Press Enter 4. The canvas, config panel, and SQL preview all update to reflect the AI's changes You can undo any AI change with Ctrl+Z / Cmd+Z. ## What You Can Do ### Build from Scratch Start with an empty canvas and describe what you need: - "Show me all customers with their order totals" - "List products with prices over 50, sorted by name" - "Find employees hired in the last year with their department names" The AI selects appropriate tables, configures joins based on foreign key relationships, picks relevant columns, and adds filters. ### Modify an Existing Query With tables already on the canvas, ask for changes: - "Add a date filter for last month" - "Change to LEFT JOIN" - "Group by category and sum the amounts" - "Remove the email column" - "Add an ORDER BY on total descending" - "Limit to 100 rows" The AI preserves your existing query and applies only the requested changes. ### Aggregate and Analyze - "Show total sales by region" - "Count orders per customer" - "Average price by category, only categories with more than 10 products" The AI automatically configures GROUP BY, aggregate functions, and HAVING clauses. ## What Gets Sent to the AI The AI receives: - **Schema DDL** — CREATE TABLE statements for the tables in your connected database (column names, types, keys, and relationships) - **Current query model** — The JSON representation of your visual query (tables, joins, columns, filters, grouping — no actual data) - **Your prompt** — The natural language instruction you typed **No row data is ever sent.** The AI works with schema structure and your query model only. ## How It Works 1. Your natural language request is sent to the configured AI provider along with the schema DDL and current query model 2. The AI returns an updated QueryModel as JSON (not SQL) 3. The Query Builder validates the response and applies it to the canvas 4. Tables, joins, columns, filters, and all configuration update visually 5. The SQL preview regenerates from the updated model The AI returns a complete query model, not a diff — so the entire visual state updates at once. This makes it easy to undo with a single Ctrl+Z. ## AI Provider The Query Builder uses the same AI provider configured in your [AI settings](/docs/ai/models-and-configuration). Any model that supports structured JSON output works — including GitHub Copilot, OpenAI, Anthropic, Ollama, and custom providers. See [AI Privacy and Security](/docs/ai/privacy-and-security) for details on how DBCode handles AI data. --- ## Docs > Api ### VSCode Extension API The DBCode VS Code Extension API allows other extensions to programmatically manage database connections and interact with the DBCode explorer. ## Installation ```bash npm install @dbcode/vscode-api ``` ## Usage ```typescript export async function activate(context: vscode.ExtensionContext) { // Get DBCode extension const dbcodeExtension = vscode.extensions.getExtension('dbcode.dbcode'); if (!dbcodeExtension) { vscode.window.showErrorMessage('DBCode extension not found'); return; } await dbcodeExtension.activate(); const dbcodeAPI: DBCodeAPI = dbcodeExtension.exports.api; // Define a connection const connection: ConnectionConfig = { connectionId: 'my-postgres-db', name: 'My PostgreSQL Database', connectionType: 'host', driver: 'postgres', host: 'localhost', port: 5432, database: 'myapp', username: 'postgres' }; // Add the connection const result = await dbcodeAPI.addConnections([connection]); if (result.success) { vscode.window.showInformationMessage('Connection added successfully!'); // Reveal the connection in the explorer await dbcodeAPI.revealConnection('my-postgres-db'); } else { vscode.window.showErrorMessage(`Failed to add connection: ${result.error}`); } } ``` ## Resources For complete implementation details, type definitions, and advanced usage patterns: - [Example Extension](https://github.com/dbcodeio/vscode-api/blob/main/example/extension.ts) - Complete working example with comments - [GitHub Repository](https://github.com/dbcodeio/vscode-api) - Full api spec and documentation - [NPM Package](https://www.npmjs.com/package/@dbcode/vscode-api) - TypeScript types and interfaces --- ## Docs > Authentication Profiles ### AWS AWS authentication profiles provide flexible credential management for AWS-based database services like Athena, Redshift, and DynamoDB. DBCode supports both static credentials and AWS profile-based authentication, including full SSO support. ## Credential Sources | Source | Use Case | Configuration | |--------|----------|---------------| | **Static Credentials** | Direct access key authentication | Access Key ID + Secret Access Key | | **AWS Profile** | Profile-based authentication including SSO | Profile name from `~/.aws/config` | ### Static Credentials Use static credentials when you have long-term IAM access keys: **Required fields:** - **Access Key ID**: Your AWS access key (starts with `AKIA...`) - **Secret Access Key**: Your AWS secret key **Optional fields:** - **Session Token**: Required for temporary credentials from STS AssumeRole - **Default Region**: AWS region (e.g., `us-east-1`) **Best for:** - Service accounts with IAM users - Development environments with dedicated access keys - Situations where SSO is not available ### AWS Profile Use AWS profiles to leverage your existing AWS CLI configuration, including SSO profiles: **Required fields:** - **Profile Name**: Profile from `~/.aws/config` or `~/.aws/credentials` **Optional fields:** - **Default Region**: Overrides the region from your profile configuration **Supported profile types:** - Standard profiles with static credentials - SSO profiles configured with `aws configure sso` - Assume role profiles - Credential process profiles ## SSO Authentication When using an SSO profile, DBCode automatically handles session management: 1. **Initial connection**: If your SSO session is valid, DBCode uses your cached credentials 2. **Expired session**: DBCode prompts you to log in with a single click 3. **Automatic login**: Clicking "Log In" runs `aws sso login --profile ` and opens your browser 4. **Credential polling**: DBCode waits for you to complete authentication, then continues connecting ### Setting Up SSO Profiles If you haven't configured an SSO profile yet: ```bash # Configure a new SSO profile aws configure sso --profile my-sso-profile # Or manually add to ~/.aws/config: [profile my-sso-profile] sso_start_url = https://my-company.awsapps.com/start sso_region = us-east-1 sso_account_id = 123456789012 sso_role_name = MyRole region = us-west-2 ``` ## Supported Databases The following databases support AWS authentication profiles: - **Athena** - Query data in S3 using SQL - **Redshift** - Data warehouse - **DynamoDB** - NoSQL database ## Troubleshooting ### "SSO session expired for profile" **Cause**: Your AWS SSO session has expired or you haven't logged in yet. **Solution**: Click "Log In" when prompted. DBCode will run `aws sso login --profile ` and open your browser for authentication. ### "No AWS profiles found" **Cause**: No profiles configured in `~/.aws/config` or `~/.aws/credentials`. **Solutions:** - Configure a profile using `aws configure` or `aws configure sso` - Verify your AWS config files exist and have valid syntax ### "Timed out waiting for SSO login" **Cause**: SSO authentication wasn't completed within 2 minutes. **Solutions:** - Try connecting again and complete the browser authentication promptly - Check that your SSO portal is accessible - Verify your SSO profile configuration is correct ### "Failed to resolve AWS credentials for profile" **Cause**: Profile configuration issue or missing dependencies. **Solutions:** - Verify the profile exists in your AWS config - For assume role profiles, ensure the source credentials are valid - Check AWS CLI is installed and configured correctly --- ### Command Command authentication profiles allow you to retrieve credentials dynamically by executing shell commands. This enables integration with external secret managers like 1Password CLI, HashiCorp Vault, AWS Secrets Manager, and any custom credential retrieval scripts. ## Key Benefits - **Secret Manager Integration**: Connect to 1Password, Vault, AWS Secrets Manager, etc. - **Dynamic Credentials**: Retrieve fresh credentials on each connection - **Custom Scripts**: Use any script or CLI tool that outputs credentials - **Environment Variables**: Connection details are available as environment variables - **Credential Caching**: Optional caching to reduce secret manager calls ## Configuration Options ### Command The shell command to execute. Connection configuration values are available as environment variables: | Variable | Description | |----------|-------------| | `${host}` | Database host | | `${port}` | Database port | | `${database}` | Database name | | `${name}` | Connection name | | `${driver}` | Database driver type | ### Output Format **Text Output** - **Password only**: Command outputs just the password - **Username:Password**: Command outputs `username:password` separated by colon **JSON Output** - Parse structured JSON with configurable field paths - Supports nested paths like `data.credentials.password` ### Credential Caching | Mode | Description | |------|-------------| | **No caching** | Execute command every time | | **Fixed TTL** | Cache for specified duration (seconds) | | **From output** | Use expiry timestamp from JSON output | ## Example Commands Here are example commands for popular secret managers: ### 1Password CLI ```bash op read "op://Private/PostgreSQL Production/password" ``` ### HashiCorp Vault ```bash vault kv get -format=json secret/databases/production | jq -r '.data.data' ``` Use JSON output format with `username` and `password` fields. ### AWS Secrets Manager ```bash aws secretsmanager get-secret-value --secret-id prod/db/credentials --query SecretString --output text ``` Use JSON output format to parse the returned secret. ### Azure Key Vault ```bash az keyvault secret show --vault-name my-vault --name db-password --query value -o tsv ``` ### Bitwarden CLI ```bash bw get password database-production ``` ### Doppler ```bash doppler secrets get DB_PASSWORD --plain ``` ### Custom Script Your script receives connection details as environment variables: ```bash #!/bin/bash # Available: DB_HOST, DB_PORT, DB_DATABASE, DB_NAME, DB_DRIVER echo "{\"user\": \"app_${DB_DATABASE}\", \"pass\": \"$(fetch_password $DB_HOST)\"}" ``` ## JSON Output Format When using JSON output, your command should return a JSON object: ```json { "username": "db_user", "password": "secret123", "expiresAt": 1699900000000 } ``` ### Nested Fields Use dot notation for nested JSON paths. For example, if your command returns: ```json { "data": { "credentials": { "user": "admin", "pass": "secret" } } } ``` Set the username field to `data.credentials.user` and password field to `data.credentials.pass`. ## Advanced Options - **Timeout**: Maximum time to wait for command to complete (default: 30 seconds) - **Working Directory**: Directory where the command runs (defaults to workspace root) ## Supported Databases Command authentication profiles can be used with any database that supports username/password authentication: - PostgreSQL, MySQL, MariaDB - SQL Server, Oracle - MongoDB - And all other databases with password auth ## Troubleshooting ### "Command timed out" **Cause**: Command took longer than the timeout setting. **Solutions:** - Increase the timeout value in advanced settings - Ensure the secret manager CLI is responsive - Check network connectivity to the secret manager ### "Command failed with exit code X" **Cause**: The command returned a non-zero exit code. **Solutions:** - Test the command manually in your terminal - Check that the CLI tool is installed and authenticated - Verify the secret path/name is correct ### "Failed to parse JSON output" **Cause**: Command output is not valid JSON. **Solutions:** - Test the command manually and verify JSON output - Ensure no extra text is output before/after the JSON - Use `jq` or similar tools to extract clean JSON ### "Username/password field not found" **Cause**: The specified JSON field path doesn't exist in the output. **Solutions:** - Verify the JSON structure of your command output - Check the field path for typos - Use the correct dot notation for nested fields --- ### Authentication Profiles Authentication Profiles provide a centralized way to manage authentication credentials that can be shared across multiple database connections. This feature is particularly useful for modern authentication methods like OAuth2 and OIDC, where credential management can be complex. ## Key Benefits - **Credential Reuse**: Define authentication once, use across multiple connections - **Centralized Management**: Update credentials in one place for all connections - **Secure Storage**: Sensitive values stored in VS Code's secure credential storage - **Modern Auth Support**: First-class support for OAuth2, OIDC, and other token-based authentication - **Workspace & Global Scope**: Share profiles across your team or keep them personal ## Supported Authentication Types | Type | Description | Documentation | |------|-------------|---------------| | **AWS** | AWS credentials via static keys or profiles with SSO support | [AWS Guide](/docs/authentication-profiles/aws) | | **Command** | Execute shell commands to retrieve credentials from external secret managers | [Command Guide](/docs/authentication-profiles/command) | | **OAuth2 / OIDC** | Token-based authentication with support for Authorization Code and Client Credentials flows | [OAuth2 Guide](/docs/authentication-profiles/oauth2) | | **.pgpass File** | Use PostgreSQL's standard password file for authentication | [pgpass Guide](/docs/authentication-profiles/pgpass) | ## Creating an Authentication Profile ### From the Authentication Profiles View 1. Open the **DBCode** activity bar 2. Navigate to the **Authentication Profiles** section 3. Click the **+** (Create) icon in the view title bar 4. Select the authentication type (e.g., OAuth2) 5. Fill in the required fields 6. Choose storage location for each field: - **Secret Storage**: Encrypted, not visible in settings files - **Settings JSON**: Visible in settings, suitable for non-sensitive values 7. Choose scope: - **User (Global)**: Available across all workspaces - **Workspace**: Only available in current workspace 8. Click **Save** ### From a Connection Form When creating or editing a connection that supports authentication profiles: 1. Find the **Authentication** section 2. Click **Create New Profile** in the auth profile dropdown 3. Complete the profile setup (same as above) 4. The new profile will be automatically selected for your connection ## Managing Authentication Profiles ### Editing a Profile **From the Tree View:** - Right-click the profile → **Edit** - Or click the pencil icon **From Command Palette:** - Run **DBCode: Edit Auth Profile** - Select the profile to edit ### Deleting a Profile **From the Tree View:** - Right-click the profile → **Delete** - Or click the trash icon **Restrictions:** - Profiles in use by connections cannot be deleted - Delete or reassign connections first ### Viewing Profile Details Hover over a profile in the tree view to see: - Profile name - Authentication type - Scope (User/Workspace) ## Using Authentication Profiles in Connections When creating or editing a connection: 1. Look for the **Auth Profile** dropdown in the connection form 2. Select an existing profile, or create a new one 3. Save the connection The connection will use the profile's credentials for authentication. If the profile uses OAuth2, you'll be prompted to authenticate via your browser when connecting. ## Storage and Security ### Secret Storage Sensitive values (passwords, client secrets, tokens) are stored in VS Code's secure credential storage: - **macOS**: Keychain - **Windows**: Credential Manager - **Linux**: Secret Service API (gnome-keyring, kwallet) ### Settings JSON Non-sensitive configuration (URLs, client IDs, scopes) can be stored in VS Code settings: - **User Settings**: `~/.vscode/settings.json` or `~/Library/Application Support/Code/User/settings.json` - **Workspace Settings**: `.vscode/settings.json` in your workspace You control which fields go where when creating or editing a profile. ## Best Practices ### Scope Selection **Use Global (User) scope when:** - Credentials are personal to you - You connect to the same resources across multiple projects - The authentication is tied to your user account **Use Workspace scope when:** - Credentials are shared with your team (committed to version control) - Authentication is specific to a project - You want to keep work and personal profiles separate ## Troubleshooting ### "Auth profile not found" **Cause**: Profile was deleted or moved between scopes **Solutions:** - Recreate the profile or select a different one - Check if the profile exists in the correct scope (User vs Workspace) ### "Profile in use by connections" **Cause**: Attempting to delete a profile that's assigned to connections **Solutions:** - Edit connections using the profile and change their auth method - Or assign a different profile to those connections ## Related Documentation - [OAuth2 / OIDC Authentication](/docs/authentication-profiles/oauth2) - [AWS Authentication](/docs/authentication-profiles/aws) - [Command Authentication](/docs/authentication-profiles/command) - [.pgpass File Authentication](/docs/authentication-profiles/pgpass) - [Creating Connections](/docs/connections/create) - [Connection Security](/docs/security) - [SSH Tunnels](/docs/connections/ssh-tunnels) --- ### OAuth2 / OIDC OAuth2 with OpenID Connect (OIDC) support provides modern token-based authentication for database systems that support it. DBCode supports both interactive and non-interactive OAuth2 flows. ## Supported Grant Types | Grant Type | Use Case | User Interaction | |------------|----------|------------------| | **Authorization Code** | Interactive user login | Browser redirect | | **Client Credentials** | Service principals, machine-to-machine | None | ### Authorization Code Flow The Authorization Code flow is designed for interactive authentication where a user logs in via their browser. **How it works:** 1. DBCode opens your browser to the authorization server 2. You authenticate with your identity provider 3. The authorization server redirects back to DBCode with an authorization code 4. DBCode exchanges the code for access and refresh tokens 5. Tokens are securely stored and automatically refreshed **Features:** - Interactive browser-based authentication - PKCE (Proof Key for Code Exchange) support for enhanced security - Refresh token management for seamless reconnection - Automatic token renewal before expiration **Best for:** - User-based authentication - Interactive development environments - When you need to authenticate as yourself ### Client Credentials Flow The Client Credentials flow is designed for service-to-service authentication without user interaction. **How it works:** 1. DBCode sends the client ID and secret directly to the token endpoint 2. The authorization server returns an access token 3. No browser interaction required **Features:** - Direct token acquisition without browser - Service principal / application authentication - No refresh tokens (tokens re-acquired on expiry) - Fully automated, no user prompts **Best for:** - Automated systems and CI/CD pipelines - Service accounts and machine identities - Non-interactive environments - Scheduled jobs and background processes ## Configuration Options ### Grant Type Select the OAuth2 flow that matches your authentication needs: - **Authorization Code**: For interactive user authentication - **Client Credentials**: For service principals and automation ### Discovery Mode **Auto Discovery** (Recommended) - Provide a Discovery URL (OIDC discovery endpoint) - DBCode automatically fetches authorization and token endpoints - Example: `https://auth.example.com/.well-known/openid-configuration` **Manual Configuration** - Directly specify the authorization and token endpoints - Use when the identity provider doesn't support OIDC discovery ### Required Fields | Field | Auth Code | Client Credentials | Description | |-------|-----------|-------------------|-------------| | **Client ID** | Required | Required | Application client identifier | | **Client Secret** | Optional | Required | Application client secret | | **Discovery URL** | Auto mode | Auto mode | OIDC discovery endpoint | | **Authorization Endpoint** | Manual mode | N/A | OAuth2 authorization URL | | **Token Endpoint** | Manual mode | Manual mode | OAuth2 token exchange URL | | **Scopes** | Optional | Optional | Space or comma-separated list of OAuth2 scopes | ### Auto-Discovery For OIDC-compliant providers, use the **Auto-Discover** button to automatically populate endpoints from your discovery URL. This fetches: - Authorization endpoint - Token endpoint - Supported scopes - Other OIDC configuration ## Supported Databases The following databases support OAuth2 authentication profiles: - **Trino** - With OAuth2-enabled clusters - **Starburst** - Enterprise Trino with OAuth2 - **Databricks** - With OAuth2 authentication enabled - **Snowflake** - With external OAuth configuration ## Configuration Examples ### Trino with Authorization Code (Interactive) ```json { "name": "Trino Production", "type": "oauth2", "options": { "grantType": "authorization_code", "discoveryUrl": "https://auth.company.com/.well-known/openid-configuration", "clientId": "trino-client", "scopes": "openid profile email" } } ``` Client secret (if required) stored in Secret Storage. ### Starburst with Client Credentials (Service Principal) ```json { "name": "Starburst Service Account", "type": "oauth2", "options": { "grantType": "client_credentials", "discoveryUrl": "https://login.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration", "clientId": "your-service-principal-client-id", "scopes": "api://starburst/.default" } } ``` Client secret stored in Secret Storage. No browser interaction required. ### Databricks with OAuth ```json { "name": "Databricks Workspace", "type": "oauth2", "options": { "grantType": "authorization_code", "authorizationEndpoint": "https://accounts.cloud.databricks.com/oidc/v1/authorize", "tokenEndpoint": "https://accounts.cloud.databricks.com/oidc/v1/token", "clientId": "databricks-oauth-client", "scopes": "all-apis offline_access" } } ``` ### Azure AD / Entra ID ```json { "name": "Azure AD Service Principal", "type": "oauth2", "options": { "grantType": "client_credentials", "discoveryUrl": "https://login.microsoftonline.com/{tenant-id}/v2.0/.well-known/openid-configuration", "clientId": "your-app-registration-client-id", "scopes": "https://your-resource/.default" } } ``` ## Token Management ### Automatic Refresh For Authorization Code flow, DBCode automatically: - Caches valid access tokens to minimize authentication prompts - Refreshes tokens before they expire using the refresh token - Prompts for re-authentication only when the refresh token expires ### Client Credentials Tokens For Client Credentials flow: - Tokens are acquired fresh when needed - No refresh tokens (the grant type doesn't support them) - Tokens are cached until they expire ### Manual Token Clearing To force re-authentication: 1. Edit the profile and save (clears cached tokens) 2. Or disconnect and reconnect the database connection ## Troubleshooting ### "Failed to open browser for authentication" **Cause**: Browser couldn't be opened for OAuth2 authorization flow **Solutions:** - Check that you have a default browser configured - Try running VS Code with appropriate permissions - For remote development, ensure port forwarding is configured ### "Client secret is required for client credentials flow" **Cause**: Using Client Credentials grant type without providing a client secret **Solutions:** - Add the client secret to the profile configuration - Store it in Secret Storage for security ### Token Refresh Failures **Cause**: Refresh token expired or invalidated **Solutions:** - Disconnect and reconnect to trigger new authorization flow - Check that your refresh token hasn't been revoked - Verify OAuth2 configuration is still valid ### "Token exchange failed" **Cause**: Error during the code-to-token exchange **Solutions:** - Verify your client ID and secret are correct - Check that the redirect URI is properly configured in your identity provider - Ensure scopes are valid for your application registration ### PKCE Errors **Cause**: Identity provider doesn't support PKCE or has it misconfigured **Solutions:** - DBCode uses PKCE by default for Authorization Code flow - If your provider doesn't support PKCE, contact your identity provider - Most modern OAuth2 providers support PKCE ## Security Best Practices 1. **Use Client Credentials for automation**: Don't embed user credentials in automated systems 2. **Store secrets securely**: Always use Secret Storage for client secrets 3. **Limit scopes**: Request only the scopes your application needs 4. **Use OIDC discovery**: Auto-discovery ensures you're using the correct endpoints 5. **Rotate secrets regularly**: Follow your organization's secret rotation policies --- ### .pgpass File The .pgpass authentication profile allows you to use PostgreSQL's standard password file for authentication. This is the same file format used by `psql` and other PostgreSQL client tools, making it easy to share credentials across tools. ## Key Benefits - **Standard Format**: Uses the same `.pgpass` file as `psql` and other PostgreSQL tools - **Credential Sharing**: Share passwords across multiple PostgreSQL client applications - **Pattern Matching**: Wildcards allow flexible credential matching - **No Code Changes**: Works with existing `.pgpass` files without modification ## File Format The `.pgpass` file contains one entry per line with colon-separated fields: ``` hostname:port:database:username:password ``` ### Fields | Field | Description | |-------|-------------| | `hostname` | Database server hostname or IP address | | `port` | Database port number | | `database` | Database name | | `username` | PostgreSQL username | | `password` | Password for this connection | ### Wildcards Use `*` as a wildcard to match any value (except in the password field): ``` # Match any database on localhost localhost:5432:*:myuser:mypassword # Match any host on port 5432 *:5432:mydb:myuser:mypassword # Match everything for a user *:*:*:admin:adminpassword ``` ### Escaping To include a literal colon (`:`) or backslash (`\`) in a field value, escape it with a backslash: ``` hostname\:with\:colons:5432:mydb:user:password ``` ## File Locations ### Default Locations | Platform | Default Path | |----------|--------------| | macOS / Linux | `~/.pgpass` | | Windows | `%APPDATA%\postgresql\pgpass.conf` | ### Environment Variable Set the `PGPASSFILE` environment variable to use a custom location: ```bash export PGPASSFILE=/path/to/custom/pgpass ``` ## Configuration Options ### File Location Choose between: - **Default Location**: Uses the standard `.pgpass` file path for your operating system - **Custom Path**: Specify a custom file path ## Example .pgpass File ``` # Development servers localhost:5432:*:postgres:devpassword dev-server.example.com:5432:appdb:appuser:devpass123 # Production (read-only user) prod-db.example.com:5432:*:readonly:prodreadonly # Staging with wildcard *.staging.example.com:5432:*:deploy:stagingpass ``` ## Matching Rules When connecting, DBCode searches the `.pgpass` file from top to bottom and uses the **first matching entry**. An entry matches if: 1. Hostname matches (or entry has `*`) 2. Port matches (or entry has `*`) 3. Database matches (or entry has `*`) 4. Username matches (or entry has `*`) ### Example Matching Given this `.pgpass` file: ``` localhost:5432:testdb:testuser:testpass localhost:5432:*:postgres:postgrespass *:*:*:admin:adminpass ``` | Connection | Matched Entry | Password Used | |------------|---------------|---------------| | localhost:5432/testdb as testuser | Line 1 | testpass | | localhost:5432/proddb as postgres | Line 2 | postgrespass | | anyhost:5432/anydb as admin | Line 3 | adminpass | | localhost:5432/testdb as postgres | Line 2 | postgrespass | ## Creating an Auth Profile 1. Open the **DBCode** activity bar 2. Navigate to the **Authentication Profiles** section 3. Click the **+** (Create) icon 4. Select **.pgpass File** as the type 5. Choose the file location: - **Default Location** for standard `.pgpass` path - **Custom Path** to specify a different file 6. Click **Save** ## Using with PostgreSQL Connections 1. Create or edit a PostgreSQL connection 2. In the **Authentication** section, select your pgpass profile 3. Enter the username (password will be read from `.pgpass`) 4. Save and connect ## Supported Databases The .pgpass authentication profile is available for: - PostgreSQL - Amazon Redshift (uses PostgreSQL protocol) - CockroachDB - Other PostgreSQL-compatible databases ## Troubleshooting ### "No matching entry found in .pgpass" **Cause**: No entry in the file matches the connection parameters. **Solutions:** - Verify the hostname, port, database, and username match an entry - Check for typos in the `.pgpass` file - Add a wildcard entry as a fallback: `*:*:*:username:password` - Remember: first match wins, so order matters ### "Password file not found" **Cause**: The `.pgpass` file doesn't exist at the expected location. **Solutions:** - Create the file at the default location (`~/.pgpass` on Unix) - Or use "Custom Path" and specify the correct location - Check that the file path is correct and accessible ### "Failed to read password file" **Cause**: File permission or access issues. **Solutions:** - Ensure the file is readable by your user - On Unix, file permissions should allow read access - Check that the path doesn't contain invalid characters ### Hidden files not visible in file picker (macOS) **Cause**: macOS hides files starting with `.` by default. **Solution**: Press `Cmd+Shift+.` in the file picker to show hidden files. ## Security Considerations - Store `.pgpass` files with appropriate permissions - On Unix systems, PostgreSQL tools typically require `chmod 600 ~/.pgpass` - Consider using a secret manager with [Command authentication](/docs/authentication-profiles/command) for production environments - The `.pgpass` file stores passwords in plain text ## Related Documentation - [Authentication Profiles Overview](/docs/authentication-profiles) - [PostgreSQL Connection Guide](/docs/supported-databases/postgresql) - [Command Authentication](/docs/authentication-profiles/command) (for secret manager integration) --- ## Docs > Cloud Providers ### index --- title: Cloud Providers description: Connecting to a cloud provider enables streamlined access, without needing to setup database specific connections or credentials. sidebar: hidden: true order: 3 --- --- ## Docs > Cloud Providers > Connect ### Connect a cloud provider Follow these steps to set up a connection to a cloud provider. ## Add Click on the "Add Connection" icon in the DBCode extension. ![Add connection button](./add.png) ## Select Cloud providers appear in the connection picker alongside the databases. Scroll to the **Cloud Providers** section (or type the provider's name in the search box), then click the provider you want to connect to. ![Select cloud provider](./select-provider.png) For this guide we will use the Turso provider, but the process is the same across all providers. ## Name Enter a name for the connection. This name will be displayed in the DBCode Explorer. You can connect to the same provider multiple times, for example, if you have separate production and development accounts. ![Enter connection name](./enter-name.png) ## Use Expand the provider in the DBCode Explorer. ![Expand cloud provider](./use.png) The first time you do this, the provider will prompt you for authentication details, which vary by provider. ![Enter credentials](./credentials.png) Refer to the detailed information in this section for specific requirements for each provider. ## Access Your Databases Navigate through the projects and databases within the provider to access your databases. ![Navigate provider databases](./navigate.png) You can now run queries, manage data, and utilize all the features of the DBCode extension with your cloud provider's databases. ## Security The credentials you enter for a cloud provider are stored in the Visual Studio Code secret storage facility and are not synced across Visual Studio Code instances, ensuring they remain only on your computer. --- ## Docs > Cloud Providers > Supported Providers ### Aiven ## Requirements To set up Aiven with DBCode, you will need an authentication token. You can obtain an authentication token by following the instructions provided on the Create authentication tokens page. ### SSL Certificates Several Aiven services require project-specific SSL certificates. DBCode will automatically download and use these certificates when connecting to Aiven services via the Aiven cloud provider. ## Connecting Once you have your authentication token, follow the steps in the [connect a cloud provider](/docs/cloud-providers/connect) article. For more information about Aiven, check out their website. --- ### Azure ## Requirements Azure cloud provider uses the Microsoft Authentication provider from Visual Studio Code. Once you add the Azure cloud provider, you will be prompted to sign in to your Azure account. ## Supported Databases The supported databases are: - Azure SQL Server - Azure PostgreSQL - Azure MySQL Connections to these databases are performed using Microsoft Entra ID authentication, which needs to be enabled for each database in the Azure portal. ## Connecting To connect to Azure, follow the steps in the [connect a cloud provider](/docs/cloud-providers/connect) article. For more information about Azure, check out what is Azure. --- ### Cloudflare ## Requirements To set up Cloudflare with DBCode, you will need to use an API token. You can obtain your API key by following the instructions provided on the Create Token page. The API Token should have the following permissions: - Account - Account Settings - Read - Account - D1 - Edit - Account - Workers R2 Storage - Read - Account - Workers R2 Data Catalog - Read - Account - Workers R2 SQL - Read Expanding an account shows a **D1** connection and an **R2 SQL** connection; open either to see its databases or catalog-enabled buckets. Permission problems with a product's token surface when you connect, not while browsing. **R2 SQL needs all three R2 permissions.** R2 SQL queries the underlying Iceberg data files using credentials that inherit your token's R2 storage permission, so a token with only R2 Data Catalog and R2 SQL read can list your catalog-enabled buckets in the tree but returns a `Corrupted Catalog` error when you run a query. Add **Workers R2 Storage - Read** to fix it. ## Connecting Once you have your API token, follow the steps in the [connect a cloud provider](/docs/cloud-providers/connect) article. For more information about Cloudflare, check out their website. --- ### Supported Providers export const providers = (await getCollection('docs', (page) => { return page.id.startsWith('docs/cloud-providers/supported-providers/') && page.id !== 'docs/cloud-providers/supported-providers'; })); export const logos = import.meta.glob('./*.svg', { eager: true, query: '?url', import: 'default' });
{providers.map(provider => { const name = provider.id.replace('docs/cloud-providers/supported-providers/', ''); const logoUrl = logos[`./logo-${name}.svg`]; const label = provider.data.sidebar?.label || provider.data.navTitle || provider.data.title; return (
{logoUrl && ( {label} )}
); })}
#### How to Connect To connect to any of these providers, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Your Provider**: Choose the desired cloud provider from the list on the right. 4. **Authenticate**: Follow the authentication process specific to the provider. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to each provider, refer to the [connect a cloud provider](/docs/cloud-providers/connect) article. By supporting these leading cloud providers, DBCode ensures you have the flexibility and power to manage your databases efficiently and effectively within your development environment. --- ### Neon ## Requirements To set up Neon with DBCode, you will need to use an API key. You can obtain your API key by following the instructions provided on the Neon API key setup page in the dashboard. ## Connecting Once you have your API key, follow the [connect a cloud provider](/docs/cloud-providers/connect) article. For more information about Neon, check out their website. --- ### Supabase ## Requirements To set up Supabase with DBCode, you will need an access token. You can obtain an access token by following the instructions provided on the Access Tokens page in the dashboard. ## Connecting Once you have your access token, follow the steps in the [connect a cloud provider](/docs/cloud-providers/connect) article. DBCode connects through the Supabase connection pooler using temporary credentials from the Supabase Management API. No permanent database users are created. For more information about Supabase, check out their website. --- ### Turso ## Requirements To set up Turso with DBCode, you will need to use an API token. You can obtain your API token by following the instructions provided on the API Token page in the dashboard. ## Connecting Once you have your API key, follow the [connect a cloud provider](/docs/cloud-providers/connect) article. For more information about Turso, check out their website. --- ## Docs > Connections ### index --- title: Connections description: Connect with our documentation on connections, including automatic ssl, zero-config setup, and SSH tunnels. sidebar: hidden: true order: 2 --- --- ## Docs > Connections > Auto Ssl ### Automatic SSL for known hosts When connecting to a host that matches our known hosts list below, the connection will automatically be configured to utilize SSL, enhancing security by encrypting data in transit. This includes automatically downloading any required public certificates, which verify the server's identity and ensures a trusted communication channel. SSL protects sensitive data from interception and tampering, providing peace of mind and a safer environment for your database operations. ## Known Hosts - AWS RDS - Azure SQL - CockroachDB Cloud - Neon - Supabase - Timescale - YugabyteDB --- ## Docs > Connections > Color ### Color-code connections Assigning custom colors to your connections in DBCode helps you visually separate environments like development, staging, and production. ## Adding a Color to a Connection 1. **Open DBCode in Visual Studio Code:** - Select the DBCode icon in the Activity Bar. 2. **Select the Connection:** - In the DBCode Explorer, locate the connection you want to color. 3. **Set a Connection Color:** - Right-click the connection and choose **Edit Connection** from the context menu. - In the **Edit Connection** tab, use the color swatch next to **Connection name** to choose a color. - Select **Save connection** to apply the color. ![Setting a connection color](./set-color.png) After saving, the selected color appears in these places by default: - The connection item in the DBCode Explorer. DBCode colors the connection name and status indicators, like the default marker and connected indicator, while leaving the main database icon unchanged. - Primary key indicators for tables in that connection. - Editor tabs associated with the connection. - SQL file headers associated with the connection. ## Modifying Color Settings in the Extension Settings You can choose where DBCode applies connection colors in Visual Studio Code: 1. **Open Settings:** Press Cmd+, on macOS or Ctrl+, on Windows and Linux. 2. **Search for DBCode color settings:** Search for `DBCode connection color`. 3. **Configure DBCode color settings:** Adjust the DBCode color settings for editor tabs, the status bar, and the command center. ![DBCode color settings](./customize-extension-settings.png) ## Additional Notes DBCode keeps the selected color for that connection across Visual Studio Code restarts. The extension settings control which VS Code surfaces also use the color. --- ## Docs > Connections > Connect ### Connect to a saved connection Connect to a saved connection in DBCode with a single click. ## Connecting 1. Click the **DBCode** icon in the Activity Bar to open the DB Explorer ![DBCode sidebar showing the Connections panel with saved connections](./dbcode-icon.png) 2. Click on a saved connection to connect. You can also right-click and select **Connect** from the context menu 3. If the connection requires authentication (such as a password), a prompt appears. Enter the credentials to complete the connection Once connected, a dot appears next to the connection name. Expand the connection to browse schemas, tables, views, and other database objects. ![Connected connection showing tables, views, and types in the tree](./active-connection.png) ## Cancelling a Connection Attempt While a connection is being established, a **Cancel Connection Attempt** button appears on the connection. Click it to abandon the attempt, for example when the server is unreachable because a VPN is down, and retry immediately once the network is back. Attempts that receive no response also time out on their own after the connection timeout, so a connection never stays stuck connecting. ## Disconnecting Select a saved connection to reveal the toolbar icons. Click the **Disconnect** button (the first icon) to end the session. You can also right-click the connection and select **Disconnect** from the context menu. ![Selected connection showing toolbar icons including disconnect, edit, copy, and delete](./disconnect.png) Your saved connection settings are retained for future use. Disconnecting only ends the active session. --- ## Docs > Connections > Copy ### Duplicate a connection Duplicate an existing connection to reuse its settings, useful when you need a similar connection with minor changes like a different database, user, or role. ## How to Copy 1. Select a saved connection to reveal the toolbar icons. Click the **Copy Connection** button (the clipboard icon) to create a duplicate ![Selected connection showing toolbar icons including copy connection](./copy-connection.png) 2. A **New Connection** tab opens with all settings pre-filled from the original. The name defaults to the original name with "Copy" appended ![New Connection form with pre-filled settings from the copied connection](./save-changes.png) 3. Modify any settings you need (name, server, credentials, database) then click **Save** The copy appears in the Connections panel alongside the original. ![Connections panel showing both the original and copied connection](./duplicated-connection.png) You can also right-click a connection and select **Copy Connection** from the context menu. ## When to Copy - **Multiple environments** - Copy a production connection and change the host for staging or development - **Different credentials** - Same server, different user or role - **Testing variations** - Experiment with connection settings without affecting the original --- ## Docs > Connections > Create ### Create a connection Set up a new database connection, link a cloud provider, or explore with the sample database included in the DBCode extension. 1. **Open DBCode:** - Select the DBCode icon in the Activity Bar. 2. **Add a connection:** - Select **Add Connection** in the Connections view, or select the **+** icon in the Connections header. ![Add Connection in the Connections header](./add-connection.png) 3. **Choose a database type:** - Select a database tile, filter the available databases, or paste a connection string into the search field. ![Database type selection](./new-connection.png) 4. **Enter the connection details:** - **Connection name:** Enter a recognizable name for the connection. - **Host and port or socket:** Enter the server address and port, or select a socket connection when supported. - **Authentication method:** Choose the method required by your database. - **Username and password:** Enter the credentials when the selected authentication method requires them. - **Password storage:** Choose whether DBCode stores the password in Visual Studio Code Secret Storage. - **Database:** Select or enter the database to open. - **SSL and advanced settings:** Configure these options when your server requires them. The available fields vary by database type. 5. **Test and save the connection:** - Select **Test** to verify the details, then select **Save connection**. ![Test and save a connection](./save-connection.png) The saved profile appears under Connections. Select or expand it to connect and explore the database. ## Connecting a Cloud Provider Connecting a cloud provider allows you to access multiple databases within that provider, without the need for individual configurations. For more detailed instructions, refer to the [Cloud Provider Integration Guide](/docs/cloud-providers). ## Exploring with the Sample Database To quickly explore DBCode's features, use the built-in sample database: 1. Open the DBCode view in the Activity Bar. 2. Select **Explore With a Sample Database** in the Connections view. ![Explore With a Sample Database](./sample-database.png) DBCode creates and opens the built-in SQLite sample connection so you can explore its tools without configuring a server. --- ## Docs > Connections > Delete ### Delete a connection Deleting a connection removes its saved connection details from DBCode. It does not delete any data in the database itself. 1. **Open DBCode in Visual Studio Code:** - Select the DBCode icon in the Activity Bar. 2. **Locate the Connection to Delete:** - In the DBCode Explorer, find the connection you want to delete. Disconnect it before proceeding. 3. **Delete the Connection:** - Right-click the connection and select **Delete Connection** from the context menu. ![Delete connection option](./delete-connection.png) - If DBCode asks for confirmation, confirm the deletion. 4. **Connection Removed:** - The connection will be removed from your list, and it will no longer be accessible in DBCode. - If you need to connect to this database again, recreate the connection. For more information, see the [create connection](../create/) article. ## Important Notes - **Deleting a Grouped Connection:** If the connection is part of a group, only the specific connection will be deleted, not the entire group. - **Data Safety:** Deleting a connection in DBCode only removes the saved connection details. It does not delete any data in the database itself. --- ## Docs > Connections > Edit ### Edit connection settings Update and modify existing database connection settings in DBCode to keep your connections up-to-date and working efficiently. 1. **Open DBCode in Visual Studio Code:** - Start Visual Studio Code, then select the DBCode icon in the Activity Bar (typically on the left side). ![DBCode icon in VS Code](./dbcode-icon.png) 2. **Locate Your Connection:** - In the DBCode `Connections` pane, find the list of your saved connections. - Then click on pencil icon besides connection name or right-click on the connection you want to modify, then choose **Edit Connection** from the context menu. ![Edit connection option](./edit-connection.png) 3. **Update Connection Details:** - A settings panel will open, allowing you to adjust the connection details, common details include: - **Server Name:** Update the connection name if needed. - **Type:** Modify the database type (e.g., MySQL, PostgreSQL) if it has changed. - **Host:** Change the server's host address, such as updating to a new IP or domain. - **Port:** Update the port number if the server port has changed (e.g., 3306 for MySQL, 5432 for PostgreSQL). - **Username:** Enter a new username if access credentials have changed. - **Password:** Update the password for secure access. - **Database:** Adjust the database name if connecting to a different one within the same server. 4. **Save the Updated Connection:** - After making the necessary changes, click **Save** to apply the updates to the connection. ![Save connection button](./save-connection.png) DBCode will test the new settings to ensure the connection works correctly. If any details are incorrect, you'll receive an error message to help troubleshoot. --- ## Docs > Connections > Folder Connections ### Folder Connections Set a connection and database for a folder, and DBCode automatically uses it for any `.sql` file you open inside that folder - so you don't have to pick a connection each time. Subfolders inherit the folder's connection, so new files and folders just work. This is useful when a single workspace holds SQL for several databases at once, where each folder maps to a different environment, module, or business. ## Setting a Folder's Connection Right-click any folder in the VS Code file explorer and select **Set Folder Connection with DBCode**, then choose the connection and database for that folder. Now open a `.sql` file under that folder and DBCode selects that connection for it automatically - you'll see it in the status bar and code lens, with no prompt. The choice is saved to your workspace settings. ## How It Works A folder connection is the default DBCode uses for `.sql` files inside the folder that don't already have a connection of their own. When you open such a file, DBCode finds the most specific folder connection that matches the file's path and assigns it: - **Subfolder inheritance** - a connection set on `reports/` applies to every `.sql` file beneath it, including ones in subfolders you create later. There's nothing to update as the folder structure grows. - **Most specific wins** - if you've set a connection on both `reports/` and `reports/prod/`, files in `reports/prod/` use the `reports/prod/` connection. - **Your choice always wins** - the folder connection is only a default. If you pick a connection for a specific file yourself (from the status bar or code lens), DBCode remembers that choice for the file and uses it instead. A folder connection is a default, not a lock. DBCode never silently switches a file: the assigned connection is always shown in the status bar and code lens, so you can see which database a file is set to before you run anything. ## Configuration Folder connections are stored in the `dbcode.connectionBindings` setting as an array: ```json "dbcode.connectionBindings": [ { "path": "reports/sales/**", "connectionId": "...", "database": "sales" }, { "path": "reports/ops/**", "connectionId": "...", "database": "ops", "schema": "public" } ] ``` | Field | Description | |-------|-------------| | `path` | A glob matched against the file's workspace-relative path. Use `/**` to cover everything under a folder. | | `connectionId` | The connection to assign. The **Set Folder Connection with DBCode** command fills this in for you. | | `database` | The database to use. | | `schema` | Optional schema, for connections that support schemas. | The setting is resource-scoped, so folder connections can be defined at the user, workspace, or folder level. Paths are workspace-relative, so workspace-level settings are portable across machines when the workspace is shared via version control. If a folder points at a connection that isn't available on the current machine, it's skipped and the file falls back to prompting for a connection as usual. --- ## Docs > Connections > Group ### Group connections DBCode enables you to organize multiple database connections into groups, helping you manage environments like development, testing, and production efficiently. Grouping connections simplifies navigation and keeps your workspace tidy. ## Creating a Group 1. **Open DBCode in Visual Studio Code** - Launch Visual Studio Code and click the DBCode icon in the Activity Bar (typically on the left side). ![DBCode Icon in VS Code](./dbcode-icon.png) 2. **Select Connections to Group** - In the **Connections Pane**, hold down the Ctrl key (or Cmd on macOS) and select one or more connections to group. - Click the **Add to Group** icon in the toolbar or right-click and select **Add to Group** from the context menu. ![Group connections option](./group.png) - A prompt will appear asking you to name the new group. ![Group naming dialog](./group-name.png) 3. **Name the Group** - Enter a name for the group and press **Enter**. - The selected connections will now be listed under the new group. ![Group created with connections](./group-created.png) ## Adding Connections to an Existing Group 1. **Select a Connection** - Locate the connection in the **Connections Pane** that you want to add to an existing group. 2. **Add to Group** - Click the **Add to Group** icon in the toolbar or right-click the connection and select **Add to Group**. ![Add to group option](./add-to-group.png) - A prompt will appear to choose the group. Select the desired group and press **Enter**. ![Select group dialog](./select-group.png) 3. **Drag and Drop** (Alternative) - Simply drag the connection from the main list and drop it onto the desired group. - The connection will be added to the group. ## Renaming a Group 1. **Locate the Group** - In the **Connections Pane**, find the group you want to rename. 2. **Rename the Group** - Right-click the group name and select **Rename Group** or click the **Rename Group** icon next to the group name. - Enter the new name and press **Enter** to save. ![Rename group option](./rename-group.png) ## Removing a Connection from a Group 1. **Select the Connection** - Locate the grouped connection you wish to remove in the **Connections Pane**. - Hold down the Ctrl key (or Cmd on macOS) to select multiple connections if needed. 2. **Remove the Connection** - Right-click and choose **Remove from Group**, or drag the connection out of the group and drop it into the main list. ![Remove from group option](./remove-from-group.png) - The connection will now appear in the main list, outside any group. ## Deleting a Group 1. **Locate the Group** - Find the group you want to delete in the **Connections Pane**. 2. **Delete the Group** - Right-click the group name and select **Delete Group**, or click the **Delete Group** icon next to the group name. ![Delete group option](./delete-group.png) > **Note:** Deleting a group does not delete its connections. The connections are moved back to the main list. ## Benefits of Grouping Connections - **Organized Workspace:** Keep connections neatly categorized for different environments. - **Quick Navigation:** Easily locate and manage connections within specific groups. - **Flexible Management:** Drag-and-drop functionality and intuitive controls make organizing connections simple. DBCode's grouping feature empowers you to manage database connections effectively, enabling a clean and efficient workspace while supporting streamlined workflows across multiple environments. --- ## Docs > Connections > Import ### Import connections from other tools The Import Connection feature in DBCode lets you quickly import connection configurations from tools like Azure Data Studio, pgAdmin, CSV files, and JSON formats, simplifying database setup. ### Supported Formats The Import Connection feature currently supports the following formats: - **Azure Data Studio**: Import connections directly from Azure Data Studio settings files. - **CSV Files**: Import connections from CSV files with user-defined field mappings. - **JSON Files**: Import connections from JSON files, including support for formats like pgAdmin. ### How It Works 1. **Command Execution**: Start the import process by running the `DBCode: Import Connections` command from the Command Palette. 2. **Source Selection**: Choose the source of the connection configurations (e.g., Azure Data Studio, CSV, JSON). 3. **File Selection**: Select the file containing the connection configurations. 4. **Format Selection** (if needed): For CSV and JSON files, select the appropriate format or define custom field mappings. 5. **Preview & Confirmation**: Review the imported connections and confirm the import. 6. **Import**: Connections are added to DBCode and ready for use. ### Benefits - **Quick Setup**: Import connections without manual configuration. - **Versatile Formats**: Supports Azure Data Studio, pgAdmin, CSV, JSON, and custom mappings. - **Seamless Integration**: Works directly with DBCode's connection management system. --- ## Docs > Connections > Monitoring ### Server monitoring and sessions Monitoring gives you real-time visibility into your database servers directly within VS Code. Track active sessions, performance metrics, locks, replication status, and server info without leaving your editor. ![PostgreSQL monitor overview in DBCode](./overview.png) ## Supported Databases Monitoring is available for databases that expose server-level statistics. The categories available depend on the database: | Database | Sessions | Performance | Locks | Replication | System Info | |----------|----------|-------------|-------|-------------|-------------| | PostgreSQL | Yes | Yes | Yes | Yes | Yes | | MySQL / MariaDB | Yes | Yes | Yes | Yes | Yes | | SQL Server | Yes | Yes | Yes | AlwaysOn only | Yes | | Oracle | Yes | Yes | Yes | Data Guard only | Yes | | DB2 | Yes | Yes | Yes | - | Yes | | Snowflake | Yes | Yes | - | - | Yes | | MongoDB | Yes | Yes | Yes | Replica sets only | Yes | | Redis / Valkey | Yes | Yes | - | - | Yes | | Cassandra / ScyllaDB | Yes | Yes | - | - | Yes | | Elasticsearch / OpenSearch | Yes | Yes | - | - | Yes | | Neo4j / Memgraph | Yes | Yes | - | - | Yes | | InfluxDB | Yes | Yes | - | - | Yes | | Databricks | Yes | Yes | - | - | Yes | | Hive / Impala | Yes | Yes | - | - | Yes | | DynamoDB | Yes | Yes | - | - | Yes | Embedded databases (SQLite, DuckDB, PGLite) do not have a server process and are not supported. ## Opening the Monitor - **From the tree** - Expand a connection, click the **Monitoring** node, and select a category. - **Right-click a connection** - Select **Server Monitor** from the context menu. - **Command Palette** - Run **DBCode: Server Monitor** and pick a connection. If a monitoring panel is already open for a connection, it will be focused rather than opening a duplicate. ![Open Server Monitor from the connection context menu](./open-monitor.png) ## Health Summary A row of metrics in the panel header shows the at-a-glance health of the server. It typically includes: - **Sessions** - Count of active client sessions - **Long-running** - Count of sessions whose duration exceeds the alert threshold (only shown when greater than zero) - Key metrics that have known healthy ranges (cache hit ratio, CPU usage, deadlocks per second, etc.) Each metric shows its current value colored by status: green when healthy, yellow when warning, red when critical. Thresholds are encoded per-metric and per-driver (for example, cache hit ratio below 95% is yellow, below 90% is red). ## Sessions The Sessions tab shows all active connections to the server. Each row includes the user, client app, current query, session state, and duration. The columns shown depend on the database. PostgreSQL shows wait events and application name, MySQL shows the command type and thread state, SQL Server shows the program name and command. ![Sessions tab in the PostgreSQL monitor](./sessions.png) Long-running queries are highlighted: rows whose duration exceeds the configured threshold get a yellow or red tint, and a notification appears with a one-click option to kill the session. ### Actions Right-click a session row for available actions: - **Cancel Query** - Stops the running query but keeps the session connected. Available on PostgreSQL, MySQL, Oracle, and Snowflake. - **Kill Session** - Terminates the connection entirely. Available on all databases that support monitoring. Both actions require confirmation. The context menu only shows actions the connected database supports. ## Performance The Performance tab shows server metrics organized into groups (Connections, Throughput, Cache, Memory, CPU, Issues, I/O, Storage). Each group is a horizontal strip of cards with the group label on the left. Card width adapts to the largest group on the panel so every card lines up regardless of how many metrics are in its group. ![Performance metrics in the PostgreSQL monitor](./performance.png) ### Metric cards Each card shows: - The metric label, with a small info icon when a description is available. Hover the icon (or the label) to read what the metric measures and what healthy values look like. - The current value, formatted in the metric's natural unit (count, bytes, percent, ms, ratio). - A progress bar when the metric has a known maximum. - A sparkline showing the recent history. Bars are individually colored: green when the historical value was healthy, yellow for warning, red for critical, so you can spot when a metric was bad even after it has recovered. The cards retain up to 10 hours of history. The compact view always shows the latest 60 samples. ### Sparkline interactivity - **Hover any bar** to see that sample's value, local clock time, and how long ago it happened. The hover state propagates across every other card so you can read what every metric was doing at the same point in time. - **Click a bar** to pin the hover state. Click it again (or a different bar) to move or release the pin. - **Click the expand icon** on a card to grow it inline and reveal the full retained history. Multiple cards can be expanded at once for side-by-side correlation. Click the icon again to collapse. ### Common metrics The exact set depends on the database server, but common metrics include: - **Connections** - Current connection count against the server maximum - **Throughput** - Transactions, queries, or operations per second - **Cache Hit Ratio** - How effectively the database is using its buffer cache - **Memory Used** - Memory consumed by the database process - **CPU Utilization** - Percentage of CPU used by the database process - **Deadlocks per second / Lock Waits** - Indicators of transaction contention - **Slow Queries / Temp Disk Tables** - Workload symptoms - **Database Size** - Total storage used ## Locks The Locks tab shows current database locks, helping you identify blocking situations. Key information includes the lock type, mode, whether the lock has been granted, and which session is the blocker. Locks are nested under their blocker so you can see the dependency tree at a glance. ## Replication The Replication tab shows the state of database replication when configured. The information varies by database: - **PostgreSQL** - Streaming replication lag (write, flush, replay), LSN positions, subscriber state - **MySQL / MariaDB** - IO/SQL thread status, seconds behind source, relay log position - **SQL Server** - AlwaysOn availability group replica states and synchronization health - **Oracle** - Data Guard transport and apply lag - **MongoDB** - Replica set member states, health, and optime This tab only appears for databases where replication monitoring is supported. It shows empty if replication is not configured on the server. ## System Info The System Info tab shows server-level metadata that doesn't change during a session, grouped by section (Server, Host, Database). Typical entries include the server version and edition, host CPU count and memory, recovery model, collation, and compatibility level. This data is fetched once on panel open and never refreshed automatically (it doesn't change). Closing and reopening the panel will fetch it fresh. ## View Modes Toggle between two layouts using the buttons in the header: - **Tabbed** - One category at a time with a tab bar (default) - **All Sections** - All categories stacked vertically. Grid sections can be resized by dragging. Your preference is saved automatically. ## Refresh Data refreshes automatically on a configurable interval (5s, 10s, 30s, or 60s, defaulting to 30s). Use the pause button to freeze the display while examining data, or click refresh for an immediate update. The refresh interval is saved per connection, so each connection remembers your preferred rate. Expanded cards are also remembered between panel sessions. Sessions, Performance, Locks, and Replication are polled on every tick. System Info is fetched once on panel open and stays cached, even on manual Refresh, since the data doesn't change. ## Snapshot Click the copy icon in the panel header to copy a markdown snapshot of every category to your clipboard. The snapshot includes the connection name, current timestamp, current values from the metrics panel, and rows from the grid panels (sessions, locks, replication) formatted as markdown tables. Useful for pasting into a chat message, ticket, or notebook without taking screenshots. ## View SQL Click **View SQL** to open the underlying query in a new editor tab connected to the same database. You can modify and run the query directly, useful for building custom monitoring queries. ## Availability Monitoring is available with a **Pro** or **Team** subscription. --- ## Docs > Connections > Refresh ### Refresh schema after changes Refresh a connected database to pick up the latest schema changes (new tables, columns, views, or other objects) without disconnecting. ![DBCode sidebar showing the Connections toolbar with the Refresh button](./refresh-connection.png) ## How to Refresh - **Toolbar** - Click the **Refresh** button (circular arrow icon) in the Connections toolbar to refresh all connected databases - **Context menu** - Right-click a specific connection and select **Refresh** to refresh just that connection DBCode reloads the list of tables, views, and other database objects, ensuring you're working with the most current schema. ## When to Refresh - **Structure changes** - After creating, altering, or dropping tables, columns, or views outside of DBCode - **Collaboration** - To see changes made by other users or processes on the same database - **Deployments** - After running migrations or DDL scripts --- ## Docs > Connections > Roles ### Read-only mode and roles DBCode's Connection Roles feature provides granular control over database interactions, helping prevent accidental modifications and ensuring appropriate access levels based on your environment context (development, testing, or production). ## Key Features Connection Roles offer two primary security mechanisms: 1. **Read-Only Mode**: Restricts all connections to read-only operations, preventing any data modifications 2. **Environment Roles**: Configures statement permissions based on the connection's intended use (Development, Testing, or Production) ## Read-Only Mode The read-only mode provides a simple safeguard against unintended data modifications. | Feature | Description | |---------|-------------| | Availability | Depends on database driver support | | Effect | Restricts connection to `SELECT` statements only | | Override | Not possible without changing connection settings | | Best for | Production data exploration, reporting connections | ### Enabling Read-Only Mode 1. Open the connection settings dialog 2. Find the **Role** section 3. Check the **Read Only** option if enabled 4. Save your connection > **Note**: Not all database drivers support read-only connections. If unsupported, this option will be disabled. ## Environment Roles Environment roles provide a more nuanced approach to connection permissions by defining what types of SQL statements are allowed based on the connection's purpose. ![Role section in connection settings showing Read Only toggle and Production role selected](./connection-role.png) ### Available Roles | Role | Typical Use Case | Default Permissions | |------|------------------|---------------------| | Development | Local development work | Most permissive; allows all statement types | | Testing | Integration/QA environments | Moderately restrictive; prevents schema changes | | Production | Live production databases | Most restrictive; limits potentially dangerous operations | ## Statement Type Permissions For each role, you can configure permissions for different SQL statement types using three permission levels: | Permission | Behavior | |------------|----------| | Allowed | Statements execute without confirmation | | Ask First | Confirmation prompt appears before execution | | Denied | Statements are blocked from execution | ### Configurable Statement Types | Statement Type | Description | Examples | |----------------|-------------|----------| | SELECT | Data retrieval operations | `SELECT * FROM table` | | INSERT | Data addition operations | `INSERT INTO table VALUES (...)` | | UPDATE | Data modification operations | `UPDATE table SET col = value` | | DELETE | Data removal operations | `DELETE FROM table WHERE ...` | | TRUNCATE | Table clearing operations | `TRUNCATE TABLE table` | | EXECUTE | Procedure/function calls | `EXEC procedure`, `CALL function()` | | CREATE | Object creation operations | `CREATE TABLE`, `CREATE VIEW` | | ALTER | Object modification operations | `ALTER TABLE ADD COLUMN` | | DROP | Object removal operations | `DROP TABLE`, `DROP DATABASE` | | TRANSACTION | Transaction control operations | `BEGIN TRANSACTION`, `COMMIT`, `ROLLBACK` | | MAINTENANCE | Database maintenance operations | `VACUUM`, `OPTIMIZE`, `ANALYZE TABLE` | | SET/USE | Session/database switching | `SET search_path`, `USE database` | | GRANT/REVOKE | Permission management | `GRANT SELECT`, `REVOKE ALL` | | OTHER | Other statement types | Database-specific operations | | Missing WHERE | DELETE/UPDATE without a WHERE clause | `DELETE FROM users`, `UPDATE orders SET status = 'x'` | | Auto-Commit | Default auto-commit mode (boolean, not a permission) | Overrides global `defaultAutoCommit` setting | ## Default Permission Matrix | Statement Type | Development | Testing | Production | |----------------|-------------|---------|------------| | SELECT | Allowed | Allowed | Allowed | | INSERT | Allowed | Allowed | Ask First | | UPDATE | Allowed | Allowed | Ask First | | DELETE | Allowed | Allowed | Ask First | | TRUNCATE | Allowed | Allowed | Denied | | EXECUTE | Allowed | Allowed | Ask First | | CREATE | Allowed | Ask First | Denied | | ALTER | Allowed | Ask First | Denied | | DROP | Allowed | Ask First | Denied | | TRANSACTION | Allowed | Allowed | Allowed | | MAINTENANCE | Allowed | Allowed | Ask First | | SET/USE | Allowed | Allowed | Allowed | | GRANT/REVOKE | Allowed | Ask First | Denied | | OTHER | Allowed | Ask First | Ask First | | Missing WHERE | Ask First | Ask First | Denied | | Auto-Commit | Not set | Not set | Not set | ## Configuring Connection Roles ### Setting the Connection Role 1. Open the connection settings 2. Navigate to the **Roles** section 3. Select the appropriate role (Development, Testing, or Production) 4. Click **Save** to update the connection ### Customizing Statement Permissions 1. Open **Settings** in VS Code 2. Navigate to **Extensions** > **DBCode** > **Connection Roles** 3. Find the role you want to customize (Development, Testing, or Production) 4. For each statement type, select the desired permission level from the dropdown: - **Allow**: Statements execute without confirmation - **Ask**: Confirmation prompt appears before execution - **Deny**: Statements are blocked from execution 5. Changes are automatically saved and applied to all connections using that role ![Role settings for the Production role showing a mix of allow, ask, and deny permissions](./role-settings-production.png) ## Auto-Commit Per Role Each role can specify a default auto-commit mode using the `autoCommit` setting. This overrides the global `dbcode.transactions.defaultAutoCommit` setting for connections using that role. For example, to always start with auto-commit OFF on production connections: ```json { "dbcode.connection.role.production": { "select": "allow", "insert": "ask", "update": "ask", "delete": "ask", "truncate": "deny", "autoCommit": false } } ``` When `autoCommit` is not set on a role, the global `dbcode.transactions.defaultAutoCommit` setting is used. See [Transaction Control](/docs/query/transaction-control) for more details. ## Use Cases ### Safeguarding Production Databases - Select the **Production** role for live database connections - Critical operations require confirmation, preventing accidental data loss - Destructive operations like `DROP` and `TRUNCATE` are blocked entirely ### Development Workflow - Use **Development** role for local database instances - Allow unrestricted operations during active development - Switch to **Testing** role when working with shared QA environments ### Teaching Environments - Configure custom permissions for student database access - Allow `SELECT` but require confirmation for data modifications - Prevent schema changes entirely ## Benefits of Connection Roles - **Mistake Prevention**: Adds confirmation steps for potentially destructive operations - **Customizable Security**: Tailor permissions to your team's needs and risk tolerance - **Confidence**: Work with production data knowing safeguards are in place Connection Roles provide an additional layer of security and awareness when working with important databases, helping prevent costly mistakes while maintaining productivity. --- ## Docs > Connections > Schema ### Schema loading and caching DBCode introspects your database schema to populate the explorer tree with tables, views, columns, indexes, and other objects. For large databases with thousands of objects, this can take time. The schema loading settings let you optimize this process. ## Progressive Loading Progressive loading (experimental) changes how DBCode fetches schema information: - **Standard mode**: Fetches all schema details (columns, indexes, keys) upfront when connecting - **Progressive mode**: Fetches only object names initially, then loads details on-demand as you expand items This can significantly reduce initial connection time for large databases. ### When to Use Progressive Loading Progressive loading is beneficial when: - Your database has hundreds or thousands of tables/views - Initial connection takes several seconds or longer - You typically work with a small subset of tables - You're connecting over a slow network ### Enabling Progressive Loading 1. Open the connection settings (right-click connection → **Edit**) 2. Expand the **Advanced** section 3. Find the **Introspection** subsection 4. Enable **Progressive Loading (experimental)** Once enabled, additional options become available: ## Settings ### Prefetch Details When enabled (default), DBCode fetches full schema details in the background after the initial connection completes. This gives you fast initial load times while still populating the full schema for features like autocomplete. - **Enabled**: Best of both worlds - fast connection, full schema eventually - **Disabled**: Only fetch details when you explicitly expand items ### Batch Size Controls how many objects are fetched per request when loading details. Higher values mean fewer requests but larger payloads. - **Default**: 15-50 depending on database type - **Lower values**: Better for slow connections or rate-limited APIs - **Higher values**: Better for fast connections with many objects ### Cache TTL How long (in days) cached schema details remain valid before being refreshed. - **Default**: 7 days - **Lower values**: More frequent refreshes, always up-to-date - **Higher values**: Less network traffic, faster subsequent connections The cache is stored locally and survives VS Code restarts. Use the **Refresh** command on a connection to force a cache refresh. ## Supported Databases Progressive loading is currently available for: - MySQL / MariaDB - Trino - Athena Support for additional databases is being added progressively. ## Tips - If you notice stale schema information, right-click the connection and select **Refresh** - The cache is per-connection, so each connection maintains its own cached schema - Disabling prefetch reduces background network activity but may slow down autocomplete until objects are expanded --- ## Docs > Connections > Ssh Tunnels ### SSH tunnels DBCode supports two types of tunnels for connecting to databases that aren't directly accessible: - **SSH Tunnels**: Traditional secure shell tunnels that forward traffic through an SSH server - **Command Tunnels**: Local proxy processes that handle authentication and connection forwarding (e.g., Google Cloud SQL Auth Proxy, AWS SSM, kubectl port-forward) Once configured, tunnels can be selected when creating or editing database connections. ## SSH Tunnels SSH tunnels create a secure, encrypted connection through an intermediate SSH server to reach your database. ### Automatic Discovery DBCode can automatically discover SSH tunnel configurations from your system's SSH config file. If you have existing configurations, they will be automatically detected and displayed in the Tunnels section of the DBCode Explorer with a compass icon (🧭) ![Discovered SSH tunnels](./discovered.png) ### Manual Configuration If you prefer to manually create SSH tunnel configurations, follow the steps below. Manual configurations allow for flexible authentication options, including username/password, SSH agent, or key-based authentication. #### Add Click the + icon in the Tunnels section of the DBCode Explorer ![Adding a new SSH tunnel](./new.png) #### Configure - **Name**: Enter the name for the tunnel. - **Host**: Enter the hostname or IP address of the remote server. - **Port**: Specify the port to use for the SSH connection (default is usually 22). - **Username**: Enter the username for the SSH connection. - **Authentication Method**: - **Username/Password**: Provide the password associated with the username. - **SSH Agent**: Use the SSH agent running on your system to manage keys. - **Key-Based Authentication**: Specify the path to your private key file, and optional password. ![SSH tunnel configuration form](./form.png) #### Save Save the newly created SSH tunnel configuration by clicking the Save button. ## Command Tunnels Command tunnels spawn a local proxy process that handles authentication and connection forwarding. This is useful for cloud database services that provide their own authentication proxies. ### Common Use Cases - **Google Cloud SQL**: Use `cloud-sql-auth-proxy` for IAM-based authentication to Cloud SQL instances - **Google AlloyDB**: Use `alloydb-auth-proxy` for connecting to AlloyDB with IAM authentication - **AWS SSM**: Use AWS Systems Manager Session Manager for secure port forwarding to RDS instances - **Kubernetes**: Use `kubectl port-forward` to connect to databases running in Kubernetes clusters ### Creating a Command Tunnel 1. Click the + icon in the Tunnels section of the DBCode Explorer 2. Select **Command** as the tunnel type 3. Configure the tunnel settings: - **Name**: A descriptive name for the tunnel - **Preset**: Select a preset for common tools or enter the details manually - **Command**: The executable to run (e.g., `cloud-sql-auth-proxy`, `kubectl`) - **Arguments**: Command arguments with variable substitution support - **Ready Pattern**: Optional regex pattern to detect when the proxy is ready - **Timeout**: How long to wait for the proxy to become ready (default: 10 seconds) ### Variable Substitution Arguments support the following variables that are replaced at runtime: | Variable | Description | Example | |----------|-------------|---------| | `{localPort}` | Auto-assigned local port | `54321` | | `{remoteHost}` | Database host from connection | `my-db.example.com` | | `{remotePort}` | Database port from connection | `5432` | | `{database}` | Database name from connection | `mydb` | **Important:** Your arguments must include `{localPort}` so DBCode knows which port to connect to after the proxy starts. DBCode assigns an available port, substitutes it into your arguments, starts the proxy, then connects to that port. ### Example Configurations **Google Cloud SQL Auth Proxy:** ``` Command: cloud-sql-auth-proxy Arguments: my-project:us-central1:my-instance --port={localPort} ``` **kubectl port-forward:** ``` Command: kubectl Arguments: port-forward svc/my-postgres {localPort}:{remotePort} -n my-namespace ``` **AWS SSM Port Forward:** ``` Command: aws Arguments: ssm start-session --target i-1234567890abcdef0 --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters host={remoteHost},portNumber={remotePort},localPortNumber={localPort} ``` ## Using Tunnels Once you have a tunnel configured (SSH or Command), you can use it when connecting to your databases. To use a tunnel for a database connection, create a new connection or edit an existing one, then select the tunnel from the **Tunnel** dropdown list. ![Using a tunnel in database connection](./connection.png) ## Active Tunnels When a tunnel is in use, it will show the databases using the tunnel and the IP addresses and ports being mapped for each database. ![Active tunnel](./active.png) ## Tunnel Logs Each tunnel has its own output channel for viewing logs. This is useful for diagnosing connection issues, seeing authentication messages, or debugging command tunnel configuration. To view tunnel logs: 1. Right-click on a tunnel in the Tunnels section 2. Click **View Tunnel Logs** 3. The Output panel will open showing the tunnel's dedicated log channel Alternatively, click the **View Logs** icon in the tunnel's inline actions. The output channel captures stdout and stderr from the tunnel process, including: - Connection status messages - Authentication progress (for command tunnels like `cloud-sql-auth-proxy`) - Error messages and warnings - Port forwarding details --- ## Docs > Connections > Variables ### Variables in connection settings DBCode supports variable substitution in connection settings so you can reference files (like service account JSON or private keys) without hard coding absolute paths. This makes connection configs portable across machines and team members. ## When To Use It - Reference files checked into your repo (e.g., `${workspaceFolder}/secrets/credentials.json`) - Support different local paths for each teammate - Keep credentials in consistent project locations without absolute paths ## Supported Variables - `${workspaceFolder}`: Path of the folder opened in VS Code - `${workspaceRoot}`: Alias for `${workspaceFolder}` - `${home}`: User home directory - `${env:VARIABLE_NAME}`: Value from the environment - Relative paths: Interpreted relative to the workspace folder (e.g., `secrets/key.json`) ## Resolution Order 1. Use the path as is if it's an absolute file path and exists 2. Resolve `${home}` if present 3. Resolve `${env:...}` variables if present 4. For each workspace folder: - Substitute `${workspaceFolder}` / `${workspaceRoot}` - Try the path as workspace relative 5. If no resolution succeeds, connection fails ## Example Configure a BigQuery/Firebase service account key stored in your repo: ```json { "dbcode.connections": [ { "connectionId": "my-service-account", "name": "My GCP Project", "driver": "bigquery", "driverOptions": { "authType": "sa", "key": "${workspaceFolder}/secrets/credentials.json" } } ] } ``` You can also use environment variables, for example: ```json { "driverOptions": { "key": "${env:CREDENTIALS_DIR}/gcp.json" } } ``` SSL key material can live alongside your project as well: ```json { "dbcode.connections": [ { "connectionId": "prod-postgres", "name": "Production", "driver": "postgres", "host": "mydb.company", "sslCACert": "${workspaceFolder}/certs/ca.pem", "sslClientCert": "${workspaceFolder}/certs/client.crt", "sslClientKey": "${home}/.certs/client.key" } ] } ``` ## Where It Applies File based fields in connection definitions automatically support variable substitution, including (but not limited to): - BigQuery: `key` (service account JSON) - Firebase: `key` (service account credentials) - Snowflake: `key`, `keyFile`, `keyFilename`, `privateKeyPath` (private key files) - SSL options: `sslCACert`, `sslClientCert`, and `sslClientKey` Additionally, file based drivers (e.g., SQLite, DuckDB) support variables in their file paths. ## Behavior And Errors - Resolution happens only when connecting; - If a file can't be found after resolution, the connection is aborted. --- ## Docs > Connections > Watched Folders ### Watched Folders Watch a folder of database files and DBCode will automatically discover connections inside it. When files are added or removed, the tree updates in real time. Supported file types: SQLite (`.db`, `.sqlite`, `.sqlite3`), DuckDB (`.duckdb`), Microsoft Access (`.mdb`, `.accdb`), and other file-based formats like Parquet, Excel, and Avro. ## Adding a Watched Folder Right-click any folder in the VS Code file explorer and select **Watch Folder with DBCode**. ![Watch Folder with DBCode in the VS Code Explorer context menu](./watch-folder.png) You'll be asked where to store the configuration: - **Workspace Settings** - Stored relative to your workspace. Portable across machines when committed to version control. - **Global Settings** - Stored as an absolute path. Available in all workspaces on your machine. The folder appears in the **Connections** view as a collapsible node. The number beside its name shows how many connections DBCode discovered. Expand it to see those connections, organized by subfolder structure. ![A watched folder expanded in the Connections view with a discovered SQLite database](./watched-folder-overview.png) ## How It Works When you add a watched folder, DBCode scans it recursively for database files. Each file is matched against known database formats using file extension and header detection (the same mechanism as [Zero Config](/docs/connections/zero-config) discovery). A file system watcher monitors the folder for changes: - **New files** are discovered automatically and added to the tree. - **Deleted files** are removed from the tree. If a deleted file had an active connection, you'll see a warning. ## Managing Watched Folders Hover over a watched folder in the **Connections** view to access inline actions: - **Edit** (pencil icon) - Rename the folder's display name. - **Delete** (trash icon) - Stop watching the folder and remove it from the tree. Right-click a watched folder for additional options: - **Refresh** - Rescan the folder for database files. - **Rename** - Change the display name. - **Delete** - Stop watching the folder. ## Subfolder Structure If your watched folder contains subfolders with database files, the tree mirrors that structure. You can browse through subfolders just like you would in a file explorer. ``` My Databases (watched folder) ├── development/ │ ├── app.db │ └── cache.db ├── testing/ │ └── fixtures.sqlite3 ├── main.db └── analytics.duckdb ``` ## Connections Connections inside watched folders behave like any other connection in DBCode. You can connect, query, and browse schemas as usual. The connection count is shown next to the folder name in the **Connections** view. ## Settings Watched folder configurations are stored in `dbcode.watchedFolders` in your VS Code settings. Each entry contains an ID, display name, and path. Workspace-scoped folders use relative paths, making them portable across machines when the workspace is shared via version control. Global folders use absolute paths. --- ## Docs > Connections > Zero Config ### Zero-config connections DBCode looks for connection information either as a connection string or defined configuration in known formats in the following locations within the root folder: 1. **Env files (*.env):** Files that contain environment variables with connection strings or individual database configuration keys. 2. **Web Config files (web.config):** Configuration files used by web applications that may include connection settings. 3. **DDev (.ddev/config.yaml):** YAML files used by DDev for configurations, including database connection details. If connection information is found and successfully parsed from these files, DBCode will automatically add it as a database connection. DBCode also scans the root directory for compatible database files (`.db`, `.duckdb`, `.sqlite`, `.sqlite3`, `.mdb`, `.accdb`, etc). If a supported file is found, it will be automatically added as a database connection. To watch an entire folder of database files (with subfolder support and live file monitoring), see [Watched Folders](/docs/connections/watched-folders). ## Supported .env Patterns DBCode automatically detects database connections in .env files using two methods: ### Connection String URLs Standard database connection URLs are detected automatically: ```bash DATABASE_URL=postgres://user:pass@localhost:5432/dbname MYSQL_URL=mysql://root:secret@127.0.0.1:3306/mydb REDIS_URL=redis://localhost:6379 ``` ### Individual Key-Value Pairs DBCode also detects common framework patterns that use separate environment variables for each connection parameter. #### Laravel ```bash DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=secret ``` #### Django ```bash DATABASE_NAME=mydb DATABASE_USER=user DATABASE_PASSWORD=pass DATABASE_HOST=localhost DATABASE_PORT=5432 DATABASE_ENGINE=django.db.backends.postgresql ``` #### Spring Boot ```bash SPRING_DATASOURCE_URL=jdbc:postgresql://localhost:5432/mydb SPRING_DATASOURCE_USERNAME=user SPRING_DATASOURCE_PASSWORD=pass ``` #### Node.js / Generic ```bash DB_HOST=localhost DB_PORT=3306 DB_DATABASE=myapp DB_USERNAME=root DB_PASSWORD=secret ``` ### Multiple Connections You can define multiple database connections in a single .env file using prefixes: ```bash PRIMARY_DB_HOST=localhost PRIMARY_DB_PORT=5432 PRIMARY_DB_DATABASE=primary SECONDARY_DB_HOST=remote.example.com SECONDARY_DB_PORT=3306 SECONDARY_DB_DATABASE=secondary ``` ### Driver Detection DBCode automatically determines the database type from: - Explicit connection type (e.g., `DB_CONNECTION=mysql`) - Database engine (e.g., `DATABASE_ENGINE=django.db.backends.postgresql`) - JDBC URL prefix (e.g., `jdbc:postgresql://`) - Port number (e.g., 5432 for PostgreSQL, 3306 for MySQL) ## Discovered Connections Automatically discovered connections are indicated by a compass icon (🧭), making it easy to identify and manage them. The DB Explorer can also be filtered to only show connections that have been discovered automatically by using the compass icon (🧭) at the top of the DB Explorer. ## Workspace Default Connection When DBCode discovers connections from your workspace (e.g., from `.env` files, SQLite databases, or other configuration files), it automatically tracks them as workspace default candidates. This enables teams to share a common workspace configuration without committing credentials. ### How It Works 1. **Explicit setting takes priority**: If you have explicitly set a workspace default connection using the `dbcode.workspaceConnection` setting (via the "Set as Workspace Default" command), that setting always takes priority over discovered connections. 2. **Single discovered connection**: If no explicit setting exists and only one connection is discovered in your workspace, it automatically becomes the workspace default. 3. **Multiple discovered connections**: If multiple connections are discovered, DBCode will prompt you to choose which one should be the default when needed. 4. **Matching saved connections**: If a discovered connection matches an existing saved connection (same driver, host, port), DBCode automatically resolves to the saved connection. This means your team can share `.env` files while each developer uses their own saved credentials. ### Visual Indicators Connections in the DB Explorer show status indicators: - **☆** (star): Indicates the workspace default connection - **●** (dot): Indicates a connected connection - **☆●** (star + dot): Indicates the workspace default that is also connected ### Sharing Across Teams This feature solves the problem of sharing workspace default connections across developers: 1. Commit your `.code-workspace` file to version control 2. Each developer maintains their own `.env` file with credentials (not committed) 3. DBCode discovers the connection from `.env` and uses it as the workspace default 4. If a developer has a matching saved connection, DBCode automatically uses that instead This approach keeps credentials secure while allowing teams to share which connection should be used for the workspace. ## Additional Config Types We recognize that there are many other types of configuration files and formats used for database connections. Please [let us know](https://github.com/dbcodeio/public/issues) if you have specific configuration file types or formats that you need DBCode to support. --- ## Docs > Data > Backup Restore ### Backup & Restore DBCode's Backup & Restore feature allows you to create backups of your databases and restore them when needed. This feature leverages the native backup tools provided by each database engine, offering database-specific options for backup format and content. ## Overview The Backup & Restore feature provides: - **Flexible backup options**: Full backups, schema-only, or data-only - **Format choices**: Database-specific formats optimized for each engine - **Easy restoration**: One-click restore with optional flags - **Progress tracking**: Real-time feedback during backup and restore operations ## Creating a Backup 1. **Navigate to your database** In the **Connections** view, locate the database you want to back up. 2. **Open the backup menu** Right-click the database name and select **Backup Database**. ![Backup Database and Restore Database in a PostgreSQL database context menu](./backup-restore-menu.png) 3. **Configure backup options** Choose your preferred backup type and format (options vary by database engine). 4. **Choose what to back up** For engines whose native tools support it (PostgreSQL, MySQL/MariaDB, MongoDB, and SQLite SQL dumps), DBCode asks whether to back up the whole database or a selected set of objects. Pick **Whole database**, **Selected schemas** (PostgreSQL only), or **Selected tables** (shown as **Selected collections** for MongoDB), then tick the objects to include. Engines that can only produce a full backup, such as DuckDB and SQL Server, skip this step. ![Selecting three tables from the public schema in the PostgreSQL backup wizard](./backup-selected-tables.png) 5. **Select save location** Choose where to save the backup file. DBCode suggests a default filename with the current date. 6. **Wait for completion** A progress notification shows the backup status. You'll receive confirmation when complete. ## Restoring a Backup 1. **Navigate to your database** In the **Connections** view, locate the target database. 2. **Open the restore menu** Right-click the database name and select **Restore Database**. 3. **Select backup file** Choose the backup file to restore. File filters show compatible formats. 4. **Select restore options** Choose any database-specific restore options available for that file type. 5. **Confirm the operation** Review the warning dialog and click **Restore** to proceed. 6. **Wait for completion** A progress notification shows the restore status. The database refreshes automatically when complete. ## Best Practices ### Before Backing Up - **Test your backup strategy**: Verify backups can be restored successfully - **Consider disk space**: Ensure adequate space for backup files - **Use appropriate formats**: Choose formats based on your needs: - Binary formats for speed and completeness - SQL formats for portability and inspection ### Before Restoring - **Create a backup first**: Always backup the current state before restoring - **Verify the backup file**: Ensure the backup file is from a compatible database version - **Check for conflicts**: Be aware of existing data that may conflict with restored data - **Use test databases**: Test restores on non-production databases first ### Backup Naming DBCode automatically generates backup filenames with this format: ``` {database_name}_backup_{YYYY-MM-DD} ``` Example: `mydb_backup_2026-08-01.dump` This naming convention helps you: - Identify the source database - Track the backup date - Organize multiple backup versions ## Security Considerations ### Backup Files - **Protect sensitive data**: Backup files contain all database data, including sensitive information - **Store securely**: Keep backup files in secure locations with appropriate access controls - **Encrypt if needed**: Consider encrypting backup files containing sensitive data - **Clean up old backups**: Regularly remove outdated backups to minimize exposure ### Credentials - DBCode uses secure methods (such as environment variables) to pass credentials to backup tools - Credentials are not stored in backup files - Connection credentials are required when restoring ## Troubleshooting ### Common Issues | Issue | Solution | |-------|----------| | "Backup failed: command not found" | Database client tools may not be installed. DBCode will provide installation instructions. | | "Permission denied" | Ensure you have write permissions for the backup location | | "Insufficient disk space" | Free up disk space or choose a different backup location | | "Restore failed: version mismatch" | Backup may be from a different database version. Check compatibility. | | "Database busy during restore" | Close connections to the database before restoring | ### Error Messages - **"Missing [tool name]"**: Required database client tools need to be installed. DBCode will provide specific installation instructions. - **"Cannot read backup file"**: File may be corrupted or incompatible with the target database - **"Target database not empty"**: Choose restore options to drop existing objects, or manually clear the database first ## Technical Details ### How It Works DBCode uses the native backup and restore tools provided by each database engine to perform these operations. This ensures: - **Compatibility**: Backups use standard formats recognized by each database system - **Reliability**: Native tools are tested and maintained by database vendors - **Feature support**: Full access to database-specific backup options and formats Database tools are typically: - Installed automatically by DBCode when possible - Available from system package managers - Bundled with the database installation DBCode manages the complexity of invoking these tools with the correct parameters, providing a consistent and user-friendly interface regardless of which database engine you're using. The Backup & Restore feature provides a reliable way to protect your database data and migrate databases between environments, all within VS Code. --- ## Docs > Data > Compare ### Compare datasets The Data Compare feature in DBCode allows you to compare data between two datasets, identify differences, and synchronize changes. Compare tables, views, or the results of any SQL query - within the same database, across different databases, or even across different servers and connection types. This is useful for validating data migrations, auditing changes, or keeping data in sync across environments. ## Starting a Comparison There are two ways to start a data comparison: ### From the DB Explorer 1. **Single Selection**: Right-click on a table or view in the DB Explorer and select **Compare Data With...**. A picker will appear allowing you to browse and select the target table. 2. **Multi-Selection**: Hold Ctrl (Windows/Linux) or Cmd (macOS) and click to select exactly two tables or views, then right-click and select **Compare Data With...**. The first selected item becomes the source, and the second becomes the target. #### Row Limit Options When comparing from the DB Explorer, you'll be prompted to select a row limit: - **All rows** - Compare the entire dataset (may be slow for large tables) - **First 1,000 rows** - Quick comparison of a sample - **First 10,000 rows** - Moderate sample size - **First 100,000 rows** - Larger sample for thorough testing #### Progress Tracking The comparison process shows real-time progress with status indicators: 1. **Connect to source** - Establishing connection to the source database 2. **Connect to target** - Establishing connection to the target database (if different) 3. **Load data from source** - Fetching rows from the source table 4. **Load data from target** - Fetching rows from the target table 5. **Analyzing differences** - Computing the diff between datasets ### From the Results Panel Compare the results of any SQL query directly from the Results Panel. This allows you to compare filtered data, joined results, or any custom query output - not just raw table data. All rows in the result sets are compared. - **Context menu** - Right-click on a result tab and select **Compare Data With...** to browse and select another table to compare against. - **Drag and drop** - Drag one result tab onto another while holding Alt (Windows/Linux) or Option (macOS) to compare them directly. - **Multi-select** - Hold Ctrl (Windows/Linux) or Cmd (macOS) and click exactly two tabs, then right-click and select **Compare Data**. ## Understanding the Results The compare view displays a unified grid showing all rows from both datasets with differences highlighted: ![Compare view showing differences between two tables](./compare-overview.png) ### Difference Statistics The toolbar shows summary statistics: - **Total differences** - Combined count of all changes - **+N** (green) - Rows that exist only in the source (inserts) - **-N** (red) - Rows that exist only in the target (deletes) - **~N** (yellow) - Rows that exist in both but have different values (updates) ### Row States Rows are styled by their state: - **Green text** - Row exists in source but not in target (will be inserted) - **Red text with strikethrough** - Row exists in target but not in source (will be deleted) - **Yellow text** - Cells that differ between source and target (will be updated) ### Filtering Use the **Differences only** checkbox to hide matching rows and focus only on the differences. ![Compare view filtered to show only differences](./compare-differences.png) ## Synchronization Direction The direction arrow in the toolbar shows the sync direction (source → target). Click it to swap the direction, which inverts the meaning of inserts and deletes: - **Source → Target**: Changes will be applied to make the target match the source - **Target → Source**: Changes will be applied to make the source match the target ## Applying Changes ### Generate Script Click **Generate Script** to create a SQL script containing all the INSERT, UPDATE, and DELETE statements needed to synchronize the target with the source. The script opens in a new editor where you can review and modify it before execution. ![Generated SQL synchronization script](./compare-script.png) ### Apply Changes Click **Apply Changes** to execute the synchronization directly. This will execute all necessary INSERT, UPDATE, and DELETE statements > **Warning**: Apply Changes executes real modifications to your database. Always review the changes carefully or use Generate Script first to inspect the SQL. ## Key Matching To match rows between source and target, DBCode needs to know which columns uniquely identify each row. If the table has a primary key defined, it will be used automatically. Otherwise, you'll be prompted to select the key columns that should be used for matching. ## Cross-Server and Cross-Database Comparison One of the most powerful features of Data Compare is the ability to compare tables across completely different servers and database systems. You can compare: - **Same server, different databases** - Compare tables across schemas or databases on the same server - **Different servers, same database type** - Compare production vs. staging PostgreSQL instances - **Different database systems entirely** - Compare a MySQL table against a PostgreSQL table, or SQL Server against Oracle This is invaluable for: - Validating data migrations between systems - Comparing production vs. staging environments - Auditing data across replicas - Verifying ETL processes that move data between platforms The comparison handles data type differences automatically where possible, matching columns by name and converting compatible types for comparison. --- ## Docs > Data > Copy ### Copy table data Discover how to copy table data without using SQL. ## Open a table In the **Connections** view, connect to your database, expand the database and **Tables**, then select a table to open its data grid. ## Copy selected cells Click and drag across the cells you want to copy. ![A range of cells selected in the data grid](./copy-selection.png) Right-click the selection and choose **Copy** to copy the values without headers. To choose a format, open **Copy As** > **Selection**, then select the format. ![Copy As Selection menu with the available formats](./copy-selection-with-options.png) ## Copy all rows To copy the complete result set, right-click inside the grid and open **Copy As** > **All**, then select a format. ![Copy As All menu with the available formats](./copy-selected-rows-with-headers.png) ## Available copy formats **Selection** includes three range-specific choices: - **Without Headers**: Cell values only - **With Headers**: Column names followed by cell values - **As Comma List**: Values in a comma-separated list Both **Selection** and **All** support: - **As CSV**: Comma-separated values - **As HTML**: HTML table markup - **As HTML (Styled)**: HTML table markup with styling - **As JSON**: Compact JSON - **As JSON Pretty**: Formatted JSON - **As Markdown**: A Markdown table - **As SQL In Clause**: Values formatted for an SQL `IN` clause - **As SQL Insert Statements**: SQL `INSERT` statements - **As XML**: XML data --- ## Docs > Data > Edit ### Edit data in the grid How to Edit Table Data without writing SQL. ![Data editor showing a table with inline editing in VS Code](./data-editor.png) ## Opening a Table To select a table, begin by opening a connection from the `DB Explorer` pane. ![Selecting a database connection](./selecting-connection.png) After selecting Connection, select a `Database`. ![Selecting a database](./select-database.png) Now expand `Tables` by double clicking and click on specific table. This will open that specific table in a new tab. ![Selecting a table](./select-table.png) ## Editing Data To edit the data, double click on a cell to open the editor and enter the value you want to set. To enter null in a field, simply enter `(null)` in the cell. A context menu is also available to set common values depending on the data type of the cell, for example to update a value to NULL right click and select `Set Value` > `null` if the column is nullable. ![Selecting a cell to edit](./select-cell.png) ## Saving Changes After making changes, click the **Save** button (Ctrl/Cmd+S) in the toolbar. Modified cells are highlighted until saved. ![Save button in the toolbar](./apply-changes.png) If a primary key is not present on the table, a prompt appears to select `Column with Unique Value` to ensure changes are matched to unique rows in your data. ![Save changes dialog](./save-changes.png) ## Verifying Changes DBCode automatically validates update or delete operations before executing them on the database. This step is crucial to ensure that changes affect only the intended data. During the validation process, each row with an update or deletion is checked to confirm that only one unique row in the table is affected. If validation fails, the changes are not applied, and an error notification is provided. --- ## Docs > Data > Explore ### Explore and analyze Data Explore lets you interactively analyze any query result or table data. It automatically classifies columns as dimensions or measures, profiles the loaded rows, and renders charts as you click fields. Date fields can be bucketed by day, week, month, quarter, or year, and dimension values can be clicked to filter the view. ## Opening Explore There are two ways to open the Explore panel: - **From the data grid**: Click the telescope icon in the grid toolbar on any query result or table data. - **From the DB Explorer**: Right-click a table and select **Explore**. DBCode queries the table and opens the panel with the loaded row set. ![Right-click context menu on a table showing the Explore option](./explore-context-menu.png) ## Layout The Explore panel is organized into several areas: - **Breadcrumb bar**: At the top, shows the current drill path with the table name and active filters. Each segment is clickable for back navigation. The AI assist toggle is also here. - **Filter bar**: Below the breadcrumbs, displays all active filters as removable chips with undo/redo buttons. - **Left sidebar**: Columns grouped into Dimensions, Measures, and Relationships. Click a column to select it. The sidebar width is adjustable by dragging the resize handle. - **Center area**: Starts with profile cards for every column. When a field is selected, it becomes a chart immediately, with the same composer row controlling plot, grouping, time axis, comparisons, and split by. - **Row preview**: A collapsible panel at the bottom of the center area showing filtered rows in a data grid. - **Status bar**: Bottom bar showing dimension, measure, relationship, and filter counts. ![Explore panel layout showing the field sidebar and column overview cards](./explore-layout.png) ## Column Overview When no column is selected, the overview page shows a card grid where each column is represented as a card containing: - Column name with a type icon - A mini sparkline histogram showing the value distribution - Distinct count and null percentage - A quick stat line (min/avg/max for measures, top value for dimensions) The overview also highlights **data quality alerts** (columns with high null rates, constant values, or all-unique values) and shows **correlations between measures** with r-values. Click any card to select that column and see its detail view. ## Column Classification DBCode automatically classifies columns into two categories: - **Dimensions** (categorical): Strings, booleans, dates, enums, and numeric columns detected as categorical via name heuristics (`_id`, `_code`, `_type` suffixes), FK metadata, or low cardinality. - **Measures** (numeric): Integers, floats, decimals, and money types suitable for aggregation. Detected IDs and foreign keys are excluded. ## Filtering ### Dimension Filters Click any value in the frequency list to add it as a filter. Multiple values can be selected. Active filters appear as removable chips in the filter bar at the top. - Null values appear as "(null)" and are filterable like any other value - A search box lets you filter the displayed frequency bars by substring (visual only, does not affect data filters) ![Explore view with a category value filter applied and a filter chip shown above the chart](./explore-filter-bar.png) ### Date Filters Selecting a date dimension buckets its values using the composer's **at** grain control - Day, Week, Month, Quarter, or Year. Changing the grain re-buckets the values and clears any previous date filters. For a custom range, use the **Filter range** block at the bottom of the side panel: it seeds From/To with the column's own min/max and applies a range filter as soon as you edit either date. ![Date dimension with Month granularity selected, showing a monthly chart, by value list, and date range filter](./explore-filter-date.png) ### Measure Filters Select a measure to see a range slider with a histogram backdrop. Drag the handles or edit the min/max inputs directly to filter to a numeric range. ### Filter Bar All active filters are shown as chips in a persistent bar below the breadcrumbs. Each chip is removable. Undo/redo buttons (up to 50 states) let you step back through filter changes. ## Aggregation Select one or more measures and choose an aggregation function for each: | Function | Description | |----------|-------------| | Sum | Total of all values | | Average | Mean value | | Min | Minimum value | | Max | Maximum value | | Count | Number of non-null values | | Distinct | Number of unique values | Measures and grouping live in the plot composer: the **by** control sets the breakdown dimension (or **Overall** for a single aggregate), and the **over** control chooses the X axis - **Values**, or a date column bucketed at the **at** grain. See [Over Time](#over-time). ## Chart Types The chart toolbar offers the following visualization types: | Type | Best For | |------|----------| | Bar | Comparing categories | | Horizontal Bar | Long category labels | | Line | Trends over time | | Area | Cumulative trends | | Pie | Proportions of a whole | | Donut | Proportions with a center label | | Scatter | Relationships between two measures | ![Bar chart showing row count grouped by category with the bar chart button highlighted](./explore-chart-bar.png) ![Line chart showing row count over month with the line chart button highlighted](./explore-chart-line.png) ## Chart Toolbar Options The chart toolbar provides controls for customizing the visualization: - **Chart / Pivot**: Switch between chart view and pivot table view - **Stacked**: Stack series on top of each other (bar, area) - **Combined / Split**: Overlay multiple measures on one chart or render them separately (requires multiple measures) - **Dual Axis**: Use separate Y-axes for different measures (requires combined mode) - **Trend line**: Select from a dropdown: None, Linear regression, MA-3, MA-5, or MA-7 - **Labels**: Show data values on chart elements - **Cumulative**: Transform values into running totals - **Other**: When Top N is active, aggregate remaining values into an "Other" entry ## Chart Color Themes Click the palette icon in the chart toolbar to choose from six color themes: | Theme | Description | |-------|-------------| | Connection | Shades derived from the connection's highlight color (default) | | Editor | Shades derived from the editor's primary accent color | | Vivid | Bold, saturated, high-contrast palette | | Ocean | Blues, teals, and cyans | | Warm | Ambers, reds, and corals | | Neon | Electric, bright colors | The selected theme is remembered across sessions. ![Vivid color theme menu beside the matching color values](./explore-chart-themes.png) ## Split By (Multi-Dimension Grouping) The composer's **split by** control adds a second dimension for sub-grouping. For example, group sales by month and split by region. The second dimension is limited to the top N values to keep charts readable; if it's a date column, it buckets automatically at the same grain as the main axis. **split by** and **vs** are mutually exclusive - a comparison always shows the combined total, so adding a split removes an active comparison and vice versa. When a second dimension is active, you can switch to a **Pivot Table** view that renders a cross-tab grid with row and column totals. ![Grouped bar chart showing revenue by category, split by region with five colored series](./explore-split-by.png) ## Over Time Clicking any field opens a plot straight away, built from one composer row above the chart. The row is always the same six controls, in the same order - a control's value changes, or it greys out with a reason, but it never appears, disappears, or moves: **Plot · by · over · at · vs · split by** - **Plot** - the measures to chart. You start with Count (for a dimension) or a Sum of the field (for a measure); add more with **+ measure** and pick an aggregation for each. - **by** - the primary breakdown. For a dimension this toggles between the clicked dimension and **Overall** (a single series); for a measure it is a dropdown of dimensions to break the measure down by. - **over** - the X axis: **Values**, or any date column in the table. The option list is the same for every field, so a date dimension can be plotted over itself or over a different date column. - **at** - the grain (Day, Week, Month, Quarter, Year). It drives time bucketing when **over** is a date column, and value bucketing when **over** is Values but the selected dimension is itself a date. It greys out with a reason when neither applies. - **vs** - a comparison against the **previous period** or the **same window a year back** (year-over-year is not offered at week grain, since ISO weeks don't align across years). It's available whenever it can act - a single measure, no split by, and a date column somewhere in the table - even while **over** is still on Values; choosing a comparison there switches the axis to time automatically, at the grain DBCode judges best for the loaded data. - **split by** - an optional second dimension. Over time this renders small multiples (one chart per split value, sharing a single time axis and color order); over Values it sub-groups each bar. Mutually exclusive with **vs**. Landing rule: click a string dimension and it lands on its own values (ranked bars); click a date dimension and it lands on its own timeline; click a measure and it lands over the best date column in the table when one exists, falling back to Values otherwise. DBCode prefers date columns named like `created`, `_at`, `timestamp`, or `date`. A categorical breakdown turns each value into its own color-matched series, mirrored in the **By value** list beside the chart (click a value to filter); that same side panel carries the **Filter range** block at its bottom for the date column **at** governs, seeded with that column's own min/max. When several measures are selected, each gets its own chart. Under the plot, an insight strip summarizes the series: in time mode, **Peak** (and when it occurred), **Avg** per grain, **Trend** (first-to-last change), and **Latest**; over Values, the grand **Total** and the leading value's share. Buckets are aggregated entirely from the rows already loaded into the panel - no extra query is sent - so use the row limit when opening Explore to control how much history is charted. ![Explore plot over time showing the composer row, Month grain control, line chart, By value list, and insight strip](./explore-over-time.png) The comparison renders as a dashed grey line - always the combined total for the window, regardless of any breakdown - and the insight strip's **vs previous** row reports the change. The most recent bucket is still filling in, so it renders dimmed and labeled "so far"; trend and comparison math only consider complete buckets, so the in-progress one never skews the numbers. If the chart was built from a row-limited snapshot, a warning appears on the chart noting how many rows it's based on, with a one-click option to re-run at a higher limit. ## Statistics When a measure field is selected, the detail view shows a summary grid with: - Sum, Average, Median, Standard Deviation - Min, Max, p25, p75 - Count, Distinct Count, Null Count, Variance A distribution histogram (~15-20 bins) is also displayed. ![Statistics panel showing summary grid and distribution histogram for a selected measure](./explore-statistics.png) ## Calculated Measures Click the **+** button in the Measures section of the sidebar to create a calculated measure. Enter an expression using column names (e.g., `price * quantity`). Autocomplete suggestions are provided as you type. ![Calculated measure dialog with expression revenue minus cost entered](./explore-calculated.png) ## Row Preview The **Rows** section at the bottom of the center area can be expanded to show the current filtered rows in a data grid. When exploring a table or a query result on a SQL connection, the row preview includes a SQL panel that shows the generated SQL for the current exploration state, with options to open the SQL in the editor or execute it directly. ![Row preview showing filtered data in a grid with columns for id, region, category, product, and revenue](./explore-row-preview.png) ## Open as SQL Every chart you compose has a SQL equivalent. Open the **Rows** panel and choose the **SQL** side panel to see the query - measures, grouping, time grain, filters, and calculated fields compile to the SQL dialect of your connection. Open it in an editor to tweak or run it. When Explore is working from a capped snapshot, the row-limit warning offers to open the full query so you can run it server-side over all rows. ## Chart Interaction Clicking a chart data point toggles a filter for that value, allowing you to drill into a specific category and see how it affects the rest of the exploration. On a time chart, drag across the plot to zoom into that date range - the chart scales to the selection so you can inspect a busy stretch of the timeline up close. Double-click the chart to zoom back out to the full range. ## Sort and Top N - **Sort**: Order values by count (ascending/descending), alphabetically (A-Z, Z-A), or chronologically for date dimensions - **Top N**: Limit the display to the top 5, 10, 20, or 50 values. Remaining values are collapsed into an "Other" entry when the Other toggle is active. ## FK Drill-Down When foreign key relationships are detected (or inferred), they appear in the sidebar under **Relationships**. Click a relationship to drill into the related table, carrying the current filter context. - An **Apply filters to relationships** checkbox controls whether the drill uses only filtered rows or all rows - The breadcrumb bar tracks the full drill path, and each segment is clickable for back-navigation - Column definitions and relationship metadata are preserved at each level ![Explore panel after drilling from orders into order_items, showing breadcrumb navigation path, correlations, and measure overview cards](./explore-drill-down.png) ## AI Insights Click the sparkle icon in the breadcrumb bar to open the AI assist panel. DBCode sends a compact summary of your data (column types, cardinality, top values, null rates, correlations) to your configured AI provider and returns: - **Insights**: Observations about your data - **Suggested actions**: Clickable buttons that apply exploration actions (select fields, add filters, set measures, drill into relationships) No raw data rows are sent to the AI provider. Summary data (column types, value distributions, null rates, some distinct values) is sent. You can view exactly what is sent by clicking the **Summary Data** link in the AI assist panel. ![AI Insights panel showing data observations and suggested exploration actions alongside the column overview](./explore-ai-insights.png) --- ## Docs > Data > Export ### Export data Learn how to export table data or query results. Export complete tables or selected ranges, and share results as an interactive web page when needed. You can export: - Table data: full table contents - Selected ranges: specific rows or cells - Query results: data returned by SQL queries Start exports via right click (context menu), from the Export / Share panel to the right of the results grid, or directly from a SQL query in the editor.
Interactive Web Page export example. Open in a new tab
## Open a Table **Step 1: Connect to a database** Establish a connection in the `DB Explorer` pane. ![Selecting a database connection](./selecting-connection.png) **Step 2: Select a database** Choose the database you want to work with. ![Selecting a database](./selecting-database.png) **Step 3: Open a table** Expand `Tables`, then click the table you want. It opens in a new tab. ![Selecting a table](./select-table.png) ## Export an Entire Table 1. **Open the export menu** Right click the table to open the context menu, then hover over `Export`. ![Export option in context menu](./export.png) 2. **Choose `All`** Select `All`, then choose your preferred format. ![Export all data option](./export-all.png) 3. **Save** Pick a location, name the file, and click **Save**. You can also run `DBCode: Export Data` from the Command Palette and pick the table or view to export. ## Export a Selected Range 1. **Select the range** Highlight the rows/cells you want, then right click and choose `Export`. ![Selecting a data range](./select-range.png) 2. **Choose `Selection`** Select `Selection`, then choose your preferred format. ![Export selection option](./export-selection.png) 3. **Save** Specify a location, set a file name, and click **Save**. Note: You can perform the same steps in the SQL results grid — right click inside the grid to export all rows or just your selection. Note: To create an interactive web page export, choose the Web Page format from the Export menu or the Export / Share panel and configure options as needed. ## Export from Query Run a query and write the results straight to a file, without first loading the data into the results grid. Useful when you want to run and export in one step, or when you prefer not to render the results before exporting. 1. **Open a SQL file** In a connected `.sql` file, place your cursor in a SELECT statement, or select one to export. 2. **Trigger the export** Use any of the following: - Click the Export icon in the editor title bar (next to Execute, Explain, Analyze) - Right click in the editor and choose `Export Query Results` - Run `DBCode: Export Query Results` from the Command Palette 3. **Pick a format and destination** Choose a format (CSV, Excel, JSON, Parquet, etc.), then pick where to save the file. 4. **Run** DBCode executes the query and writes results to the file. Progress shows in a notification, and the query is recorded in your execution history. Note: Export from Query supports a single SELECT statement at a time. Place your cursor inside the statement or highlight it before running the export. ## Supported Export Formats You can export table data in a range of formats, including: - **CSV** (Comma-Separated Values) - **Excel** (XLSX) - **HTML** (Static table markup) - **Web Page** (Interactive HTML; options to include SQL, export date/time, title, and password protection) - **JSON** (JavaScript Object Notation) - **JSON Pretty** (Formatted JSON for readability) - **Markdown** (For documentation purposes) - **Parquet** (Columnar storage format optimized for analytics workflows) - **SQL In Clause** (SQL format for use in `IN` conditions) - **SQL Insert Statements** (SQL script for re-inserting data) - **XML** (Extensible Markup Language) Excel exports include a `Query` worksheet when SQL is available. To omit it, disable `dbcode.export.includeQueryInExcel` in VS Code settings. The setting is enabled by default. These formats are available for both full table exports and selected data ranges, offering flexibility based on your requirements. --- ## Docs > Data > Formatters ### Formatters Transform how your data is displayed with formatters in DBCode. Apply predefined formatters or create custom JavaScript formatters to make your data more readable and meaningful. ## Overview Formatters allow you to customize how data is displayed in the grid without modifying the underlying data. You can: - Apply predefined formatters for common data types - Create custom JavaScript formatters for unique formatting needs - Look up related data inline with the **Data Lookup** formatter - Apply formatters to specific columns, all columns with the same name, or all columns of a base type on a connection - Save and reuse custom formatters across different connections ## Accessing Formatters To format a column: 1. Right-click on any column header in the data grid 2. Select **Format** from the context menu 3. Choose from the dropdown list which includes both predefined and custom formatters 4. To create a new custom formatter, select the option at the bottom of the dropdown 5. For predefined formatters, you can click **Customize this formatter** to create a modified version ## Predefined Formatters DBCode includes several built-in formatters organized by category: ### Binary Category **Binary as UUID** - Converts MySQL binary(16) data to readable UUID format - Perfect for applications storing UUIDs as binary data - Example: `0x1234567890ABCDEF...` → `12345678-90AB-CDEF-...` **Base64 Encoded** - Displays binary data as base64 strings - Useful for viewing encoded binary content **Hex Viewer** - Shows binary data as hexadecimal with byte grouping - Ideal for debugging binary data structures ### Text Category **Hyperlinks** - Auto-detects URLs and email addresses - Converts them to clickable links in the grid - Supports both HTTP/HTTPS URLs and email addresses **JSON Pretty** - Formats JSON strings with proper indentation - Adds syntax highlighting for better readability - Great for JSON columns in your database **Title Case** - Converts text to title case formatting - Capitalizes the first letter of each word ### Numeric Category **Currency** - Formats numbers as currency with locale support - Configurable currency type - Example: `1234.56` → `$1,234.56` **Percentage** - Displays numbers as percentages - Configurable decimal places - Example: `0.1234` → `12.34%` **Scientific Notation** - Formats large or small numbers scientifically - Useful for scientific data - Example: `1230000` → `1.23e+6` **Thousands Separator** - Adds locale-appropriate thousands separators - Example: `1234567` → `1,234,567` ### Boolean Category **Yes/No** - Displays true/false values as Yes/No - More user-friendly than raw boolean values **Icon** - Shows boolean values as icons (✓/✗) - Visual representation of true/false states **On/Off** - Displays boolean values as On/Off switches - Clear indication of state ### Datetime Category **Source Timezone** - Renders naive datetime values (stored without timezone information, such as UTC timestamps in SQLite) in your local time - Select the source timezone that the stored values were written in (defaults to UTC) - Conversion is grid display only - stored data, cell edits, and exports keep the original raw value - Useful for databases that store timestamps as plain datetime strings without an explicit offset ### Reference Category **Data Lookup** - Displays related data from another table alongside the original value - Configure the target table, join column, display columns, and separator - Batched requests and session caching keep lookups responsive ## Data Lookup Formatter ![Data grid showing actor IDs with inline lookup details](./data-lookup.png) The Data Lookup formatter enriches identifier columns (such as foreign keys) with descriptive fields from a related table. ### When to Use It - Display usernames or emails next to user IDs - Show product names beside SKU or inventory IDs - Surface any descriptive columns that help explain a referenced value ### Configuration Options - **Target table**: The table that contains the descriptive data you want to show - **Join column**: The column in the target table that matches the formatted column's values - **Display columns**: One or more columns from the target table to render after the original value - **Separator**: The string used between each display column (default: space) ### How to Configure 1. Open the **Format** menu for the column you want to enrich 2. Select **Data Lookup** from the list of predefined formatters 3. Choose the target table and join column from the available schema metadata 4. Pick the display columns you want to show and adjust the separator if needed 5. Click **Save & Apply** to start displaying the related data inline ### Runtime Behavior - Lookup requests are batched and cached for the current grid session to minimize database round trips - Refreshing the grid clears cached results so you always see up-to-date data - If a lookup fails, the grid falls back to showing the original value with an error indicator ## Custom Formatters Create your own JavaScript formatters for unique formatting requirements. ### Creating a Custom Formatter 1. In the Format window, open the dropdown with all formatter options 2. Select the **Create New Custom Formatter** option at the bottom of the dropdown 3. Enter a name for your formatter 4. Write your JavaScript code in the editor 5. Preview the output with sample data 6. Click **Save & Apply** to create and apply the formatter ### Customizing Predefined Formatters You can also customize existing predefined formatters: 1. Select any predefined formatter from the dropdown 2. Click the **Customize this formatter** link 3. Modify the JavaScript code to suit your needs 4. Give your customized formatter a new name 5. Preview the changes and click **Save & Apply** ### Custom Formatter Code Structure Your custom formatter should follow this pattern: ```javascript function format(value) { // Your formatting logic here // Return the formatted string return formattedValue; } ``` ### Custom Formatter Examples **Phone Number Formatter** ```javascript function format(value) { if (!value) return value; const phone = value.replace(/\D/g, ''); if (phone.length === 10) { return `(${phone.slice(0,3)}) ${phone.slice(3,6)}-${phone.slice(6)}`; } return value; } ``` **Capitalize First Letter** ```javascript function format(value) { if (!value || typeof value !== 'string') return value; return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase(); } ``` **Date Relative Time** ```javascript function format(value) { if (!value) return value; const date = new Date(value); const now = new Date(); const diffMs = now - date; const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); if (diffDays === 0) return 'Today'; if (diffDays === 1) return 'Yesterday'; if (diffDays < 7) return `${diffDays} days ago`; return date.toLocaleDateString(); } ``` ### Managing Custom Formatters **Using Existing Custom Formatters** 1. Your saved custom formatters appear in the main dropdown alongside predefined formatters 2. Select any custom formatter from the dropdown to apply it 3. Preview the output and click **Save & Apply** **Editing Custom Formatters** 1. Select an existing custom formatter from the dropdown 2. Edit the formatter's name and code as needed 3. Preview your changes 4. Click **Save & Apply** to update and apply the changes ## Application Scope When applying a formatter, you can choose: ### Apply to Specific Column - **Apply to just this column in this table**: Formats only the selected column in the current table - Most specific option, useful for table-specific formatting needs ### Apply to All Similar Columns - **Apply to all columns named '[column_name]'**: Formats all columns with the same name across all tables - Useful for consistent formatting of common column names like 'email', 'phone', 'created_at' ### Apply to All Columns of a Base Type - **Apply to all `` columns in ``**: Formats every column of the same base type (for example, all datetime columns) across the entire connection - Useful when you want consistent display for all columns of a given type without naming each one - A per-column formatter always takes precedence over a type-scoped one when both are set ## Formatter Storage ### Global Custom Formatters - Custom formatters are saved globally in VS Code settings - Available across all database connections - Persist between sessions and workspace changes ### Connection-Specific Mappings - Formatter assignments are stored per connection - Each connection remembers which formatters are applied to which columns ## Performance Considerations - Formatters are applied client-side and don't affect database performance - Complex custom formatters may impact rendering performance on large datasets - Original data remains unchanged; only the display is modified - Formatters include error handling with fallback to original values ## Best Practices ### Writing Custom Formatters - Always handle null/undefined values - Keep formatters simple and fast for better performance - Test with various data samples before applying ### Naming Conventions - Use descriptive names for custom formatters - Include the data type or use case in the name - Examples: "Phone Number US", "Currency EUR", "Date Relative" ## Troubleshooting ### Formatter Not Applied - Check that the formatter is compatible with the column's data type - Verify the formatter was saved successfully - Try reloading the data or reopening the table ### Custom Formatter Errors - Check the JavaScript console for error messages - Ensure your formatter handles all possible input values - Test with null, undefined, and unexpected data types ### Slow Performance - Simplify complex formatting logic - Consider using predefined formatters when possible - Limit the use of expensive operations in custom formatters Formatters make your data more readable and meaningful while maintaining the flexibility to customize display formatting to your specific needs. --- ## Docs > Data > Import ### Import data DBCode's Import feature allows you to easily transfer data from various sources into your database tables, streamlining the process of populating tables with data from files or other database objects. ## Overview The Import feature supports importing data from: 1. **Files**: - CSV (Comma Separated Values) - JSON (JavaScript Object Notation) 2. **Database Objects**: - Tables from the same or different database - Views from the same or different database ## Starting the Import Process There are three ways to initiate an import operation: ### Method 1: Table-Specific Import 1. In the Database Explorer, locate the target table 2. Right-click on the table 3. Select **Import Data** 4. The Import dialog opens with your selected table pre-configured as the destination ### Method 2: General Import 1. In the Database Explorer, right-click on the **Tables** group 2. Select **Import Data** 3. The Import dialog opens, requiring you to select a destination table ### Method 3: Command Palette 1. Open the Command Palette and run **DBCode: Import Data** 2. Pick the destination connection and database in the quick pick 3. The Import dialog opens, requiring you to select a destination table ## Import Workflow ### Step 1: Select Source 1. Choose the source type: - **File**: Import from a CSV or JSON file - **Table/View**: Import from another database object 2. If selecting **File**: - Click **Browse** to locate and select your file - Select the file format (CSV or JSON) - Configure any format-specific options: - For CSV: delimiter, quote character, header row settings 3. If selecting **Table/View**: - Choose the source connection (can be the same or different from destination) - Select the database containing the source - Choose the specific table or view to import from ### Step 2: Map Columns The Import interface displays: - Source columns on the left - Destination columns on the right ![Import Column Mapping](./import-mapping.png) Each column mapping shows: - Source column name and data type - Destination column name and data type By default, DBCode attempts to match columns by name and compatible data types. ### Step 3: Preview Data 1. Click the **Preview** button to examine sample data from the source 2. Preview rows appear transposed (horizontally) between the source and destination columns 3. This preview helps confirm: - Data values look correct - Column mappings are appropriate - Data types are compatible ### Step 4: Execute Import 1. Review your mappings 2. Click the **Import** button to begin the process 3. A progress indicator displays the import status ## Duplicate handling and error behavior ### Duplicates Control what happens when a source row conflicts with an existing row in the destination table. | Option | Behavior | |--------|----------| | **Fail on duplicates** | The import stops on the first key conflict. This is the default. | | **Skip duplicates** | Conflicting rows are silently ignored and the import continues. On MySQL, `INSERT IGNORE` is used internally, which may suppress errors beyond key conflicts; test on a sample first. | | **Replace duplicates** | Conflicting rows are overwritten. Requires a primary key on the destination table. | ### On error Control what happens when an individual row fails to insert for reasons other than a key conflict (for example, a type mismatch or a constraint violation). | Option | Behavior | |--------|----------| | **Stop on error** | The import halts at the first bad row. This is the default. | | **Skip bad rows** | Failed rows are skipped and the import continues. A summary of skipped rows is reported at the end. | ## Column Mapping Features ### Automatic Matching DBCode automatically maps columns based on: - Identical column names (case-insensitive) ### Manual Adjustments You can manually adjust mappings by: - Using the dropdown selector to change mappings ## Best Practices ### Preparation - Ensure your destination table exists with appropriate columns - Check that source data types are compatible with destination columns - Consider creating a backup before importing to production tables ## Troubleshooting ### Common Issues | Issue | Possible Solution | |-------|-------------------| | Data type mismatch | Apply appropriate transformations or adjust target column types | | Character encoding problems | Ensure CSV files are properly encoded (UTF-8 recommended) | ### Error Messages - **"Cannot convert value X to type Y"**: Data type incompatibility between source and destination - **"Constraint violation"**: Source data violates a constraint in the destination table - **"File format error"**: Source file doesn't match expected format (CSV delimiters, JSON structure) ## Limitations - Maximum file size for imports is determined by available memory - Complex JSON structures may require flattening before import - Some database-specific data types may have limited support The Import feature provides a flexible way to populate your database tables from various sources, streamlining data migration and entry processes directly within VS Code. --- ## Docs > Data > Inspector ### Row inspector Inspect any row in three ways — as an editable form, a JSON document, or plotted on an interactive map when geography is present. The Inspector also supports multi-row editing for applying changes across multiple selected rows at once. ## View Modes - Form: View a row as labeled fields. Edit values when supported by your connection and permissions, then save changes. - JSON: View or edit the row as JSON. For document databases like MongoDB, edit the full document structure directly. - Map: If the row includes geographic data, visualize it on an interactive map. ## Form View Use the Inspector's Form view to review and edit the current row in a form layout. ![Inspector Form View](./inspector-form-view.png) - Edit supported fields inline; nulls can be set the same way you would in the grid. - Save or discard changes using the standard save/apply controls. - See the Data Editing guide for broader editing details: [Data Editing](/docs/data/edit) ## JSON View Switch to JSON to view the current row as formatted JSON. ![Inspector JSON View](./inspector-json-view.png) - Useful for debugging, copying values, and comparing complex objects. - Preserves types where possible to mirror how the row is returned from the database. ### JSON Editing (Document Databases) For document databases like MongoDB, Firebase, and other NoSQL stores, JSON view becomes fully editable: - Edit the complete document structure directly in the JSON editor - Add new fields, remove fields, or modify nested objects and arrays - Full syntax highlighting and validation as you type - Changes are tracked and can be saved or discarded like form edits ## Map View (Geography) Map view plots geographic values from the current row on an interactive map. ![Inspector Map View](./inspector-map-view.png) - Automatic detection of geography/geometry columns when you open Map view. - If none are detected, pick one or more columns via a quick selection dialog. - Supports common formats such as WKT, GeoJSON, and simple coordinate pairs. - Interactive controls for pan, zoom, and fit-to-bounds; updates as you navigate rows. Notes: - Requires an active internet connection to load map tiles and styles. - The map uses vector tiles and WebGL for smooth rendering with larger data. - Only columns you select (or that are auto-detected) are visualized. ## Multi-Row Editing The Inspector supports editing a field value across multiple rows simultaneously. This is useful for bulk updates like setting a status, category, or timestamp across many records. ![Inspector Multi-Row Editing](./inspector-multi-row.png) ### How to Edit Multiple Rows 1. In the data grid, select multiple rows using Shift+Click or Ctrl/Cmd+Click 2. Open the Inspector panel - it will show the first selected row 3. Edit a field value in the Form view ### Undo Support Multi-row edits are grouped as a single undo operation. When you undo, all rows are reverted together rather than one at a time. ## How To Use 1. Open a table or query results in the data grid. 2. Open the Inspector from the right hand tool panel and navigate to a row of interest. 3. Use the Inspector title bar to toggle Form, JSON, or Map. 4. For Map view, confirm or select the column(s) containing geographic data if prompted. 5. To edit multiple rows, select them in the grid first, then use the Inspector's multi-row editing features. ## Troubleshooting - No map appears: Ensure the selected column contains a valid geographic value (e.g., WKT, GeoJSON, or coordinates). - Nothing detected automatically: Use the prompt to manually select the appropriate column(s). - Data not editable: Check connection roles/permissions or use the grid or SQL to make changes. --- ## Docs > Data > Join ### Join datasets The Join feature in DBCode lets you combine rows from two datasets based on matching column values — similar to a SQL JOIN, but performed entirely in the client without writing any SQL. Join tables, views, or the results of any query, within the same database, across different databases, or even across different servers and connection types. ## Starting a Join There are two ways to start a join: ### From the DB Explorer 1. **Single Selection**: Right-click on a table or view in the DB Explorer and select **Join...**. A picker will appear allowing you to browse and select the second table to join with. 2. **Multi-Selection**: Hold Ctrl (Windows/Linux) or Cmd (macOS) and click to select exactly two tables or views, then right-click and select **Join...**. The first selected item becomes the left side, and the second becomes the right side. #### Row Limit Options When joining from the DB Explorer, you'll be prompted to select a row limit: - **All rows** - Load the entire dataset from each table - **First 1,000 rows** - Quick join on a sample - **First 10,000 rows** - Moderate sample size - **First 100,000 rows** - Larger sample for thorough analysis ### From the Results Panel Join the results of any SQL query directly from the Results Panel: - **Context menu** - Right-click on a result tab and select **Join With...** to enter selection mode, then click the second tab. - **Drag and drop** - Drag one result tab onto another to join them directly. - **Multi-select** - Hold Ctrl (Windows/Linux) or Cmd (macOS) and click exactly two tabs, then right-click and select **Join**. - **Convert** - Right-click on a stacked or union tab and select **Convert to Join** to re-combine using a join instead. ## Configuring the Join Before the join is computed, a configuration modal appears where you set up the join parameters: ### Join Type Select the type of join to perform: - **Inner Join** - Returns only rows where both sides have matching values in the join columns. - **Left Join** - Returns all rows from the left side, plus matching rows from the right. Non-matching right-side values appear as `NULL`. - **Right Join** - Returns all rows from the right side, plus matching rows from the left. Non-matching left-side values appear as `NULL`. - **Full Outer Join** - Returns all rows from both sides. Non-matching values on either side appear as `NULL`. A visual Venn diagram updates as you select different join types to illustrate which rows will be included. ![Join configuration modal showing join type and column mapping](./join-config.png) ### Column Mapping Map one or more column pairs between the left and right datasets. These pairs define the matching condition (equivalent to the `ON` clause in SQL). - DBCode automatically suggests column matches based on matching column names and compatible types. - Add additional column pairs with the **+** button, or remove pairs with the **-** button. - Each pair specifies a left column and a right column that must have equal values for rows to match. ## Understanding the Results The join result opens in a grid (either a dedicated editor tab from the DB Explorer, or a new result tab in the Results Panel). The grid has all the standard features — sorting, filtering, exporting, charting, and more. ![Join results grid showing combined customer and address data](./join-results.png) ### Column Naming Columns are prefixed with their source label to avoid ambiguity: - Join key columns appear once (from the left side) - All other columns are prefixed with the table or query name (e.g., `customers.name`, `orders.total`) - When joining across different connections, the connection name is included in the prefix ### Join Settings Click the join icon in the toolbar to reopen the configuration modal. You can change the join type or column mapping, and the result will be recomputed immediately. The icon appears as a toggled Venn diagram in the toolbar. ## Cross-Server and Cross-Database Joins One of the most powerful aspects of the Join feature is the ability to join data across completely different servers and database systems: - **Same server, different databases** - Join tables across schemas or databases on the same server - **Different servers, same database type** - Join production vs. staging tables - **Different database systems** - Join a MySQL table with a PostgreSQL table, or SQL Server with Oracle This is invaluable for: - Correlating data across microservices that use different databases - Enriching datasets by combining reference data from different systems - Ad-hoc analysis across environments without writing complex ETL --- ## Docs > Data > Keyboard Shortcuts ### Keyboard Shortcuts The results grid supports keyboard shortcuts for common actions when it has focus. ## Shortcuts | Action | Windows/Linux | macOS | |---|---|---| | Jump to column | Ctrl + Shift + O or Ctrl + F12 | Cmd + Shift + O or Cmd + F12 | | Save changes | Ctrl + S | Cmd + S | | Refresh | Ctrl + R | Cmd + R | | Undo | Ctrl + Z | Cmd + Z | | Redo | Ctrl + Y | Shift + Cmd + Z | | Add row | Ctrl + N | Cmd + N | | Duplicate selected cells/rows | Ctrl + Shift + D | Shift + Cmd + D | | Delete selected rows | Ctrl + Backspace | Cmd + Backspace | | Copy | Ctrl + C or Ctrl + Insert | Cmd + C | | Transpose rows and columns | Ctrl + T | Cmd + T | | Focus WHERE filter | Ctrl + Shift + F | Cmd + Shift + F | | Move cell focus | Ctrl + H / J / K / L | Ctrl + H / J / K / L | | Chart selected cells | Ctrl + G | Cmd + G | | Close detail grid | Esc | Esc | ## Jump to column Jump to column opens a small popup listing every column in the grid. Type part of a column name to filter, use the arrow keys to move the highlight, and press Enter to scroll that column into view and focus it. Hidden columns appear dimmed in the list; picking one makes it visible again. Press Esc to close the popup without jumping. --- ## Docs > Data > Relationships ### Relationships Discover How to Access Related Data Across Linked Tables ## Open a Table 1. Begin by selecting a database connection from the DB Explorer. 2. Choose the desired database, then select a table by clicking it. ![Selected database table](./selected-table.png) ## Identify Linked Relationships To understand the relationships between tables, hover over a cell containing a Primary Key or Foreign Key. A small relationship icon will appear beside the cell, indicating that the column is linked to another table. ![Relationship icon](./relationship-icon.png) ## Browsing Foreign Key Relationships Foreign key relationships allow you to navigate data across multiple tables in both directions: - **From Foreign Key to Primary Key**: When you click on the relationship icon next to a foreign key, you can view the related records in the primary key table. For example, clicking on a `CustomerID` in an `Orders` table will show you all orders related to that specific customer in the `Customers` table. - **From Primary Key to Foreign Key**: Conversely, while in the related table (e.g., `Customers`), you can explore how many orders each customer has by following the foreign key back to the `Orders` table. ## View Filtered Related Data To see the linked data: 1. Hover over the relationship icon to view the message displaying the filtering query for the related table. 2. Click the relationship icon to instantly filter and display data from the related table, as shown below. ![Related table data](./related-table.png) This two-way navigation of foreign key relationships enhances your ability to analyze data comprehensively, allowing for deeper insights and better data integrity. ## Inferred Relationships Some databases like MongoDB, DynamoDB, Cassandra, and others don't have native foreign key support. DBCode can automatically detect relationships based on column naming conventions, enabling the same relationship browsing experience. ### How It Works Inferred relationships use pattern matching to detect columns that reference other tables. For example: - A column named `user_id` in an `orders` table likely references the `id` column in a `users` table - A column named `customerId` references `id` in a `customers` table ### Configuring Inferred Relationships You can configure inferred relationship patterns in two ways: #### 1. Connection Settings 1. Open your connection settings (right-click connection → Edit Connection) 2. Navigate to the **Inferred Relationships** section 3. Enable the patterns you want to use: - **Suffix patterns**: Match columns ending with `_id`, `Id`, `_fk`, etc. - **Custom patterns**: Define your own regex patterns for specific naming conventions 4. Set the **Target column** (default: `id`) - the column name to reference in target tables #### 2. Entity Relationship Diagram (ERD) For visual configuration: 1. Open the ERD diagram for your database (right-click tables → Open Diagram) 2. Click the **Inferred Relationships** tool in the toolbar 3. Toggle patterns on/off and see relationships update in real-time 4. Click **Save** to persist your configuration to the connection ### Predefined Patterns DBCode includes several predefined patterns: | Pattern | Description | Example | |---------|-------------|---------| | `column_id` → `column.id` | Underscore suffix | `user_id` → `users.id` | | `columnId` → `column.id` | CamelCase suffix | `userId` → `users.id` | | `column_fk` → `column.id` | Foreign key suffix | `user_fk` → `users.id` | | `fk_column` → `column.id` | Foreign key prefix | `fk_user` → `users.id` | ### Custom Patterns For databases with unique naming conventions, you can create custom regex patterns: - **Column Pattern**: Regex to match the source column name (use capture group for table name) - **Table Pattern**: Template for the target table name (use `$1` for captured group) - **Target Column**: The column to reference in the target table Example: To match `ref_users_key` → `users.pk`: - Column Pattern: `ref_(.+)_key` - Table Pattern: `$1` - Target Column: `pk` ### Explicit Mappings For relationships that don't follow any naming pattern, you can define explicit column-to-column mappings. This is useful when: - Column names don't match any pattern (e.g., `creator` → `users.id`) - You want to override pattern-detected relationships To add an explicit mapping: 1. In Connection Settings or ERD tool panel, find the **Explicit Mappings** section 2. Click **Add Mapping** 3. Enter the source and target in the format `table.column` or `schema.table.column`: - **From**: The source column (e.g., `orders.creator`) - **To**: The target column (e.g., `users.id`) Examples: | From | To | Description | |------|-----|-------------| | `orders.creator` | `users.id` | Non-standard column name | | `logs.entity_ref` | `products._id` | Generic reference column | | `audit.modified_by` | `auth.users.id` | Cross-schema relationship | ### MongoDB Example For MongoDB collections with document references: ```javascript // orders collection { _id: ObjectId("..."), user_id: ObjectId("..."), // References users._id items: [...] } // users collection { _id: ObjectId("..."), name: "John" } ``` Configure an inferred relationship pattern: 1. Enable the `column_id` → `column.id` pattern 2. Set **Target column** to `_id` (MongoDB's default primary key) Now when viewing orders, you'll see the relationship icon on `user_id` cells, allowing you to browse to the related user document. ## Sharing Relationships via Git Inferred relationships are stored on the connection, so you can version-control them by storing the connection in your workspace: 1. Open the connection (right-click the connection and choose **Edit Connection**). 2. Enable **Store in Workspace**. DBCode saves the connection, including its inferred relationship patterns, to `.vscode/settings.json` (or the `.code-workspace` file). 3. Commit that file. Teammates who open the repo get the same relationships in their entity relationship diagram. ## Generating Relationships with an AI Agent If you use an MCP-capable agent (Claude, Copilot Chat, Cursor) with the [DBCode MCP server](/docs/ai/mcp), it can work out the relationships for you and write them back: - `dbcode-get-tables` lets the agent inspect your schema, or it can read your dbt models. - `dbcode-set-inferred-relationships` writes the patterns into the connection. With **Store in Workspace** enabled they land in `.vscode/settings.json` automatically. - `dbcode-get-inferred-relationships` returns the patterns already configured, so the agent can review or extend them. Pass `mode: "merge"` (the default) to add to existing patterns, or `mode: "replace"` to overwrite them. Inferred relationships render with a DBCode Pro subscription. --- ## Docs > Data > Rowlimits ### Row Limit Use **Open with limit** to choose how many rows DBCode should load when opening a table. ## Select a Table In the DBCode Explorer, expand the connection, database, and **Tables** section, then locate the table you want to open. ## Open the Table with a Row Limit Right-click the table and choose **Open with limit...** from the context menu. ![Open with limit option](./open-with-limit.png) ## Specify Row Limit Enter the number of rows to load, then press Enter. The default limit can be adjusted in Settings. ![Enter row limit](./enter-limit.png) The table opens in a new tab using the specified row limit. --- ## Docs > Data > Saved Filters ### Saved Filters Save table filters for quick access to frequently used data views. Whether you're using WHERE clauses or advanced column filters, saved filters let you instantly switch between different filtered views of your data. ## Quick Start 1. **Apply a filter** to your table data - Use the inline WHERE filter, or - Apply column filters using the grid's filter menu ![Apply a filter to table data](./apply-filter.png) 2. **Save the filter** by clicking the save icon in the filters menu ![Save filter button](./save-filter-button.png) 3. **Name your filter** - Give it a descriptive name like "Active Orders" or "Recent Customers" ![Name your filter](./name-filter-dialog.png) 4. **Reapply anytime** - Click the filters menu and select your saved filter to instantly reapply it ![Saved filters menu](./saved-filters-menu.png) ## Filter Types Saved filters work with both filtering methods: **WHERE Clause Filters** - Save complex SQL conditions that would be tedious to type repeatedly. **Column Filters** - Save multi-column filtering and advanced grid configurations including sort order and grouping. ### Date and Timestamp Columns Date and timestamp columns add period options to the column filter menu: - **In year** filters to the year of the date you pick. - **In year & month** filters to that month within its year. Both push down to the database, so they work even on large, paged tables. When every row is loaded, the column's set filter also lists dates as an expandable Year > Month > Day tree, so you can select a whole year, a single month, or a specific day. ## Managing Saved Filters ### View Your Filters Click the filters icon in the table toolbar to see all saved filters for the current table. Each filter shows the filter name with the filter conditions displayed underneath. ### Rename a Filter 1. Click the filters menu 2. Click the edit icon next to the filter name 3. Enter the new name 4. Press Enter to save ### Delete a Filter 1. Click the filters menu 2. Click the delete icon next to the filter 3. Confirm deletion Deleted filters are removed immediately and cannot be recovered. ## How Filters Work ### Filter Application When you apply a saved filter: - **WHERE filters**: Rebuilds the SQL query with the saved WHERE clause - **Column filters**: Applies the saved filter model to the grid - Both filter types respect the current data state and work with other grid features ### Filter Coexistence WHERE filters and column filters can work together: - When a WHERE filter loads all matching rows, you can then apply column filters client-side - This provides powerful multi-layer filtering without additional server queries ### Filter Storage Saved filters are stored in VS Code settings (`dbcode.table.filters`) and sync automatically across devices via Settings Sync. Each filter is uniquely identified and associated with its specific table. ## Use Cases ### Common Scenarios - **Development**: Quickly switch between "Active Users", "Test Data", "Recent Changes" - **Analysis**: Save complex multi-column filters for recurring reports - **Debugging**: Store filters for error conditions, edge cases, or specific record sets - **Data Review**: Maintain filtered views for different review states or data quality checks ## Best Practices **Descriptive Names**: Use clear, specific names that describe what the filter shows (e.g., "Orders Last 30 Days" instead of "Filter 1") **Organize by Purpose**: Create filters that match your workflow - group related filters with prefixes like "DEV:", "PROD:", "QA:" **Regular Cleanup**: Remove outdated filters to keep your list manageable and relevant **Test After Changes**: If table schema changes, verify saved filters still work correctly ## Limitations - Filters are table-specific and don't transfer between different tables - Deleted tables don't automatically clean up associated filters - Column filters depend on column names - renamed columns may break saved filters - Maximum of one WHERE filter and one column filter can be active simultaneously --- ## Docs > Data > Search ### Search data without SQL Search for data across tables and views directly from the connection tree without writing SQL queries. The search feature supports multi-selection and works across all supported database types. ## Quick Start 1. **Select tables or views** in the DB Explorer - Single selection: Right-click any table or view - Multiple selection: Cmd/Ctrl+Click to select multiple items, then right-click 2. **Choose "Search..."** from the context menu ![Actor table context menu with Search highlighted](./search-context.png) 3. **Enter your search term** in the input box ![Search in actor prompt with the search field highlighted](./search-prompt.png) 4. **View results** - Each table or view opens in its own tab with all matching rows ![Search result grid showing two actor rows matching MARY](./search-results.png) You can also run `DBCode: Search...` from the Command Palette and pick the table to search. ## How It Works The search automatically detects your search term type and searches appropriate columns: - **Text columns**: Searches all string columns for values containing your search term - **Numeric columns**: When you enter a number, searches numeric columns for exact matches - **Date columns**: When you enter a valid date, searches date and datetime columns for matching values The search generates SQL queries with OR conditions for relational databases, and uses native search operations for NoSQL databases. ## Multi-Selection Search Select multiple tables and views (even from different connections) to search them all at once. Results open in separate tabs, and each result set can be independently edited and refreshed. --- ## Docs > Data > Share ### Share data securely Learn how to securely share data with **client-side encryption** and passphrase protection. Your data is encrypted on your computer before transmission - we never see your raw data or passphrase. ## How Secure Sharing Works Secure sharing uses **zero-knowledge architecture** where your data is encrypted on your computer before any network transmission. Here's how the process works: ### Encryption & Upload Process ![Encryption and Upload Flow](./encryption-upload-flow.svg) ### Download & Decryption Process ![Download and Decryption Flow](./download-decryption-flow.svg) ## Key Security Features - **Client-Side Only Encryption**: All cryptographic operations happen on your device - **Zero-Knowledge Storage**: We only store data we cannot decrypt - **Unique Random URLs**: Each share gets a randomly generated URL - **End-to-End Security**: Decrypted data only exists on sender's and recipient's computers - **Automatic Deletion**: Encrypted data expires and is permanently deleted - **PBKDF2 Key Derivation**: Industry-standard password-based key derivation with 64,000 iterations --- ## Step-by-Step Instructions ## 1. Access Your Data You can access the share panel from several places: - **Execute a query** - run any SQL query to display results - **Open a table** - browse any database table - **Export a notebook** - share all or part of your notebook analysis Once you have data displayed, you can proceed to share it securely. ## 2. Open the Share Panel Click the share icon on the right. ![Share Panel](./share-panel.png) ## 3. Configure Options ![Share Panel Detail](./share-panel-detail.png) 1. **Format**: Choose the format for your data from options such as CSV, Excel, HTML, Web Page and Markdown. This allows you to customize the data based on the preferences or requirements of your audience. 2. **Storage Region**: Select where your encrypted data is stored - **Americas**, the **European Union**, or **Asia-Pacific**. Choose the European Union region to keep your encrypted data in Cloudflare's EU jurisdiction for data residency and compliance requirements. 3. **Delete After**: Decide when the data should automatically expire and be deleted from storage. This step is crucial for managing data retention and ensuring that sensitive information is not accessible indefinitely. 4. **Passphrase**: **CRITICAL SECURITY FEATURE**: Enter a passphrase or generate one randomly. This passphrase: - **Stays on your computer** - never transmitted to storage - **Encrypts your data locally** before any upload - **Must be shared separately** with recipients (never through our system) 5. **Name**: Give your data file a clear and identifiable name to make it recognizable for both you and the recipients. ## 4. Share Now click Share. **What Happens Next - Client-Side Encryption**: - **Step 1**: Your data is encrypted **on your computer** using your passphrase - **Step 2**: Only the encrypted data is uploaded to a **unique, randomly generated URL** - **Step 3**: We store encrypted data we cannot decrypt in Cloudflare R2 (or your own S3-compatible bucket) - **Result**: Recipients access the encrypted data via the unique URL ![Share Complete](./share-complete.png) A link for the **encrypted** data is provided, along with options to copy, email or visit the link. **Important Security Practice**: **Share the link and passphrase separately** for maximum security: - Send the unique URL via email/message - Share the passphrase through a different channel (phone, separate message, etc.) - This ensures that even if one communication is intercepted, your data remains secure ## 5. Recipient Access When recipients visit the **unique URL** you shared, they download the encrypted data and must enter the passphrase to **decrypt the data on their own computer**. This maintains end-to-end security because: - **Encrypted data travels over the network** (never plain text) - **Decryption happens on the recipient's computer** (not on our servers) - **Only the passphrase holder can decrypt the data** This zero-knowledge approach ensures that sensitive information never exists in an unencrypted state during transmission or storage. --- ## Security Architecture Details ## Zero-Knowledge Security Model Our secure sharing system is built on a **zero-knowledge architecture**: - **Client-Side Only Encryption**: All cryptographic operations happen on your device - **Encrypted Storage**: We only store data we cannot decrypt - **Automatic Deletion**: Encrypted data expires and is permanently deleted - **End-to-End Security**: From your device to the recipient's device This approach guarantees that your sensitive information remains completely private - even our own systems cannot access your decrypted data. ## Technical Encryption Details Here are the technical details of our **client-side encryption** process that ensures zero-knowledge security: ### Client-Side Only Operations ALL cryptographic operations are performed on YOUR computer using the browser's native Web Crypto API. This means: - Encryption happens before any network transmission - Your passphrase is never stored by our system - We receive only encrypted data we cannot decrypt ### Secure Key Derivation A cryptographic key is derived **on your computer** from your passphrase using industry-standard methods: - **Algorithm**: PBKDF2 (Password-Based Key Derivation Function 2) - **Hash Function**: SHA-512 - **Key Length**: 256 bits - **Iterations**: 64,000 - **Cipher**: AES-GCM ### Data Encryption Process - A **random initialization vector (IV)** is generated on your computer for each encryption - Your data is encrypted **locally on your device** using AES-GCM cipher ### Secure Upload & Storage - **Only encrypted data** is transmitted to Cloudflare R2 (never plain text) - **Unique, randomly generated URL** created for each share - We store the encrypted data + random salt + IV (but NOT your passphrase) - **We cannot decrypt your data** - we don't have your passphrase - Data expires automatically and is permanently deleted --- ## Docs > Data > Streaming ### Streaming ## Overview DBCode supports live streaming from databases and message brokers that provide real-time event feeds. When you subscribe to a data source, the data grid switches into streaming mode - incoming events appear as new rows in real time, with a status bar showing the connection state and event count. Streaming is available for: | Database | Mechanism | Subscribe Target | |---|---|---| | **PostgreSQL** | [LISTEN/NOTIFY](https://www.postgresql.org/docs/current/sql-listen.html) | Channels | | **MongoDB** | [Change Streams](https://www.mongodb.com/docs/manual/changeStreams/) | Collections | | **Redis** | [Pub/Sub](https://redis.io/docs/latest/develop/interact/pubsub/) | Channels | | **SurrealDB** | [LIVE SELECT](https://surrealdb.com/docs/surrealql/statements/live) | Tables | | **Firebase** | [onSnapshot](https://firebase.google.com/docs/firestore/query-data/listen) | Collections (Firestore only) | | **RavenDB** | [Changes API](https://ravendb.net/docs/article-page/latest/nodejs/client-api/changes/what-is-changes-api) | Collections | | **Apache Kafka** | Consumer Groups | Topics | | **RabbitMQ** | AMQP Consumers | Queues | ## How to Subscribe Right-click on a supported item in the connection explorer and select **Subscribe** from the context menu. The data grid opens in streaming mode with a broadcast icon indicating an active stream. ![Right-click context menu on a PostgreSQL database showing the Subscribe option](./streaming-subscribe-menu.png) For databases that support it, you can also start a stream from the query editor: - **PostgreSQL**: `LISTEN channel_name;` - **MongoDB**: `db.collectionName.watch()` - **Redis**: `SUBSCRIBE channel_name` - **SurrealDB**: `LIVE SELECT * FROM table_name;` ## Streaming Grid While a stream is active, the data grid displays: - **Status bar**: Shows the stream source, event count, and elapsed time - **Stop button**: Click to end the stream and return the grid to a normal state - **Live rows**: New events appear at the top of the grid as they arrive Each event row includes metadata such as the event type (create, update, delete, message) and a timestamp. ![Streaming grid showing live PostgreSQL LISTEN/NOTIFY events with channel, payload, and timestamp columns](./streaming-grid.png) ## Requirements - **PostgreSQL**: Any PostgreSQL server supports LISTEN/NOTIFY - **MongoDB**: Requires a [replica set](https://www.mongodb.com/docs/manual/replication/) or sharded cluster. Standalone MongoDB servers do not support Change Streams - **Redis**: Any Redis server supports Pub/Sub - **SurrealDB**: Any SurrealDB instance (WebSocket connection required for live queries) - **Firebase**: Firestore databases only (Realtime Database does not support onSnapshot collection listeners) - **RavenDB**: Any RavenDB server (uses the Changes API via WebSocket) - **Apache Kafka**: Any Kafka broker - **RabbitMQ**: Any RabbitMQ broker with the management plugin enabled ## Availability Live Streaming is a **Pro** feature. See [Pricing](/pricing) for details. --- ## Docs > Data > Tab Behavior ### Tab Behavior When you open a table or view from the connections tree, DBCode opens it in a tab. By default it follows VS Code's preview-tab convention: a single click opens the item in a tab that gets reused the next time you open something. Once you interact with the tab (apply a filter, sort, paginate, etc.) the tab is "locked" and won't be reused. If you'd rather every click open a fresh tab, you can change this with a setting. ## The `dbcode.tabPreview` setting Three values: - **`inherit`** (default) - follows your VS Code setting `workbench.editor.enablePreview`. If you've turned VS Code's preview tabs off, DBCode does the same for tables and views. - **`enabled`** - always use preview tabs, even if VS Code's preview is off. - **`disabled`** - never use preview tabs. Every click opens a new tab. Open the VS Code Settings UI and search for "tab preview" to find the setting under `DBCode > General`. ## Auto-locking on interaction When preview is on, DBCode locks the tab the moment you do any of the following, so your customizations stick around when you open the next table: - Type in the WHERE filter input (even before you apply it) - Apply a WHERE filter - Sort by a column - Apply or change a column filter - Paginate to a different page - Resize a column - Reorder columns - Scroll away from the top - Edit a cell Any of these mark the tab as "in use" and the next click in the connections tree opens a fresh tab rather than replacing this one. ## Tip: Force a new tab You can also force a new tab without changing the setting: - **Double-click** the table in the connections tree. (Note: this also expands the tree node.) - Or set `workbench.list.openMode` to `doubleClick` so single-clicks become navigation only and double-clicks open. ## Why this exists DBCode used to always open every table in a new tab, which led to a lot of tabs piling up if you were exploring schemas. The current behavior matches how VS Code handles file tabs: peek at things with single clicks, lock them in when you start working. The auto-lock triggers above ensure your in-progress work is never lost to a casual click on another table. --- ## Docs > Data > Toolbar Pins ### Toolbar Pins Copying results as JSON, or exporting a selection to CSV, normally takes a trip through the right-click menu. Pin the ones you reach for and they become a single click on the results toolbar. ## Pinning an action Click the **+** at the end of the results toolbar. It opens a menu of everything you can pin: the **Copy As**, **Export** and **Open** trees, along with **Share**, **Select All** and the clear-filters and clear-sorts actions. Pick one and it appears on the toolbar immediately, in every open grid. The right-click menu has no pinning of its own; the **+** is the one place it happens. ![Toolbar pin menu showing Copy As options with the add action highlighted](./toolbar-pin-action.png) ## How pins are grouped Pins group by what they do, and each group is a single button. Pin five copy actions and you get one Copy button, not five icons. The button is labelled with the action a click will run, naming both what it does and the format it does it in, so `Copy JSON` copies JSON and `Export CSV` writes a CSV file. Actions that take no format, such as Share, are named on their own. When a group holds more than one pin the button grows a chevron. Opening it lists every pin in that group by its full name, with a tick against the one the button currently runs: ``` Copy JSON ▾ ✓ Copy selection as JSON Copy all rows as JSON Pretty Copy selection as CSV Copy selection as SQL In Clause ────────────── Rename... Unpin ``` ![Grouped Copy toolbar button menu showing two pinned actions](./toolbar-pin-group.png) Choosing an entry runs it and moves it onto the button, so the action you used last is the one a click repeats. A group holding a single pin has no chevron, because there is nothing behind it. ## Renaming, removing and reordering Right-click a button for **Rename...**, **Unpin** and **Reset Toolbar**. These act on the pin the button is currently showing, so to act on a different one in the same group, pick it from the chevron first and it moves onto the button. Drag a button to move it. The other buttons shift as you drag, so the order you are about to get is the order you can see. Reset Toolbar clears every pin at once. ## When pins don't fit On a narrow results panel the WHERE filter gives up width first. Once it can shrink no further, buttons that no longer fit collapse behind a chevron at the end of the zone. Click it to reach them; choosing one runs it directly. ## What can't be pinned Actions that depend on the cell or column you right-clicked, such as filtering by a particular value or clearing a single column's sort, aren't offered. A toolbar button has no clicked cell to act on. The buttons DBCode places on the toolbar itself, such as Refresh and Save, keep their positions and can't be pinned, moved or hidden. ## Where pins are stored Pins are a personal preference, stored in your user `settings.json` under `dbcode.grid.toolbarPins`, so Settings Sync carries them between your own machines: ```json "dbcode.grid.toolbarPins": [ { "id": "copy.all.jsonPretty" }, { "id": "export.selection.csv", "label": "csv" } ] ``` The array order is the order the buttons appear in, and a `label` records a rename. --- ## Docs > Data > Union ### Union datasets The Union feature in DBCode lets you stack rows from two or more datasets into a single result — similar to a SQL UNION ALL, but performed entirely in the client without writing any SQL. Union tables, views, or the results of any query, within the same database, across different databases, or even across different servers and connection types. ## Starting a Union There are two ways to start a union: ### From the DB Explorer 1. **Single Selection**: Right-click on a table or view in the DB Explorer and select **Union...**. A picker will appear allowing you to browse and select additional tables to union with. 2. **Multi-Selection**: Hold Ctrl (Windows/Linux) or Cmd (macOS) and click to select two or more tables or views, then right-click and select **Union...**. #### Row Limit Options When performing a union from the DB Explorer, you'll be prompted to select a row limit: - **All rows** - Load the entire dataset from each table - **First 1,000 rows** - Quick union on a sample - **First 10,000 rows** - Moderate sample size - **First 100,000 rows** - Larger sample for thorough analysis ### From the Results Panel Union the results of any SQL query directly from the Results Panel: - **Context menu** - Right-click on a result tab and select **Union With...** to enter selection mode, then click additional tabs to include. - **Multi-select** - Hold Ctrl (Windows/Linux) or Cmd (macOS) and click two or more tabs, then right-click and select **Union**. - **Convert** - Right-click on a stacked or join tab and select **Convert to Union** to re-combine as a union instead. ## Understanding the Results The union result opens in a grid (either a dedicated editor tab from the DB Explorer, or a new result tab in the Results Panel). The grid has all the standard features — sorting, filtering, exporting, charting, and more. ![Union results grid showing combined data from customers_prod and customers_staging](./union-results.png) ### Column Alignment Columns from each source are aligned by name (case-insensitive). This means: - Columns with the same name across sources are merged into a single column - Columns that exist in one source but not another will contain `NULL` for the rows from the other source - The column order follows the first source, with any additional columns from subsequent sources appended ### Source Identification A **Source** column is automatically added as the first column, showing which table or query each row originated from. This makes it easy to filter, sort, or group by source. When unioning across different connections, the connection name is included in the source label. ## Cross-Server and Cross-Database Unions One of the most powerful aspects of the Union feature is the ability to combine data from completely different servers and database systems: - **Same server, different databases** - Union tables across schemas or databases on the same server - **Different servers, same database type** - Combine data from production and staging - **Different database systems** - Union a MySQL table with a PostgreSQL table, or SQL Server with Oracle This is invaluable for: - Aggregating similar data from multiple environments or regions - Combining reference data scattered across different systems - Building consolidated views across microservices with different databases - Quick ad-hoc reporting across heterogeneous data sources --- ## Docs > Data > Visualize ### Visualize DBCode lets you create charts from any query results or table data. Charts work in both the [SQL Editor](/docs/query/sql-editor) and [Notebooks](/docs/notebooks) - run a query or open a table, then use any of the methods below to visualize the results. ## Chart Creation Methods ### Method 1: Using the Chart Toolbar Button The fastest way to create a chart from your results: 1. **Select Data** - Highlight desired columns or rows by clicking and dragging in the Results Pane 2. **Create Chart** - Click the **Chart** icon in the toolbar (or press `Ctrl+G` / `Cmd+G`) - A chart is created instantly using your last-used chart type (defaults to grouped column) 3. **Change Chart Type** - Click the **dropdown arrow** next to the chart icon to choose from all available chart types (Column, Bar, Pie, Line, Area, Scatter, Polar, Statistical, Hierarchical, Specialized, Funnel, and Combination) - Your selection is remembered for next time 4. **Edit Chart** - Click the ⋮ (three dots) menu in the top-right corner → **Edit** ![Edit Chart](./edit-chart.png) - Configure settings across these tabs: - **Chart**: Change visualization type and style - **Set Up**: Define categories, series, and aggregation methods - **Customize**: Adjust styles, titles, legends, and axis labels ### Method 2: Using Range Selection 1. **Select Data** - Highlight desired columns or rows by clicking and dragging in the Results Pane - Alternatively, use the `Columns` tab to select columns and drag them to `Row Groups` and `Values` fields 2. **Create Chart** - Right-click on selection → **Chart Range** → Select chart type (bar, line, pie, etc.) 3. **Edit Chart** - Click the ⋮ (three dots) menu in the top-right corner → **Edit** → Use tabs to customize ### Method 3: Using Pivot Mode 1. **Enable Pivot Mode** - Toggle the **Pivot Mode** button in the `Columns` tab of results pane 2. **Configure Pivot Layout** | Section | Purpose | Example | |---------|---------|---------| | Row Groups | Group data by categories | Product Category, Region | | Values | Display series with aggregation | SUM(Sales), COUNT(Orders) | | Column Labels | Group series across columns | Year, Quarter | ![Pivot Mode](./pivot-mode.png) 3. **Create Chart** - Right-click in result area → **Pivot Chart** → Select chart type 4. **Edit Chart** - Click ⋮ (three dots) menu → **Edit** → Use tabs to customize ## Charting Multi-Series Data A common scenario is charting data that has a category column (like a platform or region) alongside a date and a metric. For example: ```sql SELECT date_trunc('week', date) AS week, platform, SUM(value) AS metric FROM events GROUP BY 1, 2 ORDER BY 1, 2; ``` This produces "long format" data where each row has a date, a category, and a value: | week | platform | metric | |------|----------|--------| | 2025-12-29 | ABC | 143 | | 2025-12-29 | EFG | 1127 | | 2026-01-05 | ABC | 197 | | 2026-01-05 | EFG | 1512 | To chart this with each category as a separate colored series, you have two options: ### Option 1: Reshape in SQL (Wide Format) Rewrite the query so each category becomes its own column: ```sql SELECT date_trunc('week', date) AS week, SUM(value) FILTER (WHERE platform = 'ABC') AS "ABC", SUM(value) FILTER (WHERE platform = 'EFG') AS "EFG" FROM events GROUP BY 1 ORDER BY 1; ``` Then select all columns and use **Chart Range** or the **Chart** toolbar button. Each numeric column automatically becomes a separate series. ![Chart from wide format data](./chart-wide-format.png) ### Option 2: Use Pivot Mode Keep the original long-format query and use pivot mode to reshape the data visually: 1. Open the **Columns** tab and enable **Pivot Mode** 2. Drag `week` into **Row Groups** 3. Drag `platform` into **Column Labels** 4. Drag `metric` into **Values** (set aggregation to Sum) 5. Right-click the pivot grid and choose **Pivot Chart** to select a chart type ![Chart from pivot mode](./chart-pivot-mode.png) ## Chart Customization Options ### Style and Appearance | Tab | Feature | Available Options | |-----|---------|-------------------| | Chart Style | Visual treatment | Padding, background color | | Titles | Text elements | Chart title, subtitle, axis titles | | Legend | Reference guide | Enable/disable, position (top, bottom, left, right) | | Series | Data appearance | Style, tooltips, opacity, labels, shadows | | Axes | Grid structure | Position, color, grid lines, ticks, labels | ### Supported Chart Types - **Column/Bar Charts**: Compare data across categories (grouped, stacked, 100% stacked) - **Line Charts**: Analyze trends over time (line, stacked, 100% stacked) - **Pie/Donut Charts**: Display proportions of a whole - **Area Charts**: Represent cumulative data trends (area, stacked, 100% stacked) - **X Y (Scatter) Charts**: Highlight relationships between variables (scatter, bubble) - **Polar Charts**: Radar line, radar area, nightingale, radial column, radial bar - **Statistical Charts**: Box plot, histogram, range bar, range area - **Hierarchical Charts**: Treemap and sunburst visualizations - **Specialized Charts**: Heatmap and waterfall - **Funnel Charts**: Funnel, cone funnel, and pyramid - **Combination Charts**: Mix column & line or area & column in a single chart ## Additional Features ### Chart Management - **Expand**: ⋮ menu → **Expand** (enlarges chart for better visibility) - **Shrink**: ⋮ menu → **Shrink** (returns to original size) - **Close**: ⋮ menu → **Close** (removes chart from view) ### Data Filtering 1. Click the **Filters** tab in query output pane 2. Apply filters using operators: - Text: Contains, Equals, Starts with, Ends with - Numbers: Equals, Greater than, Less than, Between - Dates: Before, After, Between - General: Blank, Not blank 3. Charts automatically update to reflect filtered data ### Exporting Charts - Click ⋮ menu → **Download** - Choose filename and location to save as image ## Benefits of DBCode Visualization - **Integrated Analysis**: Complete data workflow within VS Code - **Flexible Visualization**: Multiple chart types for different analysis needs - **Interactive Exploration**: Drill down, filter, and refine visualizations - **Efficient Workflow**: Toggle between table and chart views seamlessly DBCode's chart visualization transforms raw query outputs into actionable insights directly within Visual Studio Code. --- ## Docs > Db Explorer ### index --- title: DB Explorer description: Learn how to create and edit tables, view Entity Relationship Diagrams (ERDs), rename, truncate, and drop tables, and develop stored procedures directly in DB Explorer to efficiently manage and optimize your databases. sidebar: hidden: true order: 7 --- --- ## Docs > Db Explorer > Create Or Edit Tables ### Create or Edit Tables Use the table designer to create tables or change their structure while reviewing the generated SQL before it runs. ## Create a Table 1. In **Connections**, expand the connection, database, and schema where you want to create the table. 2. Right-click **Tables** and select **Create**. ![Create command in the Tables context menu](./tables-context-menu.png) 3. Enter a **Table Name**, then select `+` to add each column. Configure the name and data type for each column. Depending on the data type, you can also set its length or scale. Use **Nullable**, **Identity**, and **Default** to define the column's behavior. **Changes Preview** updates as you edit the table. ![Table designer with columns and generated CREATE TABLE SQL](./create-table.png) 4. To define a primary key, open the **Primary Key** tab, select `+`, and choose the key column. Add more rows for a composite key. ![Primary Key tab with the id column selected](./set-primary-key.png) 5. Review **Changes Preview**, then select **Apply and Close**. Select **Yes** in the confirmation dialog to run the SQL. ## Edit a Table 1. In **Connections**, right-click the table and select **Alter**. 2. Edit existing columns or select `+` to add a column. You can change the data type, length, scale, nullable status, identity behavior, or default value. The example below adds a non-null `created_at` column with a `CURRENT_TIMESTAMP` default. **Changes Preview** shows the generated `ALTER TABLE` statement. ![Table designer adding a created_at column with generated ALTER TABLE SQL](./edit-table.png) 3. Review the SQL, select **Apply and Close**, then select **Yes** to apply the changes. --- ## Docs > Db Explorer > Drop Table ### Drop Table This guide shows how to drop a table from the DBCode Explorer without writing a SQL command. ## Select Database Connection - In the **DBCode Explorer**, connect to the database containing the table you want to drop. - Expand the connection and database that contain the table. ## Locate and Select the Table - Browse the table list and find the table you want to drop. - Right-click the table name and select **Drop** from the context menu. ![Drop table option](./drop-table.png) ## Select Multiple Tables - Hold Ctrl (Windows/Linux) or Cmd (macOS) and click additional tables to select more than one. - Right-click any of the selected tables and choose **Drop** to drop them all in a single operation. ## Choose Cascade - On databases that support it, DBCode asks whether to **Drop** or **Drop Cascade** before showing the confirmation step. - Cascade also removes dependent objects, such as views and foreign key references, so review what will be affected before confirming. ## Confirm the Drop Action - If DBCode asks for confirmation, review the table name carefully before confirming. - To stop the operation, cancel the confirmation prompt. ## Verify Success - After DBCode completes the operation, the DBCode Explorer refreshes to reflect the removed table. --- ## Docs > Db Explorer > Entity Relationship Diagram ### Entity Relationship Diagram View Entity Relationship Diagrams for related tables. ## Select a Database 1. Start by selecting a database connection from the **DB Explorer**. 2. Choose the desired database. ![Selected database](./selected-database.png) ## Access the Entity Relationship Diagram 1. Hover over **Tables** in the database menu. 2. Right-click to open the context menu, then select **Entity Relationship Diagram**. ![Tables context menu](./tables-context-menu.png) 3. A new tab will open, displaying the Entity Relationship Diagram. You can adjust the layout of the diagram by dragging tables to reorganize the view. ![Entity Relationship Diagram](./erd-diagram.png) ## Multiple Schema Support When you open an Entity Relationship Diagram, you can select which schemas to include: 1. Right-click on **Tables** in the DB Explorer. 2. Select **Entity Relationship Diagram** from the context menu. 3. A schema selector will appear in the toolbar if multiple schemas are present in the database, allowing you to choose one or more schemas. 4. Tables from all selected schemas will be displayed together in the diagram. ## Interactive ERD Example Here's an interactive example of what an Entity Relationship Diagram looks like in DBCode. This example was created using DBCode's share feature, which allows you to publish your ERDs as interactive web pages: Open in new window ↗ ## Export and Share Options DBCode provides multiple ways to export and share your Entity Relationship Diagrams, making it easy to document your database design or share it with team members and stakeholders. ### Export as PDF Generate a professional PDF version of your ERD: 1. Once the Entity Relationship Diagram is open, look for the **Export / Share** button in the toolbar. 2. Choose **PDF** format from the export options. 3. **Optional**: Set a password to protect the PDF content for sensitive database schemas. ### Export as PNG Save your ERD as a high-resolution image: 1. Click the **Export / Share** button in the toolbar. 2. Choose **PNG** format from the export options. 3. The diagram will be saved as a high-resolution PNG image, perfect for embedding into documents, presentations, or wikis. ### Share as Web Page Create an interactive HTML version that can be viewed in any browser: 1. Click the **Export / Share** button in the toolbar. 2. Choose **Web Page** format from the export options. 3. **Optional**: Configure sharing permissions and set an expiration date. 4. Get a secure link to share with others or download the HTML file. **Interactive Features:** - **Zoomable Interface**: Viewers can zoom in and out to explore diagram details - **Draggable Tables**: Interactive layout adjustment for better viewing - **Responsive Design**: Optimized for viewing on desktop, tablet, and mobile devices - **Search Functionality**: Find specific tables or relationships quickly ### Secure Share Publish your ERD securely using DBCode's sharing feature: 1. Open your Entity Relationship Diagram in DBCode. 2. Click the **Export / Share** button in the toolbar. 3. Configure sharing permissions, access controls, and expiration settings. 4. Generate a secure link to share with team members or stakeholders. Learn more about secure sharing in our [Data Sharing documentation](/docs/data/share). --- ## Docs > Db Explorer > Execute Sql File ### Execute SQL File DBCode allows you to run SQL script files against a database or supported server connection, making it easy to execute multiple statements, database migrations, or setup scripts without having to copy and paste the content into the SQL editor. ## Overview The Execute SQL File feature provides a convenient way to: - Run database migration scripts - Execute setup or seed scripts - Apply database schema changes - Import data using SQL statements - Run complex multi-statement scripts ## Using Execute SQL File ### Execute Against a Database 1. Open the **Database Explorer** view in the sidebar 2. Connect to and expand your server connection 3. Right-click the target database 4. Select **Execute SQL File** 5. Browse to and select your `.sql` file DBCode executes the file against the selected database. ### Execute From a Connection If **Execute SQL File** appears when you right-click a connection, you can run a bootstrap script without first selecting a database: 1. Open the **Database Explorer** view in the sidebar 2. Right-click the server connection 3. Select **Execute SQL File** 4. Browse to and select your `.sql` file DBCode runs the file through the selected connection. If the saved connection specifies a database, the script starts there. Otherwise, the driver or server determines the initial database for the login; on some systems, no database is selected. **Important:** DBCode never removes a saved database setting or retries against another database. If the saved database does not exist, the connection fails before the script starts. For bootstrap scripts, leave the database unset or configure an existing database from which the script can create the new one. ### View Results After execution begins, the Results panel opens automatically. It shows statement results in order and reports parsing or execution errors. ## Best Practices ### SQL File Structure - Include proper statement terminators (semicolons) between statements - Consider adding comments to document complex operations - For large operations, include transaction boundaries (`BEGIN TRANSACTION`/`COMMIT`) - Use consistent formatting for better readability ### Error Handling - Check the Results panel for any errors after execution - Consider executing critical scripts in transactions for rollback capability - For complex scripts, test on development environments before production ### Performance Considerations - Large SQL files may take time to execute - Monitor the Results panel for progress - Consider breaking very large scripts into smaller, logical files ## Common Use Cases ### Database Migration ```sql -- Example migration script CREATE TABLE customers ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE ); CREATE INDEX idx_customer_email ON customers(email); INSERT INTO customers VALUES (1, 'Acme Corp', 'contact@acme.com'); ``` ### Schema Updates ```sql -- Example schema update script ALTER TABLE products ADD COLUMN last_updated TIMESTAMP; UPDATE products SET last_updated = CURRENT_TIMESTAMP; CREATE INDEX idx_last_updated ON products(last_updated); ``` ### Data Cleanup ```sql -- Example cleanup script DELETE FROM audit_logs WHERE created_at < DATEADD(month, -6, CURRENT_DATE); VACUUM audit_logs; ``` ## Limitations - Very large files may take time to process - The Results panel will show output for all statements, which can be extensive for large scripts - Some database-specific features might have varying behavior ## Alternatives If you prefer an interactive approach for complex scripts, consider: - Using DBCode's SQL Editor for step-by-step execution - Breaking down large scripts into DBCode Notebooks with documentation - Using database-specific command-line tools for certain operations With Execute SQL File, you can quickly run existing SQL scripts directly from your filesystem without having to manually transfer their content to the SQL editor. --- ## Docs > Db Explorer > Filter ### Filter The filter feature gives you precise control over which database objects appear in your explorer view, helping you focus on just the objects that matter for your current work. ![DB Explorer Filter in action](./filter.png) ## How It Works Right-click on any container item in the DB Explorer (databases, schemas, tables, views, etc.) and select **Filter** to control which child items are displayed. This includes the connection itself. Right-click a connection to choose which databases appear beneath it. Filtering databases does not change the connection's default database, so the catalog you connect to stays selected either way. Filters are saved with the connection, so they persist across restarts and travel with the connection when it is synced or shared. Once a filter is applied, the container is labelled "filtered", and you can adjust it by choosing **Filter** again or remove it with **Clear Filter**. ## Filter Methods ### Selection List When you activate the filter, a list of available items will be presented, allowing you to: - Select specific items to display - Quickly include or exclude multiple items at once ### SQL-like Pattern Matching For more advanced filtering, type a SQL-style pattern into the input box instead of picking items. The pattern must begin with `like` or `not like`: | Pattern | Matches | | --- | --- | | `like api%` | Items starting with "api" | | `like %api` | Items ending with "api" | | `like %api%` | Items containing "api" | | `not like %temp%` | Everything except items containing "temp" | A few details worth knowing: - The `like` or `not like` keyword is required. A bare pattern such as `%api%` is treated as ordinary search text, not as a filter. - Matching is case-insensitive, so `like API%` and `like api%` behave the same. - If you leave off the trailing `%`, one is assumed. `like api` is the same as `like api%`. - Quotes are optional. `not like '%temp%'` and `not like %temp%` are equivalent. As you type, the list narrows to preview what the pattern matches. To save the pattern itself, press Enter **without** selecting any items. If you do select items, the filter is saved as that explicit list rather than as the pattern. A filter is either a list of items or a single `like` / `not like` pattern. You cannot combine an include list with an exclude pattern, or apply more than one pattern to the same container. ## Benefits - **Reduced Clutter**: Hide rarely-used objects that get in your way - **Better Focus**: Display only relevant objects for your current task - **Faster Navigation**: Find what you need without scrolling through long lists - **Context-Specific Views**: Create different filtered views for different projects or tasks This feature is particularly useful when working with large databases that contain hundreds of tables, views, or other objects. --- ## Docs > Db Explorer > Keyboard Shortcuts ### Keyboard Shortcuts The DB Explorer tree supports keyboard shortcuts for common actions when it has focus. ## Shortcuts | Action | Windows/Linux | macOS | |---|---|---| | Focus DB Explorer | Ctrl + D, Ctrl + B | Cmd + D, Cmd + B | | Quick Open | Ctrl + Win + O | Ctrl + Cmd + O | | Copy name | Ctrl + C | Cmd + C | | Script DDL | F4 | F4 | Copy name supports multi-select, so you can select multiple items and copy all their names at once. --- ## Docs > Db Explorer > Migrations ### Migrations DBCode detects when a database is managed by a migration tool and adds a **Migrations** container under it in the DB Explorer, comparing the tool's history table against your migration files. It is read-only. DBCode never runs a migration and never writes to your database or your files. Supported tools: **Flyway**, **Prisma**, and **Rails**. ![Flyway migrations in the DB Explorer, including a failed migration, applied and repeatable groups, and the folder binding status.](./migrations-overview.png) ## How Detection Works Detection is automatic and needs no setup. A database with no migration tool shows nothing extra. - `flyway_schema_history` and `_prisma_migrations` are unique to their tool. - `schema_migrations` is shared by several tools. DBCode identifies Rails by the `ar_internal_metadata` table alongside it, or by the table's columns once it reads them. - If the table can't be attributed to a known tool, such as golang-migrate, the container reads **Migrations found, tool unidentified** and lists the recorded versions with no status or commands. If a role can't read the table, the container shows an error. Hover it for the reason. ## What You See in the Explorer The container shows exceptions rather than a full inventory. - The description leads with the tool and a summary: **Flyway: 3 pending, 1 failed**, or just **Flyway** when clean. - Listed individually, failures first: **failed**, **pending**, **modified**, **missing**, **rolled back**. - Grouped into expandable nodes: **Applied (n)** and **Repeatable (n)**. - Rows are labelled with the script name, `V4__add_invoices.sql`. - A failed row shows the reason where the tool records one. Prisma does; Flyway does not. Click a row to open its migration file, already connected to the right database. Rows with no file, such as a `missing` migration, have no click action. The container also appears while disconnected, showing the detected tool. Expanding it connects and loads the detail. ## Binding a Migrations Folder To know what is **pending**, or to catch an **edited** migration, DBCode needs your migration files. Right-click the container and choose **Set Migrations Folder...**. DBCode offers: 1. Locations from your tool configuration: `flyway.toml`, `flyway.conf`, or `schema.prisma`. 2. Each tool's conventional folder, `db/migration` for Flyway, `prisma/migrations` for Prisma, `db/migrate` for Rails. 3. **Browse...** Only folders that exist are offered. If none match, the folder picker opens directly. The binding is stored on the connection, one per database and schema, so a connection can bind a different folder for each schema that runs migrations. Until a folder is bound, the container reads **pending unknown**. ## Flyway Baselines If a Flyway database was baselined onto an existing schema, everything at or below the baseline version sits inside **Applied**, marked as satisfied by the baseline rather than executed here. ## Edit Detection Flyway and Prisma store a checksum for each applied migration. DBCode computes its own from your file and reports any disagreement as **modified**. Hover a modified row to see both values, the one the tool recorded and the one DBCode computed. Rails stores no checksum, so `modified` never occurs for Rails. ## Suggested Commands DBCode generates the command that would resolve a problem. You copy it and run it yourself. Right-click a row for the commands that apply to it: **Copy Migrate Command** on a pending migration, **Copy Repair Command** on a Flyway migration that failed or was edited, **Copy Resolve Command** on a failed Prisma migration. | Status | Flyway | Prisma | Rails | |---|---|---|---| | Pending | `flyway migrate` | `prisma migrate deploy` | `rails db:migrate` | | Failed | `flyway repair` | `prisma migrate resolve --rolled-back ` | Rails records no failures | | Modified | `flyway repair` | not applicable | Rails stores no checksum | The command never contains a password. Flyway's references an environment variable: ``` flyway -url='' -user='' -password="$FLYWAY_PASSWORD" migrate ``` A driver that cannot build a connection string gets no copy action. ## Refreshing Migration state is read fresh every time you expand the container. Detection itself is cached. Right-click the container and choose **Refresh Migrations** to re-read on demand. --- ## Docs > Db Explorer > Quick Open ### Quick Open The Quick Open feature provides fast, keyboard-driven navigation through your database connections, schemas, and objects. Instead of clicking through the DB Explorer tree, you can use Quick Open to jump directly to tables, views, procedures, and other database objects. ## Opening Quick Open Use the keyboard shortcut to open Quick Open: - **Mac**: Ctrl + Cmd + O - **Windows/Linux**: Ctrl + Win + O You can also access it via the Command Palette (Cmd/Ctrl + Shift + P) and search for "DBCode: Quick Open". ## How It Works Quick Open presents a hierarchical picker that lets you navigate through: 1. **Connections** - Your saved database connections 2. **Databases** - Available databases within a connection 3. **Schemas** - Schemas within a database (where applicable) 4. **Containers** - Object types like Tables, Views, Procedures, Functions 5. **Objects** - Individual tables, views, and other database objects ![Quick Open showing object containers](./quick-open-containers.png) ### Navigation - Use the **arrow keys** to move through the list - Press **Enter** to select and drill down into an item - Press **Backspace** or select the back arrow to navigate up the hierarchy - Press **Escape** to close Quick Open ## Smart Starting Context Quick Open intelligently determines where to start based on your recent activity and workspace settings: ### Priority Order 1. **Last Selection**: If you've previously used Quick Open, it remembers your last connection, database, and schema, letting you quickly continue where you left off. 2. **Workspace Default Connection**: If you've set a workspace default connection (via the "Set as Workspace Default" command), Quick Open starts there. 3. **Zero Config Connection**: If DBCode has discovered a connection from your workspace (e.g., from a `.env` file, SQLite database, or other configuration), it uses that as the starting point. 4. **All Connections**: If none of the above apply, Quick Open starts at the root, showing all your connections. This smart context means you can often open Quick Open and immediately start searching for objects without navigating through the connection hierarchy. ## Filtering Objects Once you've navigated to a schema and can see object containers (Tables, Views, etc.), you can start typing to filter the list. The filter works across all containers, recursively searching through: - Tables - Views - Stored Procedures - Functions - And other database objects For example, if you're looking for a table named "users": 1. Open Quick Open 2. Navigate to your connection/database/schema (or let it start there automatically) 3. Once you see the container list (Tables, Views, etc.), start typing "users" 4. Quick Open will flatten the container hierarchy and show all matching objects The filter is applied as you type, showing only objects whose names contain your search text. ![Quick Open filtering objects by name](./quick-open-filter.png) ## Running Commands When you select a database object in Quick Open, it automatically executes the default command for that object type: - **Tables/Views**: Opens the data viewer showing the table contents - **Stored Procedures/Functions**: Opens the routine definition - **Other Objects**: Performs the default action for that object type ## Tips - **Repeated Access**: Quick Open remembers your last selection, so pressing the shortcut again takes you back to the same location. - **Combine with Zero Config**: Set up a `.env` file in your project with your database connection, and Quick Open will automatically start at that connection. - **Workspace Default**: For projects where you always work with a specific connection, set it as the workspace default for instant access. ## Related Features - [Zero Config](/docs/connections/zero-config) - Automatic connection discovery from `.env` files - [Filter](/docs/db-explorer/filter) - Filter objects in the DB Explorer tree view --- ## Docs > Db Explorer > Rename Table ### Rename Tables You can rename database tables from the DBCode Explorer without writing a SQL command. ## Select Database Connection - In the **DBCode Explorer**, choose the connection where the table is located. - Expand the connection and database that contain the table. ## Choose the Table to Rename - In the database tables list, locate the table you want to rename. - Right-click the table name and select **Rename**. ![Rename table option](./rename-table.png) ## Enter the New Table Name - In the input box, replace the current table name with the new table name. - Press `Enter` to confirm the rename, or press `Escape` to cancel. ![Rename table dialog](./renaming.png) ## Verify Success - After DBCode completes the operation, the DBCode Explorer refreshes to show the new table name. --- ## Docs > Db Explorer > Stored Procedures ### Stored Procedures Stored procedures are a vital tool for encapsulating reusable SQL logic. DBCode enhances your workflow with features like intuitive editors, conflict detection, and version comparison to ensure consistency and efficiency when managing stored procedures. ## Creating a Stored Procedure 1. **Launch DBCode** - Open Visual Studio Code and navigate to the DBCode workspace. 2. **Define the Procedure** - Create a new `.sql` or DBCode notebook file, then write the SQL code for your stored procedure. 3. **Execute the Script** - Save the file and execute it by clicking **Execute** or pressing Ctrl+Enter. - A success message will appear in the **DBCode** terminal, confirming that the stored procedure has been successfully created. ![Creating a stored procedure](./create-procedure.png) ## Executing a Stored Procedure 1. **Invoke the Procedure** - Open a SQL editor and execute the stored procedure using commands like `EXEC` or `CALL`. 2. **View Results** - The output will be displayed in the **Results Pane**. ![Executing a stored procedure](./execute-procedure.png) ## Modifying a Stored Procedure 1. **Locate and Open the Procedure** - Navigate to the **DB Explorer** and double-click the stored procedure to open it in the editor. 2. **Edit the Code** - Make the necessary updates in the editor. 3. **Apply Changes** - Click **Apply to Database** at the top of the editor to save changes. ![Apply changes to database](./apply-to-database.png) 4. **Confirm Changes** - A prompt will appear, asking if you want to proceed. Click **Yes** to confirm. - A success message will display in the **DBCode** terminal, confirming the update. ![Confirm changes prompt](./confirm-prompt.png) ## Conflict Detection and Version Comparison DBCode helps ensure database consistency by detecting conflicts and offering comparison tools when discrepancies arise. ### Conflict Detection - If the stored procedure in the database has been modified since it was opened in the editor, DBCode will detect the change when you try to apply updates. - A conflict prompt will appear with the following options: - **Yes:** Overwrite the database version with the editor version. - **No:** Cancel the operation. - **Compare database versions:** View differences between the database's original and updated versions. - **Compare updated database with file:** Compare the updated database version with the version in your editor. ![Conflict detection dialog](./conflict-detection.png) ### Compare Changes - **Compare database versions:** View a side-by-side comparison of the original and updated database versions, with highlighted differences. ![Comparing database versions](./compare-database-versions.png) - **Compare updated database with file:** View a comparison of the updated database version and your local file, showing all changes. ![Comparing file with database](./compare-file.png) ## **Why Use Stored Procedures in DBCode?** - **Reusability:** Simplifies recurring tasks by encapsulating SQL logic in reusable procedures. - **Efficiency:** Precompiled procedures enhance database performance. - **Conflict Detection:** Prevents overwriting newer database versions with outdated scripts. - **Integrated Workflow:** Combines creation, execution, modification, and debugging into a single interface within Visual Studio Code. DBCode ensures seamless and error-free management of stored procedures, empowering you to maintain database consistency and optimize SQL workflows effortlessly. --- ## Docs > Db Explorer > Truncate Table ### Truncate Table Truncating a table removes all rows while keeping the table structure and definitions. In many databases, truncation cannot be rolled back. ## Select Database Connection - Open **DBCode Explorer** and choose the database connection that contains the table. - Expand the connection and database that contain the table. ## Locate and Select the Table - In the database tables list, find the table you need to truncate. - Right-click the table name and choose **Truncate** from the context menu. ![Truncate table option](./truncate-table.png) ## Confirm Truncation - If DBCode asks for confirmation, review the table name carefully before confirming. - To stop the operation, cancel the confirmation prompt. ## Verify Success - After DBCode completes the operation, the table remains in the DBCode Explorer but its rows have been removed. --- ## Docs > Get Started > Connect ### Connect to your first database Create a new connection, connect to a cloud provider, or use the sample database included with the extension. ## Create a New Connection 1. Open Visual Studio Code and click on the DBCode icon in the activity bar (usually on the left-hand side). 2. Click the "Add Connection" Button, or the + icon in the explorer. Or open the command palette Ctrl/Cmd+Shift+P and select the "DBCode: Add Connection" option. ![New Connection Dialog](./new-connection.png) 3. Select the database type you want to connect to, then enter the server details: - Server Name: A name for the connection (e.g., My Database). - Host: Enter the server's host address (e.g., localhost or the IP address of your server). - Port: Input the server's port number, usually 3306 for MySQL, 5432 for PostgreSQL, or 1433 for SQL Server. - Username: The username for the database server. - Password: The password for the database server. - Database: The name of the database you want to connect to. ![Connection Form](./new-connection-form.png) 4. Save the Connection: - After entering all the required details, click the "Save" button to establish the connection. 5. The new connection will be saved, and you can start exploring the data and features of DBCode. ## Connect a Cloud Provider Using a cloud provider grants access to all databases within that provider without needing to configure each one individually. For more information, check out the [connect a cloud provider](/docs/cloud-providers) article. ## Use the Sample Database To use the sample database included with the extension, follow these steps: 1. Open Visual Studio Code and click on the DBCode icon in the activity bar (usually on the left-hand side). 2. Click the "Explore With a Sample Database" button from the explorer. Or open the command palette Ctrl/Cmd+Shift+P and select the "DBCode: Explore With a Sample Database" option. 3. Select the "Sample Database" option. ![Sample Database Selection](./sample-database.png) 4. The sample database will be loaded, and you can start exploring the data and features of DBCode. --- ## Docs > Get Started > Execute A Query ### Execute a Query First, let's create our database table. ## Open a New SQL File To begin, open a new SQL file on the database by clicking the new file icon in the DBCode explorer. ![Opening a new SQL file](./open-query.png) ## Execute a statement To keep it simple, we will create a "departments" table first, as the "employee" table depends on it. Copy and paste the following code into the new SQL file: ```sql -- Create the departments table CREATE TABLE departments ( id SERIAL PRIMARY KEY, department_name VARCHAR(100) NOT NULL ); ``` To run the SQL, you can execute via these options: - Click the execute in the code lens at the top of the editor - Click the execute icon in the top right - Use the keyboard shortcut Ctrl/Cmd+D+E - Right-click and select the "Execute with DBCode" option ![Execute SQL query](./execute.png) ## Inserting Data We will insert some sample data into the newly created table. Paste the following code into the SQL File, this time, select the code to execute only this code rather than the whole file. ```sql -- Insert data into the departments table INSERT INTO departments (department_name) VALUES ('Engineering'), ('Human Resources'), ('Marketing'); ``` Run the code using one of the above-mentioned execution methods. ## Viewing the Data To verify that the data was inserted successfully, select the table from the DBCode explorer, which will open a new tab showing the records in the table. Locate the table in the explorer and click on it to open. ![View table data](./view-data.png) ## Executing Multiple Statements Let's now execute multiple statements at once. These statements will create an "employees" table, insert some data, and perform a select query to join the employees to their departments. Copy and paste the following code into a new SQL file, or replace the existing code in the current file: ```sql -- Create the employees' table CREATE TABLE employees ( Id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, position VARCHAR(50) NOT NULL, salary NUMERIC(10, 2) NOT NULL, hire_date DATE NOT NULL, department_id INT, FOREIGN KEY (department_id) REFERENCES departments(id) ); -- Insert data into the employees table INSERT INTO employees (name, position, salary, hire_date, department_id) VALUES ('Xander Hayes', 'Network Engineer', 78000.00, '2018-10-27', 1), ('Yara Davis', 'Product Owner', 90000.00, '2019-01-07', 2), ('Zoe Carter', 'Digital Marketer', 68000.00, '2020-05-09', 3), ('Aaron Brooks', 'Software Architect', 95000.00, '2017-11-17', 1), ('Bella Simmons', 'HR Assistant', 61000.00, '2018-03-01', 2), ('Cody Fisher', 'Content Strategist', 64000.00, '2020-08-14', 3), ('Diana Russell', 'Scrum Master', 85000.00, '2019-11-06', 2), ('Ethan Coleman', 'Database Administrator', 82000.00, '2018-04-20', 1), ('Fiona Miller', 'Marketing Coordinator', 67000.00, '2019-09-29', 3), ('George Bailey', 'Technical Support Engineer', 62000.00, '2020-12-01', 1), ('Hannah Reed', 'UI Designer', 73000.00, '2018-05-23', 3), ('Ivan Kelly', 'Data Engineer', 87000.00, '2019-01-30', 1), ('Julia Howard', 'Communications Specialist', 63000.00, '2020-10-16', 3), ('Kevin Perez', 'Security Analyst', 79000.00, '2017-06-11', 1), ('Laura Hughes', 'Recruiting Coordinator', 61000.00, '2019-05-24', 2), ('Mike Patterson', 'Operations Analyst', 78000.00, '2018-08-20', 2), ('Nina Rogers', 'Sales Associate', 66000.00, '2020-07-12', 3), ('Oscar Turner', 'Financial Analyst', 81000.00, '2019-04-17', 2), ('Penelope Foster', 'Public Relations Specialist', 69000.00, '2018-09-21', 3), ('Quincy Morales', 'Web Developer', 72000.00, '2017-02-15', 1); -- Select some data SELECT e.name, e.position, e.salary, e.hire_date, d.department_name FROM employees e JOIN departments d ON e.department_id = d.id WHERE e.salary > 70000 ORDER BY e.hire_date; ``` Now, execute the code. If you don't highlight any content first, you will be prompted to execute the whole document. Select "Yes." The results should now be displayed in the DBCode panel at the bottom. ![Query results](./results.png) ## Conclusion Congratulations, you have successfully created tables, inserted data, and retrieved it. --- ## Docs > Get Started > Install ### Install Quickly install DBCode in Visual Studio Code for enhanced database management. ## Requirements ### Visual Studio Code Follow these [instructions](/docs/get-started/install-vscode) if you don't have VS Code installed. ### A Database If you don't have an existing supported database, you can host your own or explore using the sample database included with the extension. ## Install DBCode 1. Open Visual Studio Code and click on the extension icon on the left-hand side. ![Extension icon in Visual Studio Code](./extension-screenshot.png) 2. Search for "DBCode" 3. Complete the installation by clicking on "Install". ![Install DBCode Extension](./dbcode-install.png) ## Accessing DBCode Now that the extension is installed, you can access it via the DBCode logo in the activity bar (usually on the left hand side). ![Access DBCode Extension](./dbcode-active.png) --- ## Docs > Get Started > Install Vscode ### Install Visual Studio Code Install Visual Studio Code and set up your coding environment in just a few steps. 1. **Download Visual Studio Code:** - Go to the [Visual Studio Code](https://code.visualstudio.com/) website. - Download the version compatible with your operating system (Windows, macOS, or Linux). 2. **Install Visual Studio Code:** - Follow the installation instructions provided on the website. - After installation, launch Visual Studio Code and complete any initial setup prompts. 3. **Install DBCode:** - Follow these [instructions](/docs/get-started/install) to install DBCode. --- ## Docs > Help Support > Debug ### Debug & Troubleshoot Follow these steps to enable debug logging: 1. **Open the Output panel:** - Open **View > Output**, or press Shift+Cmd+U on macOS and Ctrl+Shift+U on Windows and Linux. ![Opening the output panel](./open-output-panel.png) 2. **Select the DBCode output channel:** - Use the output channel picker and select **DBCode**. ![Selecting DBCode output](./select-dbcode.png) 3. **Set the log level:** - Click **Set Log Level** in the Output panel toolbar and select **Debug**. ![Setting debug log level](./set-debug-loglevel.png) > **Note:** Debug mode will automatically stop after **30 minutes** of inactivity to prevent excessive logging. ### Viewing Debug Output - Once enabled, detailed debug output will appear in the output panel. ![Debug output example](./debug-output.png) ### Disabling Debugging Output To turn off debug logging, open the **DBCode** output channel, click **Set Log Level**, and select **Info**. --- ## Docs > Help Support > Faq ### Frequently Asked Questions ## Connection Issues ### I can't connect to my database. What should I do? First, verify your connection credentials are correct. Common issues include: - Incorrect host, port, username, or password - Database not accepting remote connections - Firewall blocking the connection - SSL/TLS configuration issues Try [enabling debug mode](/docs/help-support/debug) to see detailed connection logs. ### Do I need to whitelist any IPs? No. DBCode runs entirely within VS Code on your local machine. All database connections are made directly from your computer to your database. ## Extension Behavior ### The DBCode icon isn't showing up in VS Code Make sure the extension is installed and enabled: 1. Open Extensions view (Cmd+Shift+X or Ctrl+Shift+X) 2. Search for "DBCode" 3. Verify it's installed and not disabled 4. Try reloading VS Code ## Security & Privacy ### Is my database data secure? Yes. DBCode: - Runs entirely locally in VS Code - Never sends your database credentials or data to external servers - Stores connection details encrypted in VS Code's secure storage - See our [Security documentation](/docs/security) for details ### Does DBCode collect any data? DBCode collects anonymous telemetry data only if you have VS Code telemetry enabled. This helps improve the extension. No query contents or database credentials are ever collected. See [Telemetry](/docs/telemetry) for details. ## Licensing & Pricing ### What's included in the free version? The free tier covers browsing, querying, and editing data, plus transaction control, read-only connections and roles, missing WHERE detection, unlimited history, and the MCP server. These features are free permanently. Pro adds AI assistance, data tooling, sync and sharing, cloud integrations, and more. ### Can I try Pro features before purchasing? Yes! Pro features are available during your trial period. Contact [help@dbcode.io](mailto:help@dbcode.io) if you have questions about your trial status. ## Getting Help ### I found a bug. How do I report it? Please report bugs on our [GitHub Issues](https://github.com/dbcodeio/public/issues) page. Include: - Your VS Code version - DBCode version - Database type and version - Steps to reproduce - Debug logs if applicable ### Where can I request features? Feature requests are welcome on [GitHub Issues](https://github.com/dbcodeio/public/issues). Use the "Feature Request" label. ### How do I get help with something not covered here? Check out our [Getting Help](/docs/help-support/getting-help) page for all the ways to reach us. --- ## Docs > Help Support > Getting Help ### Getting Help Need help with DBCode? Here are all the ways to get support: ## Quick Links - **Documentation**: You're here! Browse the [Docs](/docs) for guides and references - **GitHub Issues**: [github.com/dbcodeio/public/issues](https://github.com/dbcodeio/public/issues) - **Discord Community**: [discord.gg/FvAzEAHb9w](https://discord.gg/FvAzEAHb9w) - **Email**: [help@dbcode.io](mailto:help@dbcode.io) ## Before You Ask 1. **Check the FAQ** - Many common questions are answered in our [FAQ](/docs/help-support/faq) 2. **Enable Debug Logs** - [Debug mode](/docs/help-support/debug) provides detailed error information 3. **Search Existing Issues** - Your question might already be answered on [GitHub](https://github.com/dbcodeio/public/issues) ## Report a Bug Found a bug? Please report it on [GitHub Issues](https://github.com/dbcodeio/public/issues). **What to include:** - Clear description of the issue - Steps to reproduce - Expected vs. actual behavior - Your environment (VS Code version, DBCode version, OS, database type) - Debug logs if applicable (see [Debug Guide](/docs/help-support/debug)) - Screenshots or error messages ## Request a Feature Have an idea to make DBCode better? Submit a feature request on [GitHub Issues](https://github.com/dbcodeio/public/issues). **Tips for good feature requests:** - Describe the problem you're trying to solve - Explain your proposed solution - Share your use case - Include examples or mockups if helpful ## Join the Community ### Discord Join our [Discord server](https://discord.gg/FvAzEAHb9w) to: - Ask questions and get help from the community - Share tips and tricks - Discuss feature ideas - Connect with other DBCode users --- ## Docs > Help Support > Panel Not Loading ### Panel Not Loading ## What You'll See DBCode panels stay blank, and you may see a notification like: > Could not register service worker: InvalidStateError: Failed to register a ServiceWorker: The document is in an invalid state. This comes from VS Code's webview host, not from DBCode. VS Code renders every panel, including DBCode's, inside a Chromium webview backed by a service worker. When that webview host fails to register the service worker, no panel in the window can render. DBCode surfaces the failure with a notification because its own panel never loads, but the underlying problem is in VS Code itself: [microsoft/vscode#125993](https://github.com/microsoft/vscode/issues/125993). ## Confirm It Is Not DBCode Before changing anything, confirm the webview host itself is broken, not just DBCode: 1. Open any markdown file in VS Code. 2. Press Ctrl+Shift+V (Cmd+Shift+V on macOS) to open the built-in markdown preview. If the markdown preview is blank or fails the same way, the webview host is broken for the entire window, not just for DBCode. Every extension that uses a webview (including DBCode) is affected until this is fixed. ## Restart Properly Start with **Reload Window**, either from the button on DBCode's notification or by running **Developer: Reload Window** from the command palette. It clears the problem often enough to be worth the two seconds it costs. If the panel is still blank after that, quit VS Code completely, all windows, not just the one that's failing. On macOS this means Cmd+Q, not closing the window. On Windows and Linux, close every VS Code window and confirm no `Code.exe` or `code` process is still running. A full quit is more reliable than a reload, because a reload restarts the extension host without necessarily clearing the underlying Chromium service worker registration. ## Clear The Webview Cache If a full restart doesn't fix it, the cached service worker state itself may be corrupt. With VS Code fully closed, delete these four directories. VS Code rebuilds them automatically on next start: - **Windows**, under `%APPDATA%\Code\`: `Service Worker`, `Cache`, `Code Cache`, `GPUCache` - **macOS**, under `~/Library/Application Support/Code/`: `Service Worker`, `Cache`, `Code Cache`, `GPUCache` - **Linux**, under `~/.config/Code/`: `Service Worker`, `Cache`, `Code Cache`, `GPUCache` Then start VS Code again and reopen DBCode. ## If It Keeps Coming Back If the problem returns after a clean restart and cache clear, look at what's interfering with Chromium's service worker storage in your VS Code profile directory: - **Profile directory redirected or synced** - OneDrive Known Folder Move, a corporate roaming profile, or any tool that syncs `%APPDATA%\Code\` (Windows) or the equivalent profile directory can corrupt or lock service worker storage mid-write. - **Low disk space** - service worker registration can fail silently if the volume holding your VS Code profile is nearly full. - **Antivirus or DLP software** - security software that scans or intercepts file writes in the profile directory can block the service worker files from being written correctly. Excluding the VS Code profile directory from sync and from antivirus/DLP scanning, or freeing up disk space, resolves this in most of these cases. ## Upstream This is tracked upstream as [microsoft/vscode#125993](https://github.com/microsoft/vscode/issues/125993). There's nothing DBCode can do to fix it directly since it happens before DBCode's panel ever gets a chance to load. --- ## Docs > Notebooks ### Notebooks DBCode Notebooks provide an interactive environment for data analysis, combining code execution, visualization, and documentation in a single interface. This powerful feature allows you to create reproducible analysis workflows, share insights, and collaborate effectively. ## What are DBCode Notebooks? DBCode Notebooks are interactive documents that contain code cells, markdown cells, and outputs. They're perfect for: - **Data Exploration**: Run SQL queries and analyze results interactively - **Documentation**: Combine code with explanatory text and visualizations - **Collaboration**: Share notebooks with team members for review and collaboration - **Reproducible Analysis**: Create step-by-step analysis workflows that can be re-run ## Key Features - **Multi-language Support**: Execute SQL queries and Python code in the same notebook - **Python Integration**: Inject SQL results directly into Python as pandas DataFrames - **Rich Output**: Display query results, charts, and visualizations inline - **Export Options**: Save and share notebooks in various formats - **Version Control**: Track changes and collaborate using Git ## Getting Started New to DBCode Notebooks? Start with our [Getting Started Guide](/docs/notebooks/getting-started) to learn the basics of creating and using notebooks. ## Notebook Management Learn how to manage your notebooks effectively: - [Python Integration](/docs/notebooks/python) - Use Python alongside SQL for advanced data analysis - [Exporting](/docs/notebooks/exporting) - Export and share notebooks in multiple formats - [Cell Locking](/docs/notebooks/cell-locking) - Lock individual cells to specific database connections --- ## Docs > Notebooks > Cell Locking ### Cell Locking Cell locking allows you to bind individual cells in a notebook to specific database connections, databases, and optionally schemas. This enables you to work with multiple data sources within a single notebook while maintaining consistency for specific analyses. ## What is Cell Locking? Cell locking ties individual notebook cells to specific database connections, providing: - **Multi-Source Analysis**: Query different databases within the same notebook - **Connection Consistency**: Lock critical cells to prevent accidental connection changes - **Schema Specificity**: Optionally lock cells to specific schemas within a database - **Flexible Workflows**: Change the notebook's default connection while keeping certain cells locked ## When to Use Cell Locking ### Cross-Database Analysis - Compare data across development, staging, and production environments - Query different database systems (PostgreSQL, MySQL, etc.) in the same notebook - Analyze historical data stored in separate archives ### Mixed Environment Workflows - Lock reporting cells to production while keeping exploratory cells flexible - Maintain reference data queries locked to specific connections - Ensure compliance queries always run against the correct database ### Schema-Specific Operations - Lock cells to specific schemas for multi-tenant applications - Maintain separation between different application modules - Work with multiple schemas within the same database connection ## How to Lock a Cell Locking and unlocking cells is simple and intuitive: 1. **To Lock**: Click the open lock icon in the cell status bar. 2. **To Unlock**: Click the closed lock icon. ![A SQLite notebook cell locked to its connection above an unlocked MariaDB cell](./cell-locking.png) When you lock a cell: - The cell locks to the currently selected connection, database, and schema - The lock icon changes to a closed lock to indicate the cell is locked - The cell will always use this specific connection for execution When you unlock a cell: - The lock icon changes to an open lock - The cell will use the notebook's default connection ## Managing Locked Cells ### Viewing Lock Status Check if a cell is locked: - **Locked**: Closed lock icon in the cell status bar - **Unlocked**: Open lock icon in the cell status bar --- ## Docs > Notebooks > Exporting ### Exporting DBCode Notebooks can be exported and shared in multiple formats, making it easy to collaborate with team members or present your analysis to stakeholders. ## Enhanced Export Editor Before exporting, you can enhance your notebook content using DBCode's built-in WYSIWYG editor. This powerful editor allows you to: - **Add Rich Text**: Include additional explanations, context, and formatting - **Insert Images**: Add charts, diagrams, or visual assets to support your analysis - **Create Links**: Link to external resources or internal sections - **Customize Layout**: Drag and drop to reorder content for better flow - **Apply Themes**: Choose from professional themes to match your organization's branding - **Manage Cell Visibility**: Remove cells you don't want to include (like SQL queries) from the final export while keeping the results ![Export editor interface showing WYSIWYG editing capabilities](./editing.png) The editor includes all cells from your original notebook, allowing you to selectively include or exclude content. For example, you might remove the SQL queries that produced a report while keeping the results and analysis for stakeholder presentations. ## Example Exported Notebook Here's an example of what an exported notebook looks like when shared as a web page: ## Export Options ### Export as PDF Generate a professional PDF version of your notebook: 1. Open your notebook in DBCode 2. Click **Export / Share** button in the toolbar 3. Choose **PDF** format from the export side panel 4. **Optional**: Set a password to protect the PDF content ### Export as Web Page Create an interactive HTML version that can be viewed in any browser: 1. Open your notebook in DBCode 2. Click **Export / Share** button in the toolbar 3. Choose **Web Page** format from the export side panel 4. **Optional**: Set a password to protect the content **Interactive Features:** - **Data Tables**: Viewers can filter, sort, and search through result sets - **Charts**: Interactive visualizations that respond to data filtering - **Responsive Design**: Optimized for viewing on desktop, tablet, and mobile devices - **Navigation**: Easy navigation between sections and cells ### Export as Markdown Export your notebook's cell content as a Markdown (`.md`) file: 1. Open your notebook in DBCode 2. Click **Export / Share** button in the toolbar 3. Choose **Markdown** format from the export side panel 4. **Optional**: untick **Include query results** to export the cell source only Markdown cells are written inline, and SQL or Python cells are wrapped in fenced code blocks. With **Include query results** enabled (the default), each cell's saved results are appended too: SQL grids become Markdown tables, Python text output becomes a code block, and images are embedded inline. This makes the format well suited to sharing queries, notes, and their results in pull requests, wikis, or documentation. ### Secure Share Publish your notebook securely using DBCode's sharing feature: 1. Open your notebook in DBCode 2. Click the **Export / Share** button in the toolbar 3. Configure sharing permissions and expiration 4. Get a secure link to share with others Learn more about secure sharing in our [Data Sharing documentation](/docs/data/share). ## Security and Password Protection Password protection is recommended when: - **Sensitive Data**: Your notebook contains confidential business information - **Compliance Requirements**: Industry regulations require data protection - **External Sharing**: Sharing with clients or partners outside your organization - **Public Distribution**: Distributing reports that may contain proprietary insights ### Password Best Practices - **Strong Passwords**: Use complex passwords with letters, numbers, and symbols - **Unique Passwords**: Don't reuse passwords from other systems - **Secure Distribution**: Share passwords through secure channels separately from the exported file --- ## Docs > Notebooks > Getting Started ### Getting Started ## Creating a New Notebook In Connections, hover over a database and select **Create New DBCode Notebook**. The notebook opens with one SQL cell already linked to the selected connection, database, and default schema. ![Create a new notebook](./create.png) ## Working with Cells ### Adding a Cell Use **Code** or **Markdown** in the notebook toolbar to add a cell. You can also open **More Actions...** in a cell toolbar and choose **Insert Cell**, or hover between cells or below the final cell to reveal the insert controls. ### Changing a Cell Type Open **More Actions...** and select **Change Cell to Markdown** to change a SQL cell to Markdown. The same menu lets you change a Markdown cell back to code. ## Executing Queries Select **Execute Cell** to the left of a SQL cell to run it and display the result below the cell. ![Execute cell](./run.png) Use **Run All** in the notebook toolbar to execute every SQL cell. The selected cell toolbar also provides **Execute Above Cells** and **Execute Cell and Below**. ## Result Behavior ### Result Tabs in Notebooks Each execution creates a result tab for that cell. By default, DBCode keeps up to three tabs. Use `dbcode.notebook.maxTabs` to change the limit. When `dbcode.notebook.maxTabs` is set to `1`, running the cell again refreshes the existing result tab and preserves its chart configuration. > **Note**: Unlike the SQL Editor, the Shift key modifier for toggling refresh-in-place is not available in notebooks since Shift+Enter is used to run cells. Use single-tab mode if you always want to refresh in place. ### Saving Outputs Notebook outputs are not saved in the file by default. Select **Save Output: Off** in the toolbar to enable output saving before you save the notebook. Saved outputs can contain sensitive data. Review them before sharing a notebook. ## Cell Management ### Joining Cells Open **More Actions...** in the cell toolbar to find the insert and join commands. ![Join cells](./join-cells.png) - **Join With Previous Cell** combines the current cell with the cell above it. - **Join With Next Cell** combines the current cell with the cell below it. - **Join Selected Cells** combines all selected cells. ## Tips for Getting Started - **Start Simple**: Begin with basic SQL queries to get familiar with the interface. - **Use Markdown**: Add Markdown cells to document your analysis and findings. - **Experiment**: Notebooks are useful for iterative data exploration. - **Save Frequently**: Save your work as you progress. ## Next Steps Once you're comfortable with the basics, explore: - [Python Integration](/docs/notebooks/python) to analyze SQL results with Python - [Exporting](/docs/notebooks/exporting) your notebooks - [Cell Locking](/docs/notebooks/cell-locking) for specific database connections - [Query Parameters](/docs/query/query-parameters) for dynamic queries across cells --- ## Docs > Notebooks > Python ### Python Integration DBCode Notebooks support Python cells, allowing you to combine SQL queries with Python data analysis tools. This powerful integration enables you to query your database with SQL and then process, visualize, and analyze the results using Python libraries like pandas, matplotlib, and numpy. ![DBCode Notebook showing a SQL cell with @var sales annotation, executed query results in a data grid, and the start of a Python cell below](./python-notebook.png) ![Python cell output showing a matplotlib bar and line chart of monthly sales performance](./python-chart-output.png) ## Prerequisites To use Python in DBCode Notebooks, you need to have the [Jupyter extension](vscode:extension/ms-toolsai.jupyter) installed in VS Code. ## Using Python Cells ### Adding a Python Cell When creating a new cell in a DBCode Notebook, you can choose the language for that cell. Simply change the language selector from "SQL" to "Python" to create a Python cell. ### Selecting a Python Kernel The first time you execute a Python cell in a notebook, DBCode will discover any running Jupyter kernels and prompt you to select one. If you have multiple Jupyter notebooks open with different kernels, you'll be able to choose which kernel to use. Your kernel selection is saved with the notebook, so you won't be prompted again unless you explicitly change it. You can change the kernel at any time by clicking on the kernel selector in the cell status bar. The kernel selector shows the Python environment and the Jupyter notebook it's running from (e.g., "Python - analysis.ipynb"), making it easy to identify which kernel you're using. ## SQL to Python Injection One of the most powerful features of Python integration is the ability to automatically inject SQL query results into Python as pandas DataFrames. This allows you to seamlessly transition from querying data to analyzing it. ### Enabling Injection To inject SQL results into Python: 1. Add `@var` annotations to your SQL cells as comments 2. Click the Python injection toggle in the SQL cell's status bar to enable injection 3. Select a Python kernel when prompted (if not already selected) 4. Execute the SQL cell 5. The results will be automatically available in your selected Python kernel as pandas DataFrames **Note**: You can inject SQL results to external Jupyter notebooks - the DBCode notebook doesn't need to contain Python cells. ### Using @var Annotations The `@var` annotation tells DBCode which variable name to use when injecting the result set into Python. Add it as a SQL comment before your query: ```sql -- @var users SELECT * FROM users WHERE created_at > NOW() - INTERVAL '7 days'; -- @var orders SELECT * FROM orders WHERE status = 'pending'; ``` ### Multiple Result Sets If your SQL cell produces multiple result sets (e.g., multiple SELECT statements), you can use multiple `@var` annotations. They are matched to result sets by order: ```sql -- @var user_count SELECT COUNT(*) FROM users; -- @var order_count SELECT COUNT(*) FROM orders; -- @var product_count SELECT COUNT(*) FROM products; ``` The first `@var` annotation gets the first result set, the second gets the second result set, and so on. ### Using Injected Data in Python Once injection is enabled and the SQL cell is executed, the variables are immediately available in Python cells: ```python # The 'users' DataFrame is automatically available print(f"Total users: {len(users)}") print(users.head()) # Analyze and visualize user_summary = users.groupby('country').size() user_summary.plot(kind='bar') plt.title('Users by Country') plt.show() ``` ### Injection Help When Python injection is enabled, a help icon (?) appears in the cell status bar. Click it to: - See which variables will be created - View the `@var` annotations found in the cell - Access this documentation ## Data Types SQL results are automatically converted to appropriate Python types: - **Numbers**: Integers and decimals become Python int/float - **Strings**: Text becomes Python str - **Dates/Times**: Timestamps are preserved as pandas datetime objects - **NULL values**: Converted to pandas NaN ## Example Workflow Here's a complete example of using SQL and Python together: **SQL Cell 1:** ```sql -- @var sales_data SELECT date_trunc('month', order_date) as month, SUM(amount) as total_sales, COUNT(*) as order_count FROM orders WHERE order_date >= '2024-01-01' GROUP BY date_trunc('month', order_date) ORDER BY month; ``` **Python Cell 1:** ```python # Calculate growth rate sales_data['growth_rate'] = sales_data['total_sales'].pct_change() * 100 # Create visualization fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8)) # Sales trend ax1.plot(sales_data['month'], sales_data['total_sales'], marker='o') ax1.set_title('Monthly Sales Trend') ax1.set_ylabel('Total Sales ($)') # Growth rate ax2.bar(sales_data['month'], sales_data['growth_rate']) ax2.set_title('Month-over-Month Growth Rate') ax2.set_ylabel('Growth (%)') ax2.axhline(y=0, color='r', linestyle='--') plt.tight_layout() plt.show() ``` ## Tips and Best Practices - **Variable Names**: Use descriptive variable names in `@var` annotations (e.g., `@var monthly_revenue` instead of `@var data`) - **One Query Per Variable**: While you can have multiple result sets, consider using separate SQL cells for complex queries to keep your analysis organized - **Check Your Data**: Always inspect the injected DataFrame with `.head()`, `.info()`, or `.describe()` before analyzing - **DataFrame Operations**: All standard pandas operations work on injected DataFrames (filtering, grouping, joining, etc.) - **Install Libraries**: Make sure required Python libraries (pandas, matplotlib, etc.) are installed in your Python environment ## Troubleshooting ### No Python Kernel Found If you don't have any running Jupyter kernels, DBCode will prompt you to open a Jupyter notebook and run a cell first. This initializes a kernel that DBCode can connect to. ### Variables Not Available Make sure: 1. Python injection is enabled (toggle in SQL cell status bar) 2. The SQL cell has been executed after enabling injection 3. Your `@var` annotations are correctly formatted as comments 4. You're using the correct variable name in Python ### Duplicate Variable Names Each `@var` annotation must have a unique name within the notebook. If you use the same variable name multiple times, DBCode will show an error and prevent injection. ## Next Steps - Learn about [Cell Locking](/docs/notebooks/cell-locking) to work with multiple database connections - Explore [Exporting](/docs/notebooks/exporting) notebooks with Python code and visualizations - Check out [Query Parameters](/docs/query/query-parameters) for dynamic SQL queries --- ## Docs > Query > Autocomplete ### Autocomplete **Autocomplete** is designed to assist with SQL query creation by providing context and schema aware suggestions in a context menu as you type. This streamlines your workflow by reducing typing effort, improving accuracy, and enhancing productivity. ## Key Features of Autocomplete 1. **Context-Aware Suggestions:** - As you type, a context menu appears with suggestions for table names, column names, SQL keywords, and functions relevant to your context. - For example, typing `SELECT` brings up options like `*`, column names, or tables, while `WHERE` suggests relevant fields from the tables specified in the query for filtering. ![Table suggestions after typing SELECT from a connected PostgreSQL schema](./context-suggestion.png) 2. **Schema-Aware Recommendations:** - Autocomplete integrates with your database schema to suggest valid options based on the connected database. - This ensures the suggestions include only accurate table names, column names, and data types, reducing the risk of errors. ![Column suggestions for the departments table in a WHERE clause](./context-columns.png) 3. **Enum Value Suggestions:** - Columns backed by a closed set of values, such as PostgreSQL enum types or MySQL `ENUM` columns, get their values suggested as quoted literals. - Suggestions appear after a comparison (`WHERE state = `), inside an `IN (...)` list, and in `UPDATE ... SET` assignments, ranked ahead of other completions. Typing `=` or an opening quote triggers them, and quoting matches your database's dialect. 4. **SQL Syntax Highlighting and Validation:** - Autocomplete supports SQL keywords and syntax, helping you construct valid queries and minimizing potential mistakes. 5. **Keyboard Navigation:** - Use the `Arrow Keys` to navigate the context menu and press `Enter` or `Tab` to insert your selected option directly into your query. ## Benefits of Autocomplete - **Speed:** Quickly locate and insert relevant fields, tables, or commands without needing to remember exact names or syntax. - **Accuracy:** Schema-awareness ensures that suggestions are valid and contextually appropriate. - **Ease of Use:** A context menu simplifies navigation, making it easy for users of all experience levels to write SQL queries. - **Error Reduction:** Autocomplete minimizes typos and syntax errors, leading to more reliable query execution. Autocomplete is an essential tool for writing SQL efficiently and accurately. Whether you're exploring a database schema, constructing complex queries, or working on repetitive tasks, this feature provides a streamlined and intuitive experience. --- ## Docs > Query > Debugger ### Debugger Stored routines are usually the hardest thing in a database to reason about: you can read the source, but you cannot see what it actually did. DBCode's debugger runs a function or procedure on the server and pauses it wherever you set a breakpoint, so you can step through the logic line by line and inspect real values as they change. It uses the native VS Code debug UI. Breakpoints go in the gutter of the routine's source, and the Run and Debug view shows the call stack, variables, and watches exactly as it does for any other language. Debugging requires a DBCode Pro subscription, and the database server needs to be set up for it. Each database documents its own requirements: see [Supported Databases](#supported-databases). ## Starting a session Open the function or procedure from the database explorer, then start the debugger any of these ways: - Click the **Debug** CodeLens above the routine definition - Click the **Debug** icon in the editor title bar - Right-click the routine in the database explorer and choose **Debug** DBCode checks the server is ready, collects any arguments, and runs the routine. If the routine cannot be debugged (the wrong language, for example) it says so and names the reason rather than failing silently. Debugging runs against the **deployed** source, which is the definition currently stored on the server. If the editor has unsaved changes, apply or revert them first so the lines you set breakpoints on match the lines the server executes. ![A PostgreSQL function open in VS Code with a breakpoint set and the Debug action highlighted.](./debug-start.png) ## Arguments If the routine takes arguments, DBCode prompts for them in the results panel using the same parameter grid as [query parameters](/docs/query/query-parameters), so the values are entered the same way you already enter them for a query. - Type a value to pass it - Leave a cell empty to use the routine's own default, where it has one - Enter `(null)` to pass a SQL `NULL` - Enter `(empty)` to pass an empty string, which an empty cell cannot express for an argument that has a default Values are remembered per routine, so re-running a debug session keeps what you entered last time. ![The debugger argument grid with the value 20 entered for a PostgreSQL function.](./debug-arguments.png) ## Stepping and inspecting Once paused you get the usual debug controls: | Control | Behaviour | |---|---| | Continue | Run to the next breakpoint, or to the end | | Step Over | Run the current line, then pause on the next one | | Step Into | Step into a called routine that can also be debugged | | Step Out | Return from the current routine to its caller, when the database debugger supports it | | Stop | End the session and cancel the running routine | The **Variables** view lists the routine's variables at the current line, and values update as you step. When the database and variable type support it, you can edit a value while paused to try a different path without changing the source. The **Watch** view accepts variable names, so you can pin the few values you care about instead of scanning the whole list. The **Call Stack** view shows the nesting when one routine calls another. Selecting a frame shows that frame's variables. ![A PostgreSQL debug session paused at a breakpoint with local variables and the call stack visible.](./debug-paused-session.png) ## Output and results Routine results land in the DBCode results panel: - Engines that support live routine messages can stream them into the panel as they happen. For example, PostgreSQL can stream `RAISE NOTICE` messages from PL/pgSQL - When the routine finishes, whatever it returns is shown as a normal result tab, the same as running it directly ## Connections Debug sessions use engine-specific dedicated resources that are separate from the connection pool used by ordinary queries. - PostgreSQL opens two dedicated database connections: one executes the routine, and the other drives stepping and reads variables. - Db2 opens one dedicated execution connection and a temporary callback listener on the extension host. Db2 must be able to reach that listener. - Oracle opens two dedicated Thin mode database connections: one executes the routine, and the other drives stepping and reads variables. Dedicated debug connections are not released for inactivity, so you can inspect a breakpoint without the session reconnecting to a different backend. The [Editor Connection Idle Timeout](/docs/query/idle-timeout) does not apply to them. Each engine closes its dedicated resources when the session ends. ## Limits - **Step Out** is available for Db2 and Oracle, but not PostgreSQL - **Pause** cannot interrupt a routine mid-run; use a breakpoint to stop where you need - **Watch expressions** accept variable names only, not arbitrary expressions - **Variable editing** depends on the database and variable type - Breakpoints apply to the deployed source, so a routine that is redeployed while paused ends the session ## Supported Databases | Database | Requirements | |---|---| | [PostgreSQL](/docs/supported-databases/postgres/postgres#debugging) | The `plugin_debugger` plugin loaded, the `pldbgapi` extension installed, a superuser or routine-owner role, and a `LANGUAGE plpgsql` routine | | [IBM Db2](/docs/supported-databases/db2#debugging) | Db2 LUW, a debug-enabled SQL PL procedure, the required debugger roles and privileges, and reverse callback reachability | | [Oracle](/docs/supported-databases/oracle#debugging) | Thin mode, classic `DBMS_DEBUG`, `DEBUG CONNECT SESSION`, and a standalone routine compiled with debug and PL/Scope metadata | --- ## Docs > Query > Execution Plans ### Execution Plans Execution Plans help you see how your database executes a query so you can debug, tune performance, and avoid costly mistakes. DBCode supports database native plan generation (EXPLAIN and, where supported, ANALYZE/actual plans) and provides an interactive Plan Explorer for deep inspection. - EXPLAIN: Generates the estimated execution plan without running the query. - ANALYZE / Actual Plan: Executes the query and returns actual timing and row counts (only on engines that support it). - Plan Explorer: An interactive view to explore nodes, costs, timings, cardinality, predicates, and potential bottlenecks. ## How To Use You can run Execution Plans from both the SQL Editor and DBCode Notebooks: 1. Write or select a SQL query. 2. Choose one of: - Explain: Runs the database's EXPLAIN for the selected query. - Analyze: Runs the database's ANALYZE/actual plan (where supported) and returns runtime metrics. 3. View results in the Plan Explorer panel. Tip: If no text is selected, DBCode uses the active statement under your cursor. ## Plan Explorer The Plan Explorer renders plans in a clear, navigable tree so you can quickly find hotspots and understand operator behavior. - Node Tree: Expand/collapse nodes to explore scans, joins, sorts, aggregates, etc. - Metrics At A Glance: View estimated vs. actual rows, cost, and time (when available). - Predicates & Filters: Inspect join conditions, index usage, filter predicates, and projections. - Hotspot Highlighting: Identify the most expensive operators to focus tuning efforts. - Search & Navigation: Quickly jump to nodes by name or operator type. ![Plan Explorer table view showing execution plan nodes](./plan-table.png) ### Charts Open the Charts panel to visualize the execution plan as a Sankey diagram, Sunburst, or Treemap. Toggle between Time, Cost, and Rows to highlight different aspects of the plan. ![Plan Explorer with Sankey diagram chart](./plan-chart.png)
Plan Explorer interactive example. Open in a new tab
## Supported Engines DBCode issues database native commands for plan generation and only shows options that are supported by your engine and permissions. Common examples include: - PostgreSQL: EXPLAIN, EXPLAIN ANALYZE - MySQL/MariaDB: EXPLAIN (ANALYZE available on modern versions) - SQLite: EXPLAIN QUERY PLAN - SQL Server: Estimated vs. actual execution plans - Oracle: EXPLAIN PLAN ## When To Use Explain vs. Analyze - Use EXPLAIN to review the optimizer's plan safely without executing the query. - Use ANALYZE to compare estimates with actuals, validate cardinality, and pinpoint miss estimates and slow operators. This will execute the query. ## Tuning Workflow 1. Explain the query to understand operator choices and index usage. 2. Identify potential issues (full scans, mismatched join orders, sorts, spills). 3. Analyze (where supported) to compare estimated vs. actual rows and timings. 4. Apply changes (indexes, rewritten predicates, smaller result sets, better join order). 5. Re-run Explain/Analyze to validate improvements. ## AI Analysis The Plan Explorer includes a built-in AI assistant that can analyze your execution plan and provide actionable optimization suggestions. ### How It Works 1. Run an Explain or Analyze for your query. 2. In the Plan Explorer, open the **AI Analysis** panel. 3. Enter a prompt — or use the default — describing what you want to analyze. 4. The assistant reviews your execution plan, the original SQL query, and your database schema, then returns: - Identified bottlenecks with specific node references - Explanations of performance issues in plain language - Suggested SQL improvements (indexes, query rewrites) as ready-to-use code blocks ### Model Selection The AI assistant uses whichever provider is active in your DBCode AI settings: - **Custom Model** — your own OpenAI-compatible endpoint (see [Custom Provider](/docs/ai/custom-provider)) - **GitHub Copilot** — if installed and active - **DBCode AI** — hosted model, always available as fallback You can temporarily switch to a different model for a single analysis directly from the assistant panel, without changing your default settings. This is useful when you want a more capable model for a complex plan while keeping a fast model for inline completions. ### What Data Is Sent When you request AI analysis, the following is sent to the selected model: - The execution plan (JSON structure with nodes, costs, timings) - The original SQL query - Database schema for tables referenced in the plan (table/column names, types, indexes) - The database dialect (e.g. PostgreSQL, MySQL) No credentials, connection strings, or actual data values are sent. See [Privacy and Security](/docs/ai/privacy-and-security) for details. ## Troubleshooting - Permissions: Some databases require specific roles/privileges to generate plans. - Long Running Queries: ANALYZE executes the query; prefer EXPLAIN during iteration. - Parameter Effects: Different parameter values can lead to different plans; test representative inputs. - Engine Support: If a button isn't shown, your database/driver may not support that plan type yet in DBCode. Execution Plans and the Plan Explorer give you clear visibility into query behavior so you can optimize confidently, without leaving VS Code. --- ## Docs > Query > Favorites ### Favorite objects Favorites let you bookmark database objects directly in the connection tree. Favorited items appear in a dedicated **Favorites** section at the top of each connection, giving you one-click access to the tables, views, procedures, and other objects you use most. ## Adding Favorites To add a database object to your favorites: 1. Find the item in the DB Explorer panel (table, view, stored procedure, etc.) 2. Right-click and choose **Add to Favorites**, or drag and drop it into the Favorites section The object appears under a **Favorites** node at the top of that connection's tree. ## Removing Favorites Right-click a favorited item and choose **Remove from Favorites** to remove it. ## Related Features - [Library](/docs/query/library): Save scripts, Query Builder queries, Explore views, and file references in a dedicated panel with folders and drag-and-drop organization - [Query History](/docs/query/history): Automatically track and recall executed queries --- ## Docs > Query > History ### Query history History automatically logs executed SQL queries, allowing you to review, reuse, and manage past queries with ease. By default, the History feature is **disabled**. In the DBCode Explorer, open the **History** view. ![History panel in DBCode](./history-panel.png) Click **Enable history** to start recording executed SQL queries. ![Enable history in DBCode](./enable-history.png) ### Accessing Query History 1. **Open DBCode in Visual Studio Code:** - Launch Visual Studio Code and click the DBCode icon in the Activity Bar on the left. ![DBCode icon in VS Code](./dbcode-icon.png) 2. **Open the History Panel:** - In the DBCode sidebar, click the **History** view to access the list of previously executed queries. ![History panel view](./query-list.png) ## Using the History Panel 1. **View Past Queries:** - The History panel shows a chronological list of queries grouped by connection and database. - Use the `Expand All` icon to see all details or the `Queries Only` icon to show a list of queries from all connections and databases. - Apply filters using the `Filter` icon to narrow your view based on specific criteria. ![Query history list](./query-list.png) 2. **Re-Run a Query:** - Click the **Load Query** icon next to any query to reload it into a new editor tab for the selected database connection. ![Re-run a saved query](./run-query.png) 3. **Edit and Copy Queries:** - Use the **Copy SQL** icon to duplicate a query. Paste it into the editor to modify or use as a new template. ![Copy a query from history](./copy-query.png) 4. **Delete History:** - To delete a query, click the **Delete** icon next to it. Confirm the action by selecting "Yes" in the prompt. Individual queries or all queries for a database can be deleted. ![Clear query history](./clear-history.png) ## Benefits of Using Query History - **Time-Saving:** Quickly re-run frequently used queries without retyping. - **Efficient Troubleshooting:** Easily review past queries to identify and resolve issues. - **Organized Workflow:** Maintain a comprehensive log of query development for easy reference. Enabling and using the History can streamline your workflow and make database interactions in Visual Studio Code more efficient and organized. --- ## Docs > Query > History Sync ### History Sync & Backup History Sync keeps your query history available across devices using client-side encryption and cloud storage. Encryption happens on your machine before upload; only encrypted data is stored in the cloud. ## Capabilities - End to end encrypted sync and cloud backup - Local first: works offline; syncs when online - Conflict free merges across devices (CRDT powered) - Restore on new devices ## Requirements - Signed in DBCode account - History enabled in DBCode - Network access to DBCode API and storage ## How It Works Your history is stored locally on your device. Before upload, DBCode encrypts changes on device using a randomly generated Data Encryption Key (DEK). The DEK is protected by a server stored key envelope: the DEK is wrapped with a Key Encryption Key (KEK) derived from your passphrase via scrypt. The passphrase never leaves your device and is not stored; only the encrypted DEK (the envelope) and encrypted history blobs are stored in the cloud. On another device, DBCode fetches the envelope, prompts once for your passphrase to unwrap the DEK, and decrypts data locally. ![History Sync encryption and multi-device flow](./sync-encryption-flow.svg) ## Sync Cadence & Retention - Updates: Background sync batches and uploads changes every 2 hours. - Snapshots: A full snapshot is created every 7 days. - Restore path: New devices restore using the latest snapshot plus any subsequent updates. - Retention: Updates are retained for 1 month; snapshots for 6 months. - Protection: Uploads are compressed and then encrypted on your device before leaving it. ## Enable Sync 1. Open DBCode in VS Code and go to the DBCode Explorer sidebar. 2. Open the History view and click the sync icon. 3. Create an encryption passphrase (recommended minimum 12 characters). It never leaves your device and is not stored. DBCode derives a KEK from your passphrase to wrap a generated DEK and uploads only the encrypted envelope; the decrypted DEK is cached locally in VS Code Secret Storage so you won't be prompted again on this device. 4. If this is a new device, history will be restored from the cloud; otherwise your device begins syncing changes in the background. Tip: You can also manage sync via settings: DBCode: History: Enable Sync. > Important: Use the same passphrase on every device that participates in History Sync. If you forget your passphrase, you will not be able to unwrap the DEK to decrypt your cloud history. We cannot recover or reset your passphrase. ## Restore on a New Device When enabling sync on a device without local history, DBCode can restore from your encrypted cloud backup. ![Restore encrypted history on a new device](./restore-sync-flow.svg) ## Security - Client side only: Encryption and decryption happen on your device. - End to end encryption: History blobs are encrypted with a random 32 byte DEK using AES 256 GCM. The DEK is wrapped by a KEK derived from your passphrase via scrypt and stored only as an encrypted envelope on the server. - Passphrase privacy: Your passphrase never leaves your device and is never stored. The decrypted DEK is cached locally in VS Code Secret Storage for seamless use on that device. - Zero knowledge storage: Only encrypted data and an encrypted DEK envelope are stored in S3 compatible storage; we cannot decrypt them. - Additional protection: Server side encryption at rest (SSE) is enabled on storage as a secondary layer. - Local storage: DBCode does not encrypt your history at rest on your device; encryption is applied immediately before upload. - Passphrase scope: All devices must use the same passphrase to unlock the same DEK; changing your passphrase rewraps the DEK without re encrypting your history data. ## Related - Learn the basics of [History](/docs/query/history) ## Technical Details - Key envelope: Server stores a small JSON envelope containing the DEK encrypted (wrapped) with a KEK derived from your passphrase using scrypt, along with scrypt parameters and AES GCM IV/tag. Only the encrypted DEK is stored; the passphrase is never transmitted. - Blob format: Each uploaded blob begins with a compact header identifying the format version and a `keyId`, followed by AES GCM output: IV || ciphertext || tag. The `keyId` lets DBCode select the correct DEK if rotation is added. - First device: If no envelope exists, DBCode generates a DEK, wraps it with your passphrase derived KEK, uploads the envelope, and caches the DEK in Secret Storage. - New device: DBCode fetches the envelope, prompts for your passphrase to unwrap the DEK, caches it locally, and decrypts history. - Change passphrase: DBCode derives a new KEK from your new passphrase and rewraps the same DEK; history blobs do not need to be re encrypted. --- ## Docs > Query > Idle Timeout ### Editor Connection Idle Timeout DBCode maintains dedicated connections for SQL editor tabs to support features like [transaction control](/docs/query/transaction-control). These connections run periodic keepalive queries to prevent server-side disconnection. For serverless or pay-per-query databases like **Redshift Serverless**, **Snowflake**, **BigQuery**, and **Databricks**, these keepalive queries can result in unexpected charges. The Editor Connection Idle Timeout setting allows you to automatically release these connections after a period of inactivity. ## Configuring the Idle Timeout The idle timeout is configured per-connection in the **Advanced** section of the connection settings: 1. Open the connection configuration (click the edit icon on your connection) 2. Scroll to the **Advanced** section 3. Set **Editor Connection Idle Timeout** to your preferred value: - **Never** (default) - Connections are kept alive indefinitely - **5 minutes** - Recommended for serverless databases - **10 minutes** - **15 minutes** - **30 minutes** - **1 hour** ## How It Works When the idle timeout is enabled: 1. **Timer starts** when a query completes and the editor becomes idle 2. **Timer pauses** while a query is running, and resets when it finishes 3. **Connection releases** automatically when the timeout expires Because the timer only counts idle time, a query that takes longer than the timeout is never interrupted. A five minute timeout will not cut off a query that runs for an hour. ### Handling Uncommitted Changes If you have uncommitted changes when the timeout expires (auto-commit is off): 1. A **warning notification** appears showing the remaining time 2. The timeout is **extended by the same period** to give you time to respond 3. You can click **Cancel** to keep the connection and reset the timer 4. If the grace period expires, changes are **automatically rolled back** and the connection is released ![Grace period notification for uncommitted changes](./grace-period-notification.png) The grace period gives you time to commit or rollback your changes before the connection is released. ## Recommended Settings | Database Type | Recommended Timeout | |--------------|---------------------| | Redshift Serverless | 5 minutes | | Snowflake | 5-10 minutes | | BigQuery | 5-10 minutes | | Databricks | 5-10 minutes | | Provisioned databases | Never (default) | For provisioned databases where you pay a fixed cost regardless of queries, the default "Never" setting is appropriate and provides the best user experience. ## Output Logging When connections are released due to inactivity, DBCode logs the event to the Output panel: - **Clean release**: `Connection: Released idle pinned connection for 'myfile.sql' after 5 minute(s)` - **With uncommitted changes**: `Connection: Released idle pinned connection for 'myfile.sql' after grace period (2 changes rolled back)` ## Debug Sessions The idle timeout does not apply to the dedicated connections a [debug session](/docs/query/debugger) uses. A routine paused at a breakpoint exists only on the backend that is running it, so releasing and reconnecting would lose the session. Those connections are held until the session ends, however long you spend stepping through the code. ## Related - [Transaction Control](/docs/query/transaction-control) - Learn about managing database transactions - [Debugger](/docs/query/debugger) - Step through stored routines with breakpoints and variables --- ## Docs > Query > Inline Completion ### Inline Completion Inline Completion uses AI to enhance SQL coding productivity and generate schema aware SQL directly within your editor, enabling you to create complex queries, or ask natural language questions. 1. **Start Typing a SQL Query:** - Begin writing your SQL query or command in a DBCode-supported environment, such as a `.sql` file or a DBCode Notebook. - As you type, Inline Completion displays light grey text suggesting how to complete your query based on the context. - To ask a question, you can enter the text as an SQL comment, such as `-- What find all the users with the last name "Smith"?` and the LLM will generate a query for you, using knowledge of the schema of your database. ![Inline completion in action](./inline-completion.png) 2. **Accept Suggestions:** - Press `Tab` to insert the suggested code where your cursor is. 3. **Dismiss Suggestions:** - To ignore a suggestion, simply keep typing, and the prediction will adjust dynamically to the new input. 4. **Dynamic Updates:** - Inline Completion updates its predictions in real-time as you continue typing, refining suggestions based on the context of your query. ![Dynamic inline suggestions](./dynamic-inline-suggestion.png) ## Benefits of Inline Completion - **Speed:** Write queries faster by leveraging intelligent predictions that eliminate unnecessary typing. - **Accuracy:** Reduce syntax errors with compliant suggestions tailored to your database schema. - **Convenience:** Avoid interruptions by getting in-line predictions directly in the editor, without needing external references. Inline Completion is a powerful feature for SQL developers, streamlining query creation by predicting and suggesting contextually appropriate completions. Whether you're a beginner or a seasoned professional, this tool enhances productivity and coding efficiency in Visual Studio Code. If you have an active Copilot subscription in VS Code, you can use the Copilot provided models for suggestions, but it is not required. ## Model Selection DBCode uses one of two model sources for inline completion: - **GitHub Copilot** (if installed and active) - **DBCode Hosted Model** (automatic fallback when Copilot is not available) For details on how models are selected and configured, see [AI Models and Configuration](/ai/models-and-configuration). ## Privacy and Security Inline completion shares your database schema (table and column names) with AI models to provide accurate suggestions. Only the database structure is sent - never actual data values or credentials. For security considerations, see [AI Privacy and Security](/ai/privacy-and-security). ## Provide Schema to Copilot for .sql files By providing the schema of your database to Copilot, you can get more accurate and relevant inline completions. When enabling this function, DBCode will utilize Copilot to perform inline completions for `.sql` files, and provide the schema of your database to Copilot to generate more accurate and relevant suggestions. To enable this feature locate the GitHub > Copilot: Enable setting, and add sql to the item list with a value of false. --- ## Docs > Query > Library ### Saved script library The Library lets you save and organize reusable items across your projects. It supports four item types: - **Scripts** - SQL snippets with connection metadata - **Query Builder queries** - Full visual Query Builder state (tables, joins, filters, columns) - **Explore views** - Saved data exploration configurations - **File references** - Links to SQL files in your workspace ## Project and Personal Scopes Items are organized under two scopes: - **Project** - Stored in `.dbcode/library/` in your workspace folder. Shared with anyone who opens the project (ideal for team queries and shared scripts). - **Personal** - Stored in your VS Code global storage. Private to you and available across all workspaces. ![Library panel with Project and Personal scopes, an expanded Reports folder, and saved SQL scripts](./library-overview.png) ## Adding Items ### Save from the SQL Editor 1. Select SQL text in any editor 2. Click **Add to DBCode Library** in the editor toolbar, or run the command from the Command Palette 3. Enter a name 4. Choose **Project** or **Personal** in the scope picker ![Scope picker for saving selected SQL to the Project or Personal library](./save-to-library.png) ### Save from the Query Builder Click **Save to Library** in the Query Builder toolbar: - **First save** - Prompts for a name and scope, then stores the full visual state (tables, joins, filters, columns, positions) along with the generated SQL - **Subsequent saves** - Updates the saved item silently - **Save As New** - Creates a copy with a new name ### Drag Files from the Explorer Drag `.sql` or other files from the VS Code Explorer into the Library panel. DBCode creates a file reference that opens the file when clicked. For Project scope, workspace-relative paths are stored so references work for all team members. ## Organizing with Folders Right-click on a scope root or existing folder and choose **Create Folder**. Drag and drop items and folders to rearrange them, including moving items between Project and Personal scopes. ## Opening Items Click any item in the Library tree to open it: - **Scripts** open in a new SQL Editor tab bound to the original connection - **Query Builder queries** restore the full visual state in a Query Builder tab - **File references** open the linked file If the original connection is not available (for example, a shared project item from a teammate), DBCode prompts you to select a local connection. ## Renaming and Deleting Right-click any item or folder to rename or delete it. Deleting a folder removes all items inside it. ## File Format Library items are stored as plain files: | Type | Extension | Format | |------|-----------|--------| | Script | `.sql` | SQL with YAML frontmatter (name, connection, database) | | Query Builder | `.qb.json` | JSON with builder state and generated SQL | | Explore | `.explore.json` | JSON with exploration configuration | | File reference | `.file.json` | JSON with the file path | Because items are regular files, they can be version-controlled, shared, and edited outside of DBCode. ## Related Features - [Favorites](/docs/query/favorites): Bookmark database objects in the connection tree for quick access - [Query Builder](/docs/query/query-builder): Build queries visually and save them to the Library - [Query History](/docs/query/history): Automatically track and recall executed queries --- ## Docs > Query > Missing Where Detection ### Missing WHERE Detection DBCode automatically detects `DELETE` and `UPDATE` statements that are missing a `WHERE` clause before they execute. This prevents accidental mass data modifications that could affect every row in a table. ## How It Works When you execute a `DELETE` or `UPDATE` statement without a `WHERE` clause, DBCode intercepts the query and shows a warning dialog before execution. This gives you a chance to cancel the operation and add the appropriate filter. ![Missing WHERE warning showing the intercepted UPDATE statement with Execute Anyway and Cancel options](./missing-where-dialog.png) For example, the following statements would trigger the warning: ```sql -- Missing WHERE on DELETE - will affect ALL rows DELETE FROM users; -- Missing WHERE on UPDATE - will affect ALL rows UPDATE orders SET status = 'cancelled'; ``` While these statements execute normally without a warning: ```sql -- Has WHERE clause - targets specific rows DELETE FROM users WHERE id = 5; -- Has WHERE clause - targets specific rows UPDATE orders SET status = 'cancelled' WHERE order_id = 123; ``` ## Detection Behavior | Statement | Detected | |-----------|----------| | `DELETE FROM table` | Yes | | `DELETE FROM table WHERE ...` | No | | `UPDATE table SET ...` | Yes | | `UPDATE table SET ... WHERE ...` | No | | `SELECT * FROM table` | No | | `INSERT INTO table ...` | No | ### Subquery Awareness The detection is aware of subqueries and only checks for `WHERE` at the top level of the statement. A `WHERE` inside a subquery does not count: ```sql -- Still flagged - the WHERE is inside the subquery, not on the UPDATE UPDATE orders SET total = (SELECT SUM(amount) FROM items WHERE order_id = orders.id); -- Not flagged - has a top-level WHERE clause DELETE FROM users WHERE id IN (SELECT user_id FROM inactive); ``` ### CTE Support Common Table Expressions (CTEs) are handled correctly: ```sql -- Flagged - DELETE has no WHERE clause WITH cte AS (SELECT id FROM temp) DELETE FROM users; -- Not flagged - DELETE has a WHERE clause WITH cte AS (SELECT id FROM temp) DELETE FROM users WHERE id IN (SELECT id FROM cte); ``` ## Availability Missing WHERE detection runs automatically on every query execution. When combined with [Connection Roles](/docs/connections/roles), the behavior is configurable per role: | Permission | Behavior | |------------|----------| | **Allow** | No detection; statements execute without checking | | **Ask** (default) | Warning dialog appears; you choose to proceed or cancel | | **Deny** | Statements are blocked entirely | The default settings for each role: | Role | Missing WHERE | |------|--------------| | Development | Ask | | Testing | Ask | | Production | Deny | ## Configuring Missing WHERE Detection ### With Connection Roles 1. Open **Settings** in VS Code 2. Navigate to **Extensions** > **DBCode** > **Connection Roles** 3. Find the role assigned to your connection 4. Set the **Missing WHERE** permission to **Allow**, **Ask**, or **Deny** ### Without Connection Roles When no role is assigned, missing WHERE detection defaults to **Ask** behavior, showing a confirmation dialog when a potentially dangerous statement is detected. --- ## Docs > Query > Query Builder ### Query Builder The Query Builder in DBCode lets you construct SELECT queries visually. Add tables to a canvas, configure joins by dragging between columns, pick columns, set filters, and see the generated SQL update in real time. You can also use natural language to describe what you need and let AI build or modify the query for you. ![Query Builder with two joined tables, selected columns, filters, and SQL preview](./query-builder.png) ## Opening the Query Builder There are three ways to open the Query Builder: 1. **Tree icon** — Click the Query Builder icon next to a database in the DB Explorer 2. **Right-click** — Right-click a database and select **Open Query Builder** 3. **Command Palette** — Run `DBCode: Open Query Builder`. If no connection is in context, you'll be prompted to select one The Query Builder opens as a full editor tab with the connection's schema pre-loaded. ## Interface Overview The Query Builder is divided into four areas: - **Toolbar** (top) — AI input bar, Run/Explain button, Save, and Open in Editor - **Canvas** (left) — Drag-and-drop area where tables appear as nodes and joins appear as edges - **Config Panel** (right) — Stacked sections for column selection, filters, GROUP BY, HAVING, ORDER BY, DISTINCT, and LIMIT - **SQL Preview** (bottom) — Read-only, syntax-highlighted SQL generated from the current model. Updates live as you make changes. Resizable by dragging the top border ![Query Builder interface showing three joined tables, selected columns, a filter, and generated SQL](./overview.png) ## Adding Tables 1. Click the **Add Table** button on the canvas 2. Search for a table by name in the dropdown — it filters as you type 3. Select a table to place it on the canvas as a node Each table node shows the table name, its columns with data types, and primary/foreign key indicators. You can drag nodes to reposition them on the canvas. To remove a table, select its node and press Delete or Backspace. ## Selecting Columns Tick a column's checkbox on its table node to add it to the SELECT clause. The **Columns** section in the Config Panel then lists the selected columns in order: - **Drag to reorder**: grip handles on the left let you reorder selected columns, including across tables - **Alias**: click the alias field to give a column an output name - **Aggregate**: choose an aggregate function (COUNT, SUM, AVG, MIN, MAX) from the dropdown. When you apply an aggregate, GROUP BY is configured automatically for non-aggregated columns Click **+ Add column** for a searchable menu of every column. Each table has a select-all checkbox to add or remove all of its columns at once, handy for wide tables and available even when only one table is on the canvas. ## Joining Tables When you add a second table that has a foreign key relationship with an existing table, DBCode automatically suggests a join. ![Two tables on the canvas connected by an INNER JOIN with selected columns highlighted](./query-with-join.png) To create a join manually: 1. Drag from a column on one table node to a column on another 2. The join appears as an edge connecting the two tables ### Configuring Join Type Click a join edge to see the join type picker. Hover over a type to preview its Venn diagram and description, then click to select: - **INNER JOIN** — Only matching rows from both tables - **LEFT JOIN** — All rows from the left table, matching rows from the right - **RIGHT JOIN** — All rows from the right table, matching rows from the left - **FULL JOIN** — All rows from both tables - **CROSS JOIN** — Every combination of rows (Cartesian product) To remove a join, select the edge and press Delete or Backspace. ## Filtering Data The **Where** section lets you build WHERE clause conditions without writing SQL: 1. Click **+ condition** 2. Select a column from the dropdown 3. Choose an operator: `=`, `!=`, `>`, `<`, `>=`, `<=`, `LIKE`, `NOT LIKE`, `CONTAINS`, `NOT CONTAINS`, `IN`, `NOT IN`, `IS NULL`, `IS NOT NULL`, `BETWEEN`, or `NOT BETWEEN` 4. Enter a value ### Values are quoted for you DBCode quotes each value based on the column's type: text is quoted (`'GER'`), numbers stay bare (`18`), and `IN` lists are split on commas and quoted element by element (`'EU', 'US'`). To pass a value through verbatim, such as a column reference or a function call like `NOW()`, toggle the **fx** button on that condition. For text comparisons, the **Aa** button makes the match case-insensitive by wrapping both sides in `UPPER()`. ### Combining conditions with AND/OR groups The conditions in a group are joined by a single **Match** operator, **AND** or **OR**, selected at the top of the group. To mix AND and OR, nest a group: click **+ group** to add a sub-group with its own Match operator. This produces parenthesised SQL, for example `language = 'GER' AND (region = 'EU' OR region = 'US')`. Drag the grip handle on any condition or group to reorder it, or to move it into or out of a group. Removing the last condition from a group removes the empty group automatically. ## Grouping and Aggregation ### GROUP BY The **Group By** section lets you group results by one or more columns. Select columns from the dropdown to add them. When you apply aggregate functions to columns in the Columns section, non-aggregated selected columns are automatically added to GROUP BY. ### HAVING The **Having** section adds conditions that filter grouped results (like WHERE, but applied after aggregation). Add conditions with a column, operator, and value, just like the Where section. ## Ordering Results The **Order By** section controls result sorting: 1. Click **Add** to add a sort column 2. Select the column from the dropdown 3. Toggle between **ASC** (ascending) and **DESC** (descending) 4. Drag to reorder when multiple sort columns are defined ### DISTINCT and LIMIT - **DISTINCT** — Toggle the checkbox to eliminate duplicate rows - **LIMIT** — Enter a number to cap the result set size ## AI Assistance The text input at the top of the toolbar accepts natural language descriptions. Type what you need and press Enter: - **Build from scratch** — "Show me all customers with orders over $100 in the last 30 days" - **Modify existing** — "Add a date filter for last month" or "Change to LEFT JOIN" - **Aggregate** — "Show total sales by category" The AI reads your current query model and schema, then returns an updated model. The canvas, config panel, and SQL preview all update to reflect the changes. You can undo AI changes with Ctrl+Z / Cmd+Z. ## Running Queries Click the **Run** button (or use the dropdown for **Explain** / **Analyze** where supported by your database) to execute the generated SQL. Results appear in the standard Results Pane, just like running a query from the SQL Editor. The Query Builder tab stays open so you can refine and re-run. ## Saving to Library Click **Save to Library** to save the query builder state to your [Library](/docs/query/library) panel: - **First save** — Prompts for a name and scope (Project or Personal), then stores the full visual state (tables, joins, filters, columns, positions) along with the generated SQL - **Subsequent saves** — Updates the saved item silently (no prompt) - **Save As New** — Creates a copy with a new name Opening a saved query builder from the Library restores the full visual state — table positions, joins, column selections, filters, and all configuration. If the query builder is already open, clicking the saved item reveals the existing tab instead of opening a duplicate. ## Opening in Editor Click **Open in Editor** to copy the generated SQL into a new SQL Editor tab bound to the same connection. This is useful when you want to hand-edit the query or save it as a `.sql` file. ## Supported Databases The Query Builder works with all databases supported by DBCode. SQL generation adapts to each dialect automatically: - Identifier quoting (double quotes, backticks, or square brackets) - LIMIT vs TOP vs FETCH FIRST for row limiting - Schema qualification where applicable ## Undo and Redo All changes to the query model support undo and redo: - Ctrl+Z / Cmd+Z — Undo - Ctrl+Shift+Z / Cmd+Shift+Z — Redo This includes AI-generated changes, so you can safely experiment and revert. --- ## Docs > Query > Query Parameters ### Query Parameters DBCode provides flexible query parameter formats to help you create dynamic queries, supporting use across notebook cells. This guide explains the available parameter formats, their optional components, and best practices for effective usage. ### Supported Formats DBCode supports defining query parameters using the following prefixes: - **&** (e.g., `&user` for a parameter named "user") - **$** (e.g., `$amount` for a parameter named "amount") - **:** (e.g., `:event_date` for a parameter named "event_date") - **%** (e.g., `%(field)` for a parameter named "field") - *Only supported when using `{}` or `()` to enclose the parameter name.* ### Components Each format can include optional components: - **Syntax:** `&name||value||type` **Components:** - **value:** The assigned value of the parameter. - **type:** The data type of the parameter value. Supported types are: - **string:** Escapes the value as a text string. - **number:** Treats the value as a numeric type. - **date:** Handles the value as a date format. - **identifier:** Leaves the value unescaped. > **Note:** If no type is specified, DBCode will attempt to infer the type automatically. ### Handling Spaces If a parameter name or value contains spaces, enclose it in curly braces `{}` or parentheses `()` to avoid syntax errors. **Example:** ```sql SELECT * FROM orders WHERE customer_name = &{customer name||John Doe||string} ``` ### Use Query Parameters **1. Open DBCode Query Editor** - Launch DBCode within Visual Studio Code and open an `SQL editor` or `DBCode notebook`. **2. Write a Query with Parameters** - Incorporate one of the supported parameter formats into your SQL query. - Then execute the query by using Ctrl+Enter or by clicking on **Play** button ![SQL query with parameters](./query-parameter.png) **3. Confirm Values and Type for Parameters** - If any parameter value is not supplied in the query, DBCode will prompt you to input the required values and types, otherwise confirm the default or previously used values. - Click the `Continue` button to execute the parameterized query. ![Parameter input prompt](./parameter-prompt.png) **4. Review Query Results** - DBCode will execute the query with the provided parameter values and display the result. ![Query results with parameters](./query-result.png) ### Sharing in Notebook Cells - Query parameters can share data across notebook cells. Once a parameter is defined in one cell, it can be reused in subsequent cells. - DBCode caches previously defined parameter values. When you execute a cell, a prompt will appear in the result panel, allowing you to continue using the same value or modify it. Click Continue if no changes are needed. ### Parameter Reuse Once you define a parameter with its default value and type, you can reuse it throughout your query by referencing just the parameter name. This is particularly useful for complex queries where the same parameter is used multiple times. **Example:** ```sql SELECT * FROM actor WHERE id = &actorId||1||number AND status = 'active' AND id = &actorId ``` In this example, `&actorId` is first defined with a default value of `1` and type `number`. Later in the same query, you can simply use `&actorId` without repeating the default value and type - DBCode will use the previously defined configuration. ### Examples 1. **Using '&':** ```sql SELECT * FROM users WHERE username = &user ``` 2. **Using '$' with a default value:** ```sql SELECT * FROM transactions WHERE amount = $amount||100 ``` 3. **Using ':' with a default value and type:** ```sql SELECT * FROM events WHERE event_date = :event_date||2024-12-25||date ``` 4. **Using '%' with a default value and the identifier type:** ```sql SELECT * FROM products WHERE %{field||category||identifier} = 'Electronics' ``` --- ## Docs > Query > Run Tab ### Multi-Statement Run Tab When you run a script that contains more than one statement, DBCode shows a **Run tab** that anchors the whole batch. It reports live progress while the script executes, then a summary when it finishes. You no longer get one result tab per statement. ## What you see by statement type DBCode decides where each statement's result goes based on whether it returns columns: - **SELECTs** (anything that comes back with columns, including `INSERT ... RETURNING`, `MERGE ... OUTPUT`, `CALL` returning a resultset, `SHOW`, `DESCRIBE`, and so on) still get their own result tab with a data grid. - **DML and DDL** (`INSERT`, `UPDATE`, `DELETE`, `CREATE`, `ALTER`, and similar statements that return only a row count) flow into the Run tab's per-statement list and the output log. They no longer open individual tabs. ## When the Run tab appears The Run tab is the tab that shows while the batch is executing. What happens when the batch finishes depends on what it produced: - **All SELECTs, no errors** - the Run tab is dismissed and focus moves to the first result tab. You just see your result grids, exactly as before. - **Any DML/DDL, or any error** - the Run tab stays, showing the batch summary and per-statement detail. Single-statement execution is unchanged: a SELECT shows its grid, an `INSERT` shows "Success, N rows affected". ## While the batch runs The Run tab shows live progress: - How many statements have completed out of the total - Total rows affected so far - Elapsed time - The statement currently executing (for supported drivers) A **Cancel** button on the Run tab stops the batch. ![Run tab executing a six-statement PostgreSQL batch with the Cancel button highlighted](./run-tab-progress.png) ## When the batch finishes The Run tab summarizes the run: total statements, total rows affected, and total time. If any statement failed, each error is listed with its line number. Every statement is also recorded in the output log (the notepad icon on the left of the results panel), which keeps a history across runs. ![Completed Run tab showing six statements, affected rows, durations, and completion status](./run-tab-complete.png) ## Many SELECTs: the overflow tab If a batch produces a lot of SELECT results, the first several open as individual tabs and the rest collect into a single stacked overflow tab, so a script with hundreds of queries does not flood the panel with tabs. Use the existing **Unstack** action to split the overflow tab back into individual tabs. ### The `dbcode.stackThreshold` setting Controls how many individual SELECT result tabs a batch opens before extra results stack into the overflow tab. The default is `15`. Set it to `0` to disable overflow entirely, so every result gets its own tab. ## Notebooks The same behavior applies to multi-statement SQL notebook cells: the cell output shows a Run tab following the same rules. --- ## Docs > Query > Scratch Files ### Scratch Files Scratch Files provide a persistent workspace for your SQL queries by saving them to disk instead of using temporary untitled files. This feature automatically organizes your SQL work by connection and manages file rotation and cleanup. ## Overview When enabled, DBCode creates persistent scratch files on disk instead of opening untitled files. Each connection gets its own scratch file, and files rotate based on your configured schedule (hourly, daily, weekly, or monthly). Old files are automatically cleaned up based on your retention settings. **Key Benefits:** - **Persistent Storage:** Your SQL snippets are saved to disk and survive editor restarts - **Automatic Organization:** Files are organized by connection name and time period - **Automatic Cleanup:** Old scratch files are deleted based on your configured retention period - **Flexible Rotation:** Choose how often new scratch files are created ## Configuration To enable and configure Scratch Files, open VS Code settings and search for "DBCode Scratch Files": ### Enable Scratch Files [`DBCode > Scratch Files: Enabled`](vscode://settings/dbcode.scratchFiles.enabled) Enable scratch file mode to save SQL snippets to disk instead of using untitled files. - **Default:** `false` (disabled) ### Storage Path [`DBCode > Scratch Files: Path`](vscode://settings/dbcode.scratchFiles.path) Directory path to store scratch files. Supports `~` for home directory expansion. - **Default:** `~/.dbcode/scratch` ### Rotation Period [`DBCode > Scratch Files: Rotation Period`](vscode://settings/dbcode.scratchFiles.rotationPeriod) How often to create a new scratch file per connection. - **Default:** `day` - **Options:** - `hour` - Create a new scratch file each hour - `day` - Create a new scratch file each day - `week` - Create a new scratch file each week - `month` - Create a new scratch file each month - `none` - One persistent scratch file per connection, no timestamp ### Automatic Deletion [`DBCode > Scratch Files: Delete`](vscode://settings/dbcode.scratchFiles.delete) Automatically delete old scratch files based on their last modified date. - **Default:** `6months` - **Options:** - `never` - Never automatically delete scratch files - `1month` - Delete scratch files older than 1 month - `6months` - Delete scratch files older than 6 months - `1year` - Delete scratch files older than 1 year ## File Naming and Organization Scratch files are automatically named based on the connection, database, and time period: **Format:** `{connectionName}-{database}-{timestamp}.sql` ### Examples by Rotation Period - **Hourly:** `postgres-prod-myapp-2025-10-17-14.sql` - **Daily:** `postgres-prod-myapp-2025-10-17.sql` - **Weekly:** `mysql-dev-analytics-2025-W42.sql` - **Monthly:** `oracle-test-hrdb-2025-10.sql` - **None:** `postgres-prod-myapp.sql` Connection and database names are sanitized (special characters replaced with `-`) to ensure valid filenames. Extra files created with **New Query File** get a numbered suffix, for example `postgres-prod-myapp-2025-10-17-2.sql`. Some databases use their native extension instead of `.sql`: Power BI query files are `.dax`, and Elasticsearch and OpenSearch files are `.es`. ## Using Scratch Files Once enabled, scratch files work automatically: 1. **Opening SQL Queries:** When you open a SQL query from the schema explorer or other DBCode actions, it opens in the scratch file for that connection instead of an untitled file 2. **Appending Queries:** Multiple queries opened for the same connection are appended to the same scratch file (separated by blank lines) 3. **File Rotation:** When the rotation period changes (e.g., a new day starts with daily rotation), a new scratch file is automatically created 4. **Editing:** You can edit scratch files like any normal SQL file in VS Code ## Commands DBCode provides commands to manage your scratch files: ### New Query File **Command:** Right-click a database in the Connections panel and choose **New Query File** Creates an additional scratch file alongside the current one, with a numbered suffix (for example `postgres-prod-myapp-2025-10-17-2.sql`). Use this when you want a separate file for a different task; the **Open Query File** icon still takes you to the main scratch file. ### Scratch Files **Command:** Right-click a database in the Connections panel and choose **Scratch Files...** Shows a picker of all scratch files for that connection and database, newest first, including files from earlier rotation periods and numbered files. Selecting one opens it with the connection already attached, ready to execute. ### Open Scratch Files Folder **Command:** `DBCode: Open Scratch Files Folder` Opens the scratch files directory in your system file explorer, allowing you to browse, organize, or manually manage your scratch files. ### Delete Old Scratch Files **Command:** `DBCode: Delete Old Scratch Files` Manually triggers the deletion of old scratch files based on your configured retention period. This is useful if you want to clean up immediately rather than waiting for the automatic cleanup cycle. > DBCode automatically checks for old files to delete every 24 hours. This command allows you to manually trigger the cleanup process. ## Automatic Cleanup DBCode automatically manages scratch file cleanup: - **Initial Cleanup:** When DBCode starts with scratch files enabled, it checks for and deletes old files - **Periodic Cleanup:** Every 24 hours, DBCode checks for files older than your configured retention period - **Safe Deletion:** Files currently open in the editor are never deleted, even if they exceed the retention period ## Behavior Details ### File Reuse When scratch files are enabled: - If a scratch file for a connection already exists for the current period, queries are appended to it - If the file is already open in VS Code, new content is added to the end - If the file is closed, it's opened and new content is appended ### Connection and Database Organization - Each connection and database combination gets its own scratch files - Files are named using the connection name and database at creation time - If you rename a connection or switch databases, existing scratch files keep their original names ## Best Practices 1. **Choose Rotation Based on Usage:** - Use daily rotation for most workflows - Use hourly for rapid development sessions - Use weekly/monthly for lighter database work 2. **Set Appropriate Retention:** - For audit purposes: Set to `1year` or `never` - For active development: `1month` or `6months` is usually sufficient 3. **Organize Your Workspace:** - Use the "Open Scratch Files Folder" command to review and organize files - Consider version controlling important scratch files 4. **Custom Storage Path:** - Store scratch files in a project-specific directory by setting a custom path - Use workspace settings to have different scratch paths for different projects ## Troubleshooting ### Scratch files not being created 1. Verify the feature is enabled in settings (`dbcode.scratchFiles.enabled`) 2. Check that the configured path is valid and writable 3. Look for error messages in the DBCode output panel 4. Try manually creating the directory at your configured path ### Files not being cleaned up 1. Check your `dbcode.scratchFiles.delete` setting 2. Verify files are actually older than the retention period 3. Ensure files aren't currently open in VS Code (open files are preserved) 4. Manually run the "Delete Old Scratch Files" command ### Permission errors 1. Ensure you have write permissions to the configured directory 2. Try using a different path in user home directory 3. Check for filesystem restrictions or antivirus interference ## Related Features - [Query History](/docs/query/history): Automatically track and recall executed queries - [SQL Editor](/docs/query/sql-editor): Edit and execute SQL queries with syntax highlighting - [Library](/docs/query/library): Save and organize scripts, queries, and file references - [Favorites](/docs/query/favorites): Bookmark database objects in the connection tree --- ## Docs > Query > Sql Editor ### SQL Editor The SQL Editor in DBCode provides a powerful environment for working with `.sql` files, making it easy to write, execute, and manage SQL queries. It offers intelligent features like syntax highlighting, code formatting, autocomplete, and the ability to quickly switch database connections, ensuring a seamless and efficient workflow. ## Using the SQL Editor ### 1. **Create or Open a `.sql` File** - **From the Connections Panel:** Open the `Connections` pane in DBCode, select your desired database connection, and click the **Open Query File** icon next to the database. The file is automatically associated with that connection. If a query file for that connection is already open, the icon takes you back to it; when several are open, a picker lets you choose between them or create a new one. To always start a fresh file, right-click the database and choose **New Query File**. ![Creating a new SQL file from the Connections panel](./new-sql-file.png) - **From VS Code:** Use **File > New File** or Cmd+N (macOS) / Ctrl+N (Windows/Linux) to create a new file, then save it with a `.sql` extension. DBCode will automatically activate for any `.sql` file. ### 2. **Write SQL Code** - Begin typing SQL commands to take advantage of syntax highlighting, autocomplete, and error detection. - Use features like [Autocomplete](/docs/query/autocomplete) and [Inline Completion](/docs/query/inline-completion) for enhanced coding assistance. ### 3. **Format Code** - **Format Entire Document:** Right-click anywhere in the file and choose **Format Document**, or use the shortcut **Alt+Shift+F**. ![Formatting SQL code with right-click menu](./code-formatting.png) - **Format Selected Code:** Highlight a code block, right-click, and select **Format Selection**, or use Ctrl+K Ctrl+F (Windows/Linux) or Cmd+K Cmd+F (macOS). ![Formatting selected code](./format-selection.png) ### 4. **Switch Database Connections** - Use the dropdown in the code lens at the top of the editor or the status bar to change the active database connection. - Easily switch between databases without closing or reopening the file. - To give every `.sql` file in a folder the same connection by default, see [Folder Connections](/docs/connections/folder-connections). ![Switching database connections](./change-connection.png) ### 5. **Execute Queries and View Results** - **Run Selected Queries:** Highlight a query and click **Execute Selection** from the toolbar or right-click and select **Execute Selection with DBCode**. - **Run All Queries:** Click the **Execute Query** icon at the top-right corner or press Ctrl+Enter to run all queries in the file. ![Executing SQL queries](./execute-query.png) - **View Results:** Query results are displayed in the DBCode Results Panel at the bottom of the editor. ![SQL query with results in VS Code](./query-results.png) ### Result Tab Behavior By default, each query execution creates a new result tab. This allows you to compare results across multiple queries. However, if you've created charts or customized your view, you may want to preserve those settings when re-running a query. #### Refresh Result in Place Hold Shift while executing (Shift+Ctrl+Enter) to update the last result tab instead of creating a new one. This preserves any chart configuration you've created. #### Single-Tab Mode When using single-tab mode (`dbcode.maxTabs` set to `1`), the behavior is inverted - refresh-in-place becomes the default, and holding Shift creates a new tab instead. #### Behavior Matrix | Mode | Shift Key | Result | |------|-----------|--------| | Multi-tab | Not pressed | New tab created | | Multi-tab | Pressed | Last tab refreshed (chart preserved) | | Single-tab | Not pressed | Last tab refreshed (chart preserved) | | Single-tab | Pressed | New tab created | > **Note**: Pinned tabs are never replaced. If the last tab is pinned, a new tab will always be created. #### Stacked Results When executing multiple SQL statements, each result set typically opens in its own tab. Hold Alt while executing (Alt+Ctrl+Enter) to stack all result sets into a single tab with collapsible sections. Stacked result tabs feature: - **Collapsible sections** - Each result set has a header showing the SQL preview, row count, and column count. Click to expand or collapse. - **Resizable sections** - Drag the dividers between sections to adjust their heights. - **Synchronized scrolling** - Click the link icon in the first section header to synchronize horizontal scrolling across all grids. - **Close sections** - Click the X icon to remove a section. Closing the last section closes the tab. - **Connection indicators** - Sections from different connections show a colored left border matching the connection color. You can also stack existing result tabs by: - **Drag and drop** - Drag one result tab onto another to stack them together. - **Multi-select** - Hold Ctrl (Windows/Linux) or Cmd (macOS) and click multiple tabs, then right-click and select **Stack with...**. - **Context menu** - Right-click on a result tab and select **Stack with...** to choose another tab to stack with. ### 6. **Save and Reuse Queries** - Save your `.sql` file with Cmd+S (macOS) / Ctrl+S (Windows/Linux) for future use. Add comments to document your queries and keep them organized. ## Customizing Editor Colors DBCode contributes theme colors that you can override in your VS Code settings under `workbench.colorCustomizations`. This lets you adjust or disable visual decorations in the SQL editor. | Color ID | Description | Default | |----------|-------------|---------| | `dbcode.activeStatementBackground` | Background highlight on the active SQL statement | `#ffffff0d` | | `dbcode.insertMatchedParameterBackground` | Highlight on matched INSERT parameter/value pairs | `#7655FF28` | | `dbcode.highlight` | General accent color used across DBCode | `#7655FF` | For example, to disable the active statement background highlight, set the color to transparent: ```json "workbench.colorCustomizations": { "dbcode.activeStatementBackground": "#00000000" } ``` Or adjust it to match your theme: ```json "workbench.colorCustomizations": { "dbcode.activeStatementBackground": "#3344ff15" } ``` ## Benefits of the SQL Editor - **Flexible Connection Switching:** Effortlessly toggle between database connections within a single file. - **Enhanced Efficiency:** Advanced features like autocomplete, syntax highlighting, and formatting speed up the query-writing process. - **Integrated Workflow:** Easily manage and view results within the same editor, ensuring a smooth SQL development experience. DBCode's SQL Editor brings an intuitive and feature-rich experience to managing `.sql` files in Visual Studio Code, empowering users to write and execute SQL commands efficiently while maintaining organized workflows. --- ## Docs > Query > Sql Formatting ### SQL Formatting DBCode provides flexible SQL code formatting powered by [sql-formatter](https://github.com/sql-formatter-org/sql-formatter) with multiple configuration options. You can configure formatting through **VS Code settings**, **workspace configuration files**, or **explicit config file paths**. The SQL dialect is automatically detected based on your active database connection, so you don't need to configure it manually. ## Quick Start ### Option 1: VS Code Settings (Recommended) The easiest and most discoverable way to configure SQL formatting: 1. Open VS Code Settings (Cmd/Ctrl+,) 2. Search for **"dbcode formatting"** 3. Configure your preferences (e.g., `Keyword Case`, `Indent Style`, `Tab Width`, etc.) Settings can be configured at: - **User** level (applies to all projects) - **Workspace** level (applies to current project only) ### Option 2: Configuration Files For team-shared configurations or project-specific formatting rules: **Auto-Detection:** 1. Create a `.sql-formatter.json` file in your workspace root 2. Add your formatting preferences (see examples below) 3. DBCode automatically detects and uses your config **Custom Path:** 1. Open VS Code Settings 2. Search for **"dbcode.formatting.configPath"** 3. Set the path to your config file (absolute or relative to workspace root) ## Configuration Priority When formatting SQL, DBCode merges options in this order (later takes precedence): 1. [sql-formatter](https://github.com/sql-formatter-org/sql-formatter) defaults 2. VS Code editor settings (`editor.tabSize`, `editor.insertSpaces`) 3. **DBCode formatting settings** (`dbcode.formatting.*`) 4. Workspace **`.sql-formatter.json`** file (if found) 5. **Explicit config file** at `dbcode.formatting.configPath` (if set) 6. **SQL dialect** (automatically detected from your database connection) This allows you to set global defaults in VS Code settings, override them per-project with `.sql-formatter.json`, and further override with an explicit config file if needed. ## Configuration Options ### Case Formatting Control the casing of SQL keywords, data types, functions, and identifiers: ```json { "keywordCase": "upper", "dataTypeCase": "upper", "functionCase": "upper", "identifierCase": "preserve" } ``` **Options:** `"preserve"`, `"upper"`, `"lower"` **Example:** ```sql -- Before select count(*) from users where created_at > now() -- After (with upper case keywords/functions) SELECT COUNT(*) FROM users WHERE created_at > NOW() ``` ### Indentation Style Choose how SQL statements are indented: ```json { "indentStyle": "standard", "tabWidth": 2, "useTabs": false } ``` **Indent Style Options:** - `"standard"` - Standard block indentation - `"tabularLeft"` - Align keywords to the left - `"tabularRight"` - Align keywords to the right **Example (standard):** ```sql SELECT user_id, email, created_at FROM users WHERE active = true ``` **Example (tabularLeft):** ```sql SELECT user_id, email, created_at FROM users WHERE active = true ``` ### Logical Operators Control newline placement for `AND`/`OR` operators: ```json { "logicalOperatorNewline": "before" } ``` **Options:** `"before"`, `"after"` **Example (before):** ```sql SELECT * FROM users WHERE status = 'active' AND created_at > '2024-01-01' AND email_verified = true ``` **Example (after):** ```sql SELECT * FROM users WHERE status = 'active' AND created_at > '2024-01-01' AND email_verified = true ``` ### Expression Width Set maximum characters in parenthesized expressions: ```json { "expressionWidth": 50 } ``` **Example:** ```sql -- Short expressions stay on one line SELECT * FROM users WHERE (status = 'active' AND verified = true) -- Long expressions break to multiple lines SELECT * FROM users WHERE ( status = 'active' AND email_verified = true AND created_at > '2024-01-01' ) ``` ### Spacing Options Control spacing and line breaks: ```json { "linesBetweenQueries": 2, "denseOperators": false, "newlineBeforeSemicolon": false } ``` **linesBetweenQueries:** Number of blank lines between separate queries **denseOperators:** When `true`, removes spaces around operators ```sql -- denseOperators: false WHERE age >= 18 AND status = 'active' -- denseOperators: true WHERE age>=18 AND status='active' ``` **newlineBeforeSemicolon:** When `true`, places semicolons on separate lines ```sql -- newlineBeforeSemicolon: false SELECT * FROM users; -- newlineBeforeSemicolon: true SELECT * FROM users ; ``` ### Column Alias Alignment Align AS keywords in SELECT column lists for improved readability: ```json { "tabulateAlias": true } ``` When enabled, DBCode automatically aligns AS keywords and their aliases within SELECT clauses, making column lists easier to scan. **Example:** ```sql -- Before SELECT user_id AS id, email AS user_email, first_name AS fname FROM users -- After (with tabulateAlias: true) SELECT user_id AS id, email AS user_email, first_name AS fname FROM users ``` **Works with complex queries:** ```sql SELECT u.user_id AS id, u.email AS user_email, COUNT(o.order_id) AS order_count, SUM(o.total) AS total_spent FROM users u LEFT JOIN orders o ON u.user_id = o.user_id GROUP BY u.user_id, u.email ``` **Note:** This feature works best with single-line column expressions. Multi-line expressions (like complex subqueries) may not align as expected. ## Complete Configuration Examples ### Basic Configuration Suitable for most teams - uppercase keywords, standard indentation: ```json { "keywordCase": "upper", "dataTypeCase": "upper", "functionCase": "upper", "tabWidth": 2, "linesBetweenQueries": 2 } ``` ### Tabular Style Great for aligned keywords: ```json { "keywordCase": "upper", "dataTypeCase": "upper", "functionCase": "lower", "identifierCase": "preserve", "indentStyle": "tabularLeft", "logicalOperatorNewline": "before", "expressionWidth": 50, "linesBetweenQueries": 1, "tabWidth": 4, "useTabs": false } ``` ### Compact Style Minimalist formatting with lowercase keywords: ```json { "keywordCase": "lower", "dataTypeCase": "lower", "functionCase": "lower", "indentStyle": "standard", "linesBetweenQueries": 1, "denseOperators": true, "tabWidth": 2 } ``` ## Using Formatting Once your configuration is set up, format SQL code using: **Format Entire Document:** - Right-click → Format Document - Or press Alt+Shift+F (Windows/Linux) or Option+Shift+F (macOS) **Format Selection:** - Select code → Right-click → Format Selection - Or press Ctrl+K Ctrl+F (Windows/Linux) or Cmd+K Cmd+F (macOS) ### Multiple Workspaces For monorepos or multi-project workspaces, place separate `.sql-formatter.json` files in each workspace folder. DBCode checks each workspace folder in order. ### Using VS Code Settings All formatting options can be configured through VS Code settings under the `dbcode.formatting` namespace: - `dbcode.formatting.keywordCase` - Case for SQL keywords (preserve/upper/lower) - `dbcode.formatting.dataTypeCase` - Case for data types (preserve/upper/lower) - `dbcode.formatting.functionCase` - Case for function names (preserve/upper/lower) - `dbcode.formatting.identifierCase` - Case for identifiers (preserve/upper/lower) - `dbcode.formatting.indentStyle` - Indentation style (standard/tabularLeft/tabularRight) - `dbcode.formatting.logicalOperatorNewline` - AND/OR newline placement (before/after) - `dbcode.formatting.expressionWidth` - Max chars in expressions (number) - `dbcode.formatting.linesBetweenQueries` - Blank lines between queries (number) - `dbcode.formatting.denseOperators` - Remove spaces around operators (boolean) - `dbcode.formatting.newlineBeforeSemicolon` - Place semicolons on new lines (boolean) - `dbcode.formatting.tabulateAlias` - Align AS keywords in SELECT lists (boolean) **Note:** Tab width and tab/space preferences are automatically inherited from VS Code's `editor.tabSize` and `editor.insertSpaces` settings. ### Global Configuration File Use the `dbcode.formatting.configPath` setting to point to a shared config file: ```json { "dbcode.formatting.configPath": "~/shared-configs/sql-formatter.json" } ``` ## Troubleshooting **Config not working:** - Verify JSON syntax is valid (use a JSON validator) - Ensure file is named exactly `.sql-formatter.json` - Check file is in workspace root or path is correct in settings - Restart VS Code to reload the configuration **Inconsistent formatting:** - Multiple config files may exist (explicit path overrides workspace file) - Verify options match sql-formatter documentation - Check that your database dialect is supported **Configuration not reloading:** - DBCode watches for file changes automatically - If changes don't apply, try reloading VS Code window ## Further Reading - [sql-formatter](https://github.com/sql-formatter-org/sql-formatter) - The open-source formatter library powering DBCode's SQL formatting - [sql-formatter configuration options](https://github.com/sql-formatter-org/sql-formatter#configuration-options) - Complete reference for all available options - [SQL Editor](/docs/query/sql-editor) - Learn about SQL editing features in DBCode - [Autocomplete](/docs/query/autocomplete) - Intelligent SQL code completion --- ## Docs > Query > Transaction Control ### Transaction Control DBCode provides comprehensive transaction control for databases that support transactions, allowing you to manage auto-commit behavior, track uncommitted changes, and safely commit or rollback your database operations. Transaction control enables you to group multiple SQL statements into a single atomic operation, ensuring data consistency and integrity. With auto-commit turned off, you can execute multiple queries and review their effects before permanently committing the changes to the database. ## Understanding Auto-Commit Auto-commit is a mode that determines how database changes are handled: - **Auto-Commit ON (Default):** Each SQL statement is automatically committed to the database immediately after execution. This is the standard behavior for most database operations. - **Auto-Commit OFF:** SQL statements are executed but not committed automatically. Changes remain pending until you explicitly commit or rollback the transaction. This allows you to: - Execute multiple related queries as a single unit of work - Review the effects of your changes before making them permanent - Rollback changes if something goes wrong ## Transaction Status Bar When auto-commit is turned off, DBCode displays a transaction status indicator in the VS Code status bar showing: - Current auto-commit state (ON/OFF) - Number of uncommitted statements - Total rows affected by uncommitted changes **Example:** `🔒 Auto-Commit: OFF (3 statements, 15 rows)` Click the status bar indicator to access quick actions for managing your transaction. ![Transaction status bar showing uncommitted changes](./transaction-uncommitted.png) ## Managing Transactions ### Turning Auto-Commit Off To start managing transactions manually: 1. **Open a SQL file** connected to a database that supports transactions. 2. **Click the transaction status indicator** in the status bar. 3. **Select "Turn Auto-Commit OFF"** from the menu. DBCode will start a transaction, and subsequent queries will not be committed automatically. The status bar will update to show `🔒 Auto-Commit: OFF` along with the count of uncommitted changes. ![Auto-commit menu showing Turn Auto-Commit Off option](./transaction-autocommit-menu.png) ### Committing Changes When you're ready to permanently save your changes: 1. **Click the transaction status indicator** in the status bar. 2. **Select "Commit Transaction"** from the menu. 3. All uncommitted changes will be permanently saved to the database. **Alternative:** Execute a `COMMIT;` statement in your SQL editor. ![Transaction menu showing commit and rollback options](./transaction-commit-menu.png) ### Rolling Back Changes If you need to undo uncommitted changes: 1. **Click the transaction status indicator** in the status bar. 2. **Select "Rollback Transaction"** from the menu. 3. All uncommitted changes will be discarded, and the database will return to its state before the transaction began. **Alternative:** Execute a `ROLLBACK;` statement in your SQL editor. ### Turning Auto-Commit Back On When you have uncommitted changes and want to commit them and return to auto-commit mode: 1. **Click the transaction status indicator** in the status bar. 2. **Select "Turn Auto-Commit ON"** from the menu. 3. DBCode will commit all uncommitted changes and return to auto-commit mode. Alternatively, you can commit or rollback your changes first, then turn auto-commit back on. ## Tracking Uncommitted Changes DBCode automatically tracks operations performed while auto-commit is off: - **INSERT** statements - Shows number of rows inserted - **UPDATE** statements - Shows number of rows modified - **DELETE** statements - Shows number of rows removed - **DDL** statements - CREATE, ALTER, DROP (on databases with transactional DDL) The status bar displays a real-time summary of uncommitted changes. Hover over the status bar indicator to view a list of uncommitted operations in a tooltip, showing the SQL statement, statement type, and number of rows affected for each change. ### DDL and Transactional Databases How DDL statements behave with auto-commit OFF depends on the database: - **PostgreSQL, SQL Server, Snowflake** support transactional DDL. DDL statements like `ALTER FUNCTION` or `CREATE TABLE` execute within the transaction and are tracked as uncommitted changes. You can roll them back just like DML. - **MySQL, Oracle, DB2, ClickHouse** do not support transactional DDL. DDL implicitly commits. DBCode will warn you before executing DDL on these databases when auto-commit is OFF, since the database will commit the transaction regardless. ## Using SQL Transaction Statements In addition to the UI controls, you can manage transactions directly with SQL statements: ### Starting a Transaction Execute `BEGIN;` or `BEGIN TRANSACTION;` to explicitly start a transaction: ```sql BEGIN; ``` This automatically turns auto-commit off for the current editor. ### Committing a Transaction Execute `COMMIT;` or `COMMIT TRANSACTION;` to save all changes: ```sql COMMIT; ``` ### Rolling Back a Transaction Execute `ROLLBACK;` or `ROLLBACK TRANSACTION;` to discard all changes: ```sql ROLLBACK; ``` ### Example Transaction Workflow ```sql -- Start transaction BEGIN; -- Make changes UPDATE users SET status = 'active' WHERE last_login > '2024-01-01'; INSERT INTO audit_log (action, timestamp) VALUES ('bulk_activation', NOW()); DELETE FROM sessions WHERE expired = true; -- Review the changes (optional - check affected rows) -- Commit if everything looks good COMMIT; -- Or rollback if you need to undo -- ROLLBACK; ``` ## Transaction Settings DBCode provides settings to customize transaction behavior: ### Editor Connection Idle Timeout For serverless databases (Redshift Serverless, Snowflake, BigQuery, etc.), you can configure connections to automatically release after a period of inactivity. If you have uncommitted changes, you'll receive a warning and a grace period before auto-rollback. See [Editor Connection Idle Timeout](/docs/query/idle-timeout) for configuration details. ### Long Transaction Warning **Setting:** `dbcode.transactions.longTransactionThreshold` **Default:** `5` (minutes) **Range:** 0-60 minutes DBCode will warn you when a transaction has been open for longer than the specified threshold. This helps prevent accidentally leaving transactions open, which can lock database resources. Set to `0` to disable warnings. **Example:** ```json { "dbcode.transactions.longTransactionThreshold": 10 } ``` ### Auto-Rollback on Error **Setting:** `dbcode.transactions.autoRollbackOnError` **Default:** `false` When enabled, DBCode will automatically rollback the current transaction if a query fails with an error. This is particularly useful for databases like PostgreSQL that abort transactions on error. **Note:** Use this setting with caution, as it will discard all uncommitted changes when any query fails. **Example:** ```json { "dbcode.transactions.autoRollbackOnError": true } ``` ### Default Auto-Commit Mode **Setting:** `dbcode.transactions.defaultAutoCommit` **Default:** `true` Controls the default auto-commit mode for new pinned connections. Set to `false` to start with auto-commit OFF by default. This setting can be overridden per-role using the `autoCommit` property in [Connection Roles](/docs/connections/roles). For example, you could keep auto-commit ON globally but set it to OFF for your Production role. **Example:** ```json { "dbcode.transactions.defaultAutoCommit": false } ``` ## Database Compatibility Transaction control is available for databases that support transactions. The feature automatically detects whether your connected database supports transaction control and enables the functionality accordingly. ## Benefits of Transaction Control - **Data Integrity:** Group related operations into atomic units that either all succeed or all fail together. - **Safe Testing:** Test changes in a transaction before committing, allowing you to rollback if results aren't as expected. - **Error Recovery:** Easily undo changes if something goes wrong during multi-step operations. - **Consistency:** Ensure related changes are applied together, maintaining referential integrity across tables. - **Development Workflow:** Experiment with data modifications safely, knowing you can always rollback to the previous state. - **Real-Time Feedback:** Track exactly what changes you've made and how many rows were affected before committing. Transaction control in DBCode brings enterprise-grade database transaction management directly into Visual Studio Code, enabling safer and more confident database operations during development and maintenance tasks. --- ## Docs > Query > Universal Sql ### Universal SQL Not every database DBCode connects to has a SQL engine. Document stores speak query documents, key-value stores speak commands, and API-backed services speak REST. Universal SQL lets you use the SQL you already know against these connections anyway: DBCode parses each statement and translates it into the database's own operations. A `WHERE` clause becomes a native filter or an API parameter, `ORDER BY` becomes a native sort, `LIMIT` becomes native paging. DBCode does not fetch everything and filter rows in the editor. The condition is pushed down to the server, so the database does the work and only matching rows come back. ```sql SELECT name, email, status FROM customers WHERE status = 'active' AND createdAt >= '2026-01-01' ORDER BY createdAt DESC LIMIT 20; ``` No SQL text reaches the database; the statement runs as a native query. Each database supports the subset of SQL its engine or API can actually serve, and its own page documents that subset precisely - see [Supported Databases](#supported-databases). Anything outside the subset is rejected before it runs, with the construct named and its line and column reported, rather than approximated. ## The SQL Core Every Universal SQL connection shares one SQL dialect. A database may serve a subset, but everything inside its subset behaves the same way everywhere. ### Statements | Statement | Notes | |---|---| | `SELECT` | Named columns or `*`, from a single table or collection | | `SELECT COUNT(*)` | Server-side count | | `INSERT` | Single row, explicit column list | | `UPDATE ... SET` | With an optional `WHERE` | | `DELETE` | With an optional `WHERE` | ### Filtering with WHERE | Group | Operators | |---|---| | Comparison | `=`, `!=`, `<>`, `>`, `>=`, `<`, `<=` | | Pattern | `LIKE` with `%text%`, `text%`, `%text`, or plain `text` (exact match); `NOT LIKE` with `%text%`; `ILIKE` (case-insensitive) | | Membership | `IN (...)`, `BETWEEN low AND high` | | Null tests | `IS NULL`, `IS NOT NULL` | | Combinators | `AND`, `OR`, parentheses | ```sql SELECT * FROM orders WHERE status IN ('pending', 'paid') AND total BETWEEN 100 AND 500 AND cancelledAt IS NULL; ``` ```sql SELECT * FROM products WHERE name LIKE '%sensor%'; ``` Primary key lookups fetch the named records directly: ```sql SELECT * FROM payments WHERE id IN ('pay_001', 'pay_002'); ``` ### Sorting, Paging, and Counting `ORDER BY`, `LIMIT`, `OFFSET`, and `COUNT(*)` are part of the core, executed by the database: ```sql SELECT COUNT(*) FROM sessions WHERE lastSeen >= '2026-07-01'; ``` ### Dates as Plain Strings Write dates as ordinary string literals. DBCode types the comparison from what it knows about the column, so `'2026-01-01'` compared against a date column behaves as a date, not as text: ```sql SELECT * FROM charges WHERE created BETWEEN '2026-01-01' AND '2026-03-31' LIMIT 100; ``` ### Comments, Identifiers, and Scripts - **Comments**: `--`, `//`, `#`, and `/* ... */` are all recognized - **Quoted identifiers**: wrap a field name in double quotes when it contains spaces or unusual characters, for example `SELECT "unit price" FROM items` - **Multi-statement scripts**: separate statements with semicolons; each statement is translated and executed on its own, and error positions point into the original script ## Writing Data Where the database is writable, `INSERT`, `UPDATE`, and `DELETE` translate to the native write operations: ```sql INSERT INTO users (name, email, status) VALUES ('Ada', 'ada@example.com', 'active'); UPDATE users SET status = 'inactive' WHERE email = 'ada@example.com'; DELETE FROM users WHERE status = 'inactive'; ``` The same safety net that guards SQL connections guards these: an `UPDATE` or `DELETE` without a `WHERE` clause goes through [Missing WHERE Detection](/docs/query/missing-where-detection), so depending on the connection's [role](/docs/connections/roles) it asks for confirmation or is denied outright. Read-only connections reject writes. ## SQL Alongside the Native Language SQL does not replace a database's native language, it sits beside it. Where a connection has its own query language, an editor cell whose first non-comment line starts with `SELECT`, `INSERT`, `UPDATE`, or `DELETE` runs as SQL; anything else runs in the native language, exactly as before. Native queries and SQL can share the same workflow, and each runs the way it was written. ## Supported Databases | Database | Statements | Highlights | |---|---|---| | [MongoDB](/docs/supported-databases/mongodb/mongodb#supported-sql) | `SELECT`, `COUNT(*)`, `INSERT`, `UPDATE`, `DELETE` | Server-side filter, sort, and paging; typed date comparisons; `_id` strings match ObjectIds automatically | | [Stripe](/docs/supported-databases/stripe#supported-sql) | `SELECT` | Date ranges, resource equality filters, direct `id` lookups, and Search API pushdown over the Stripe API | Each link goes to that database's Supported SQL reference, which states exactly which statements and filters it serves. More databases adopt the same engine over time. --- ## Docs > Security ### Security DBCode is **local-first**: it runs inside your editor and connects directly to your databases. Credentials, queries, and results stay on your machine. There is no DBCode server in the query path, so there is no server for your data to leak from. A few optional features (AI, Secure Sharing, History Sync, license activation) do reach our infrastructure, and every one is listed with its exact payload and retention in [Network Egress](/docs/security/network-egress). DBCode holds no SOC 2, and this page says so plainly. What it offers instead is evidence you can check without trusting us: an egress table written to be verified with a proxy, an [SBOM](/docs/security/sbom) your own scanner can read, and a [signed build attestation](/docs/security/build-integrity) you can verify with one command. ## Artifacts for reviewers Assessing DBCode? Start with these. Each artifact says how to check it for yourself. | Artifact | What it answers | How to check it | |---|---|---| | [Network Egress](/docs/security/network-egress) | Every domain DBCode can contact, what triggers it, what it sends, how long it is kept, and how to switch each one off | Run DBCode behind a proxy and compare | | [Build & Release Integrity](/docs/security/build-integrity) | How the package you install is built in public from an exact commit, scanned, and signed | `gh attestation verify` against any release from v1.36.6 onward | | [Software Bill of Materials](/docs/security/sbom) | The full production component list of every release, as CycloneDX | Feed it to Grype, Trivy, or Dependency-Track | | [Subprocessors](#subprocessors) | Who else touches data and what they touch | Reads in one table below | | [security.txt](https://dbcode.io/.well-known/security.txt) | Where to report a vulnerability, and our disclosure policy | RFC 9116, at the well-known path | If your review needs something that isn't here, ask: [security@dbcode.io](mailto:security@dbcode.io). ## Local-First Architecture DBCode runs entirely within VS Code on your local machine. Here's what that means for your data: ### Your Data Stays on Your Computer - **Database connections** are made directly from your computer to your database servers - **Query results** are processed and displayed locally in VS Code - **Connection credentials** are optionally stored on your device with multiple security options, or can be entered each session - **Query history and notebooks** are saved to your local filesystem ### No DBCode Servers in the Middle Unlike cloud-based database tools, DBCode does not route your database traffic through our servers: - We **never see** your database credentials - We **never access** your databases - We **never receive** your query results - We **have no ability** to view your data Your database connections go directly from VS Code on your machine to your database servers. DBCode is simply the interface that runs locally. ## Credential Storage DBCode offers multiple options for storing database credentials, all managed locally on your device: - **VS Code Secret Storage** (default) - Credentials stored in your operating system's secure keychain - **Encrypted Storage** - Credentials encrypted with a passphrase you control - **Session-Only** - Credentials kept in memory, cleared when VS Code closes - **No Storage** - Enter credentials each time you connect See [Password Storage](/docs/security/password-storage) for detailed information on each option. ## Optional Cloud Features DBCode offers two optional features that transmit encrypted data to cloud storage. Both use **zero-knowledge encryption**: data is encrypted on your device before transmission, and we cannot decrypt it. ### Secure Sharing [Secure Sharing](/docs/data/share) lets you share query results with others using end-to-end encryption: - **Encryption happens on your computer** - Data is encrypted using AES-256-GCM before it ever leaves your machine - **Only encrypted data is transmitted** - We receive and store data we cannot decrypt - **You control the passphrase** - The encryption key is derived from a passphrase that never leaves your computer - **Recipients decrypt locally** - Data is decrypted on the recipient's device, not our servers - **Automatic expiration** - Shared data expires and is permanently deleted #### Bring Your Own Storage EU data residency is available by selecting the **European Union** storage region, which keeps your encrypted data in Cloudflare's EU jurisdiction. For full control over location and retention, you can also configure Secure Sharing to use your own S3-compatible storage: - Use your own **AWS S3 bucket** - Use any **S3-compatible storage** (MinIO, Backblaze B2, Cloudflare R2, etc.) - Encrypted data never touches DBCode infrastructure - Full control over data location and retention See [Secure Sharing](/docs/data/share) for complete details. ### History Sync [History Sync](/docs/query/history-sync) lets you sync your query history across devices with end-to-end encryption: - **Client-side encryption** - History is encrypted on your device using AES-256-GCM before upload - **Zero-knowledge storage** - Only encrypted data and an encrypted key envelope are stored; we cannot decrypt them - **Passphrase protected** - Your passphrase never leaves your device and is never stored by us - **Multi-device support** - Sync history across all your devices using the same passphrase See [History Sync](/docs/query/history-sync) for complete details. ## Team Feature Controls On team plans, admins can control which DBCode features each member can use through [Team Roles](/docs/accounts/team-roles). Built-in roles (such as `no-export` and `restricted`) and custom roles can disable: - AI features, either as a whole or individually (completions, analysis, query builder, explore, grid) - History Sync - Data Export, Data Copy, and Data Share Restricted features appear disabled with a "Restricted by your team role" message rather than being hidden. Role definitions are stored in your Stripe subscription metadata, cached locally on each member's machine, and refreshed every 12 hours. Roles are a **policy tool, not a security boundary**. They enforce company guidelines inside the extension, but a determined user could sign out, use a different client, or connect to the database directly. For protecting sensitive data, use database-level access controls (grants, row-level security, network rules) as the primary mechanism. Roles complement those controls, they don't replace them. ## Connection Security Database connections originate from your machine, so whether traffic is encrypted depends on your connection settings and what the target server supports. DBCode gives you the controls: - **Auto SSL** - For recognized cloud hosts (AWS RDS, Azure SQL, Neon, Supabase, Timescale, CockroachDB Cloud, YugabyteDB), DBCode automatically enables SSL and downloads the required public certificates. See [Auto SSL](/docs/connections/auto-ssl). - **Manual SSL/TLS** - Provide your own CA, client certificate, and key for any connection. - **SSH tunnels** - Reach databases that aren't publicly exposed through an encrypted SSH tunnel. See [SSH Tunnels](/docs/connections/ssh-tunnels). Because DBCode runs locally it cannot force a server to accept encryption, but it supports encrypted connections and, for known cloud hosts, enables them by default. ## Subprocessors DBCode's local features use no third parties. The optional cloud features rely on a small set of subprocessors. In every case the data they handle is either encrypted so we cannot read it, or sent only when you explicitly invoke an AI action: | Subprocessor | Purpose | Data handled | |---|---|---| | Cloudflare (Workers, Workers AI) | Hosts the dbcode.io site and runs the hosted AI models | AI request payloads (schema, and on request, query results); not stored, not used for training | | Cloudflare R2 | Stores encrypted blobs for Secure Sharing and History Sync | Ciphertext only (zero-knowledge); we cannot decrypt it | | Stripe | Payments, subscriptions and team seat/role records | Billing details you enter with Stripe; team role assignments held in subscription metadata | | PostHog | Product usage telemetry, proxied through `dbcode.io/ingest` | Anonymous install id, feature-usage events, redacted error reports. Off entirely when VS Code telemetry is disabled | | Google Workspace | Support email to `mike@dbcode.io` | Whatever you choose to send us, including any attachments | | Linear | Issue tracking and triage of support requests | Support requests that arrive by email or from GitHub, and the identity attached to them. This is the subprocessor most likely to hold something sensitive, because it holds whatever you put in a bug report | | GitHub | Public issue tracker and release hosting | Anything you post in a public issue. Note that this channel **is public**: issues on `dbcodeio/public` are visible to anyone | For Secure Sharing you can [bring your own S3-compatible storage](#bring-your-own-storage), in which case encrypted data never touches DBCode infrastructure. See [AI Privacy and Security](/docs/ai/privacy-and-security) for the full AI data-flow breakdown. ## Data Retention and Deletion - **Local data** (connections, query history, notebooks) lives on your filesystem and is removed when you delete it. DBCode keeps no copy. - **Secure Sharing** - You choose a storage region (Americas, the European Union, or Asia-Pacific) and an expiry window per share. The European Union region stores your encrypted data in Cloudflare's EU jurisdiction. Encrypted data is automatically and permanently deleted when it expires. - **History Sync** - Snapshots are created every 7 days. Incremental updates are retained for 1 month and snapshots for 6 months. Stored blobs are client-side encrypted with AES-256-GCM, with server-side encryption at rest as a secondary layer. ## Build and Release Integrity Every release is built by a public GitHub Actions workflow from an exact, tagged commit, scanned with two antivirus engines, attested with Sigstore, and only then published. The source is closed; the process that turns it into the package you install is not. [Build & Release Integrity](/docs/security/build-integrity) walks the pipeline and shows how to verify a release yourself. Every release from v1.36.6 onward is built and attested through it. ## Summary | Feature | Data Location | DBCode Access | |---------|--------------|---------------| | Database connections | Your computer | None | | Query execution | Your computer | None | | Query results | Your computer | None | | Credentials | Your computer (optional) | None | | Notebooks | Your computer | None | | Secure Sharing (optional) | Cloudflare R2 (encrypted) | Encrypted only - cannot decrypt | | History Sync (optional) | Cloudflare R2 (encrypted) | Encrypted only - cannot decrypt | **Bottom line**: DBCode is a local tool. Your databases, credentials, and data stay on your machine. The only features that transmit data are the optional ones listed above: AI features you invoke, Secure Sharing, History Sync, and license activation. Secure Sharing and History Sync encrypt on your device before transmission with zero-knowledge architecture, so we cannot decrypt your data. ## Compliance DBCode does not hold a SOC 2 report. Because DBCode is a local-first editor extension rather than a multi-tenant SaaS, the data such an audit protects never reaches our infrastructure in the first place. What we publish instead is designed to be independently verifiable: [Network Egress](/docs/security/network-egress), the [SBOM](/docs/security/sbom), and [build attestation](/docs/security/build-integrity). If your procurement process requires a completed questionnaire (SIG, CAIQ, or your own), contact [security@dbcode.io](mailto:security@dbcode.io). ## Reporting a Vulnerability If you believe you've found a security vulnerability in DBCode, report it privately to [security@dbcode.io](mailto:security@dbcode.io). Include steps to reproduce, affected versions, and any relevant details. We'll acknowledge your report, investigate, and keep you posted on remediation. Please don't disclose the issue publicly until we've had a chance to address it. --- ## Docs > Security > Build Integrity ### Build and Release Integrity DBCode's source is closed. The process that turns it into the package you install is not: every release is built by a public GitHub Actions workflow you can read and watch run. This page walks the pipeline and shows how to verify a release yourself. Every release from v1.36.6 onward is built and attested through this pipeline; earlier releases were built by the previous, private release process. ## The pipeline, in public Releases are built by [`build-and-publish.yml`](https://github.com/dbcodeio/public/blob/main/.github/workflows/build-and-publish.yml) in the public repository, and every run is visible in the [Actions history](https://github.com/dbcodeio/public/actions/workflows/build-and-publish.yml) with full logs. The workflow: 1. **Checks out the private source at an exact commit** with a read-only deploy key, then verifies that commit matches the release tag and the version in `package.json`. A dispatch that does not match the tag fails the run. 2. **Stamps provenance into the package.** The source repository, source commit, version, and a link to the workflow run are written into `build-provenance.json` inside the package, so the artifact records what produced it. 3. **Builds and packages from a committed lockfile.** Nothing resolves at release time. 4. **Scans the package with two antivirus engines before anything ships**: ClamAV with heuristics and PUA detection, and Windows Defender configured with cloud-delivered protection, sample submission, and PUA blocking. Any detection blocks the release for investigation. There is no allowlist step. 5. **Attests the package with Sigstore**, via GitHub [artifact attestations](https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations). This runs only after both scans pass, so only clean artifacts are signed. Sigstore log entries are public and permanent. 6. **Publishes the same bytes everywhere**: the [GitHub release](https://github.com/dbcodeio/public/releases) (with the [SBOM](/docs/security/sbom) attached), the VS Code Marketplace, and Open VSX. ## Verify a release yourself You need the [GitHub CLI](https://cli.github.com/). Download any release's `.vsix` and run: ```sh gh attestation verify dbcode-.vsix --repo dbcodeio/public ``` Verification succeeds for every release from v1.36.6 onward and reports the workflow that built the file: `dbcodeio/public/.github/workflows/build-and-publish.yml`. Run it against an older release and it fails, because GitHub has no attestation on record for a file the previous, private process built. That failure is expected, not an incident. The verification proves the exact file you hold was produced by this repository's workflow, at a recorded commit, on GitHub's runners, and has not been altered since. If verification fails for a release that should carry an attestation, treat it as an incident and tell us: [security@dbcode.io](mailto:security@dbcode.io). ## Static analysis DBCode's extension source is closed, so you cannot watch these runs the way you can watch the build pipeline above. Static analysis still runs on every change: CodeQL, configured through GitHub's advanced setup (a workflow we own, not GitHub's default), scans the `actions`, `javascript-typescript`, and `python` languages present in the private source repository, using the standard CodeQL query suite. Nothing is excluded from the scan. Every pull request into main is analysed, and CodeQL is a required check in the branch ruleset, so no code reaches main unanalysed. (A docs-only change can legitimately have nothing for CodeQL to analyse, but the required check still has to report before the pull request can merge.) A scheduled run repeats the analysis daily, which keeps the baseline and the repository's official alert state current even on days with no pull requests. The scanning action itself is pinned to a commit SHA and kept current by Dependabot. ## Supply chain hygiene - Dependencies are pinned by a committed lockfile and installed with `--frozen-lockfile` everywhere, including the release build. - New dependency versions must age for 7 days before they can be installed, which blunts compromised-package releases. - Every GitHub Actions step is pinned to a full commit SHA, not a mutable tag. - Secret scanning (gitleaks) runs on every pull request across the full history, with a pre-commit hook scanning staged content locally. - A weekly scheduled scan checks the full dependency tree against the OSV vulnerability database, which catches CVEs disclosed against dependencies nobody has touched recently. Exceptions are tracked with expiry dates instead of being silenced permanently. ## What this does and does not prove Attestation proves where the bytes came from and that they were not modified. It does not prove the source is defect-free, and closed source means you cannot read it. The rest of the security story is built for that gap: the [egress table](/docs/security/network-egress) tells you what the extension can do on the wire and how to check it, and the [SBOM](/docs/security/sbom) tells you what is inside. --- ## Docs > Security > Caiq ### Security Self-Assessment (CAIQ-Lite) DBCode is a commercial VS Code extension operated by a single-person company. This page is a self-assessment against the Cloud Security Alliance's [Cloud Controls Matrix](https://cloudsecurityalliance.org/research/cloud-controls-matrix) v4, organised by its seventeen domains, so a reviewer can map our answers onto whichever framework they use. **This is a self-assessment, not an audit.** DBCode has no SOC 2 or ISO 27001. Where a control isn't in place, we say so. Where it comes from Cloudflare, we say that, and you should read their [STAR entry](https://cloudsecurityalliance.org/star/registry) too. The completed CSA workbook is available on request from [security@dbcode.io](mailto:security@dbcode.io). ## Architecture, in one paragraph DBCode runs on your machine, inside your editor, and connects directly to your databases. Credentials live in VS Code Secret Storage. There is no DBCode server in the path of a query. Four optional features do reach our infrastructure: AI, Secure Sharing, History Sync, and licence activation. Each is enumerated with payloads and retention in [Network Egress](/docs/security/network-egress). Our infrastructure is Cloudflare Workers, Workers AI and R2; our only other subprocessors are Stripe and PostHog, listed with the data they handle in [Subprocessors](/docs/security#subprocessors). ## Assessment by domain | Domain | Position | |---|---| | **Audit & Assurance** | No third-party audit. No SOC 2, ISO 27001 or CSA STAR Level 2. This self-assessment, the [SBOM](/docs/security/sbom) and the [egress table](/docs/security/network-egress) are offered as verifiable substitutes: the egress table in particular is designed for you to test with a proxy. | | **Application & Interface Security** | Client-side encryption for everything we store (AES-256-GCM, key derived on device via scrypt). Every release is scanned with ClamAV and Windows Defender before publishing and a detection blocks the release. The MCP server binds to loopback and defaults to OAuth authorisation. Secret scanning runs on every pull request: gitleaks scans the full commit history, with a pre-commit hook scanning staged content locally. **No SAST is configured** - a known gap. | | **Business Continuity & Operational Resilience** | Site and API run on Cloudflare's global network. Customer data we hold is limited to encrypted blobs in R2 and account records. **NEEDS CONFIRMATION: backup and restore testing cadence, and any RPO/RTO you are willing to state.** | | **Change Control & Configuration Management** | All changes land through pull requests with automated checks. The `main` branch is protected by a ruleset whose only bypass actor is a deploy key held by CI, so no laptop and no personal token can push to it. All 36 GitHub Actions references are pinned to full commit SHAs. | | **Cryptography, Encryption & Key Management** | Secure Sharing and History Sync are zero-knowledge: data is encrypted on your device with AES-256-GCM under a key wrapped by a passphrase-derived KEK (scrypt). The passphrase never leaves your device and is never stored by us. We cannot decrypt your blobs. Database credentials are held in VS Code Secret Storage, which uses the OS keychain. See [Password Storage](/docs/security/password-storage). | | **Datacenter Security** | Inherited entirely from Cloudflare. DBCode operates no datacentres and owns no server hardware. | | **Data Security & Privacy Lifecycle** | Retention is documented per feature: Secure Sharing expires on the window you choose, History Sync keeps incrementals 1 month and snapshots 6 months, AI requests are processed and discarded. No customer data is used to train models. Local data never leaves your filesystem unless you invoke one of the four features above. | | **Governance, Risk & Compliance** | Single-person company, so governance is direct rather than committee-based. Security documentation is public and versioned in git. **NEEDS CONFIRMATION: whether you perform and record a periodic risk assessment, and any policy documents you are willing to share.** | | **Human Resources** | One person. No employees, so no onboarding, offboarding or role-separation controls apply. **NEEDS CONFIRMATION: whether any contractor has access to production or customer data, and whether background screening applies.** | | **Identity & Access Management** | Sign-in uses your existing identity provider through VS Code's authentication or the web flow (Microsoft, Google, GitHub, email). Team role assignments are stored in Stripe subscription metadata and refreshed every 12 hours. The MCP HTTP server is OAuth-gated by default; see the warning about `None` in [AI privacy](/docs/ai/privacy-and-security). **NEEDS CONFIRMATION: MFA enforcement on your own admin accounts (GitHub, Cloudflare, Stripe).** | | **Interoperability & Portability** | No lock-in by design. Connections, history and notebooks are local files. Results export to standard formats. Secure Sharing can use [your own S3-compatible storage](/docs/security#bring-your-own-storage). Air-gapped use is supported via [offline licence activation](/docs/accounts/offline-license). | | **Infrastructure & Virtualization Security** | Inherited from Cloudflare Workers, which is an isolate-based runtime with no long-lived compute we administer. DBCode operates no VMs, containers or networks in production. | | **Logging & Monitoring** | Product telemetry goes through VS Code's telemetry logger, so setting `telemetry.telemetryLevel` to `off` silences it at the source. Telemetry is anonymous install id, feature-usage events and redacted errors: never query text, connection details or data. **NEEDS CONFIRMATION: retention period for API and access logs on the Cloudflare side.** | | **Security Incident Management** | Vulnerabilities are reported to [security@dbcode.io](mailto:security@dbcode.io) via a published [security.txt](https://dbcode.io/.well-known/security.txt) and the [disclosure policy](/docs/security#reporting-a-vulnerability). **NEEDS CONFIRMATION: your customer breach-notification commitment (a stated window, for example 72 hours, is what reviewers look for) and whether an incident response runbook exists.** | | **Supply Chain Management, Transparency & Accountability** | A [CycloneDX SBOM](/docs/security/sbom) ships with every release. Licences are checked in CI against a deny list. Subprocessors are [listed publicly](/docs/security#subprocessors) with a commitment to announce additions 30 days before they handle customer data. Both the extension and the website hold new dependency versions for 7 days before they can be installed. | | **Threat & Vulnerability Management** | Dependency updates, licence checks and secret scanning (gitleaks, pinned by version and verified by checksum) run in CI; AV gates run on every release artefact. **NEEDS CONFIRMATION: whether any external penetration test has been performed, and how dependency CVEs are triaged and within what target window.** | | **Universal Endpoint Management** | Not applicable in the usual sense: DBCode runs on endpoints you manage, under your policies. DBCode settings can be pinned via machine-scoped VS Code settings, which is how you would enforce, for example, OAuth-only MCP. | ## Known gaps, stated plainly 1. No third-party security audit or certification. 2. No SAST in CI. Secret scanning is in place; static analysis for code defects is not. 4. [`dbcode.disableOnlineServices`](/docs/security/network-egress#disable-dbcode-online-services) blocks DBCode-hosted services and automatic dependency downloads, but it is not complete network isolation. Database and SaaS connections, authentication, cloud-provider APIs, required assets, map tiles, user-configured providers, and user-authored SQL or URLs remain available. 5. Single-person operation means no separation of duties, and bus-factor risk you should weigh. Offline licence activation exists partly to mitigate it: an air-gapped install keeps working without us. Missing a control you need? Tell us: [security@dbcode.io](mailto:security@dbcode.io). --- ## Docs > Security > Network Egress ### Network Egress Every network destination DBCode can reach, in one table. **Don't trust this page, check it.** Run DBCode behind a proxy (mitmproxy, Charles, Burp, or your corporate TLS gateway) and compare. If you see a host that isn't listed, or one that fires without the trigger described here, that's a bug: [security@dbcode.io](mailto:security@dbcode.io). ## DBCode's own endpoints These are the only hosts DBCode contacts that belong to us. | Domain | Trigger | Payload | Retention | |---|---|---|---| | `dbcode.io` | Sign in, license activation and the periodic license refresh | Account identifier and machine key. No database content | Account and license records kept while your account exists | | `dbcode.io` | An AI feature you invoke (see [AI privacy](/docs/ai/privacy-and-security)) | Database schema, your prompt, and for AI Data Grid and AI Data Explore the query results in view | Not stored. Processed and discarded | | `dbcode.io` | Secure Sharing, when you share a result | Ciphertext only, encrypted on your machine. We cannot decrypt it | Deleted at the expiry you choose | | `dbcode.io` | History Sync, when enabled | Ciphertext only, client-side encrypted | Incrementals 1 month, snapshots 6 months | | `dbcode.io/ingest` | Product telemetry, [disabled by policy or VS Code telemetry settings](#disable-dbcode-online-services) | Anonymous install id, feature-usage events, redacted error reports. Never query text, connection details or data | Aggregated usage retained; no per-user profile | Requests to `dbcode.io` terminate on Cloudflare Workers. AI requests continue to Cloudflare Workers AI on Cloudflare's own infrastructure. Nothing else sits in that path, and no gateway can reroute a request to another model provider. See [Subprocessors](/docs/security#subprocessors). ## Driver and tool downloads Some engines need a driver, native binary or CLI that we can't bundle, either because we're not licensed to redistribute it or because it's platform-specific. DBCode downloads it the first time you use that engine and caches it. **No information about your database is sent. These are plain file downloads.** | Using this | Downloads | From | |---|---|---| | SQLite | SQLite binary, `better_sqlite3.node`, and the extensions you enable (`sqlite-vec`, `sqlite-js`, `sqlean`, `mod_spatialite`, `sqlite-regex`) | `github.com/dbcodeio/public` | | DuckDB | DuckDB binary | `github.com`, `registry.npmjs.org` | | DuckDB engine extensions | Core or community extensions configured or required by a DuckDB-based connection. Automatic installs are blocked when `dbcode.disableOnlineServices` is enabled | `extensions.duckdb.org`, `community-extensions.duckdb.org` | | libSQL | libSQL binary | `registry.npmjs.org` | | LanceDB | LanceDB binary | `registry.npmjs.org` | | Db2 | IBM Db2 node binary and ODBC CLI | `github.com/ibmdb` | | Teradata | `teradatasql`, `koffi` | `registry.npmjs.org` | | Dameng | `dmdb`, `iconv-lite`, `safer-buffer` | `registry.npmjs.org` | | SAP HANA | SAP HANA client | `registry.npmjs.org` | | Any JDBC engine | Java bridge native binding | `registry.npmjs.org` | | Access (JDBC) | UCanAccess, Jackcess, HSQLDB | `repo1.maven.org` | | Derby (JDBC) | Derby engine, shared and client jars | `repo1.maven.org` | | H2 (JDBC) | H2 jar | `repo1.maven.org` | | IBM i (JDBC) | JT400 jar | `repo1.maven.org` | | SAP ASE (JDBC) | jTDS jar | `repo1.maven.org` | | Aerospike (JDBC) | Aerospike JDBC jar | `github.com/aerospike` | | Kerberos authentication | Kerberos native binding | `github.com/mongodb-js` | | MongoDB import, export, backup, restore | MongoDB Database Tools | `fastdl.mongodb.org` | | SQL Server import or export | SqlPackage | `download.microsoft.com` | | PostgreSQL backup, restore or import | PG Tools (`pg_dump`, `pg_restore`, `psql`) | `get.enterprisedb.com` | | Native drivers on Windows | Visual C++ redistributable | `aka.ms` | On Linux, PG Tools aren't downloaded. DBCode uses the `pg_dump`, `pg_restore` and `psql` already on your `PATH`, so install them with your package manager. Block these hosts and the feature is unavailable rather than silently degraded. Pre-install the tool and DBCode uses your copy. ## Webview assets Two DBCode views load assets from a CDN rather than from the extension bundle. This is browser-style egress from the webview, so it appears in a proxy log differently from the rest of this page. | Domain | Trigger | Payload | |---|---|---| | `cdn.jsdelivr.net` | Opening the **map viewer** (geospatial column preview) | Loads MapLibre GL and Turf.js. No data sent | | `tiles.openfreemap.org` | Opening the **map viewer** | Map tile requests. These contain the map area being viewed, which is derived from your geospatial data | | `*.vscode-cdn.net` | Any webview | VS Code's own fonts and icons, requested by VS Code rather than by DBCode | | `*.r2.cloudflarestorage.com` | Opening a Secure Share, or History Sync | Fetches your encrypted blob directly from storage. Ciphertext only | Map tiles are the one case where an outside host can infer something about your data: the tiles requested match the coordinates you're looking at. Avoid the map view for sensitive geospatial data. ## Destinations you configure Everything else DBCode can reach is somewhere **you** pointed it. We list it here because it will appear in your proxy logs, and a reviewer should know why. | Category | Domains | Trigger | |---|---|---| | Your databases | Whatever host you enter | Connecting, querying | | Cloud provider import | `api.cloudflare.com`, `console.neon.tech`, `api.supabase.com`, `api.turso.io`, `api.aiven.io`, `api.digitalocean.com`, `management.azure.com` | Only when you link that provider to list your databases | | SaaS data sources | `api.stripe.com`, `us.posthog.com` or `eu.posthog.com`, `firestore.googleapis.com` | Only when you add one of these as a **connection**. Stripe and PostHog are supported data sources; this traffic is you querying your own account, not DBCode reporting to them | | Authentication | `login.microsoftonline.com`, `graph.microsoft.com`, and the identity provider in your [authentication profile](/docs/authentication-profiles) | Signing in to a database with OAuth or Entra ID | | Custom AI provider | Whatever endpoint you set in `dbcode.ai.customModel.endpoint` | An AI feature, when a custom provider is configured | ## Disable DBCode online services Enable **DBCode: Disable Online Services** in the Settings UI under DBCode's Security settings, or add this to `settings.json`: ```json { "dbcode.disableOnlineServices": true } ``` This machine-scoped setting defaults to `false`. When it is `true`, DBCode gates newly started DBCode-hosted online work and automatic dependency downloads. It does not cancel an operation that is already in progress. Changing the setting applies at the next operation entry. With Remote SSH or a Dev Container, set it in the **Remote** or **Dev Container** settings where the DBCode extension runs. A value set only on your local VS Code machine does not configure the remote extension host. | Area | Blocked when the setting is `true` | Still allowed | |---|---|---| | DBCode API, account and licensing | DBCode API requests, sign-in and account actions, team-permission refresh, and online license activation or refresh | An already installed local or manual license, including an offline license | | AI | DBCode-hosted AI and DBCode-hosted vector embeddings | Custom AI endpoints and VS Code or GitHub Copilot models that you configured | | Sharing and history | Starting Secure Sharing and newly started History Sync online work, including background sync and snapshots | Local query history and other local history work | | Telemetry | DBCode product telemetry events | PostHog and other SaaS endpoints when you explicitly configure them as database connections | | Drivers, tools and extensions | Automatic driver, CLI, native dependency and DuckDB engine extension downloads | Cached packages, tools found on the system, manual package files and already installed DuckDB extensions | | Connections and authentication | Nothing in this category | Database and SaaS connections, their authentication traffic, and cloud-provider APIs | | Assets and maps | Nothing in this category | Icons, CSS and other required webview assets, map assets and tile maps | | MCP | Nothing in the local or inbound MCP path | The MCP server and local database tools. A tool that starts a blocked DBCode-hosted feature still meets that feature's gate | | User-authored requests | Nothing in this category | Arbitrary SQL and URLs that you enter, including SQL that installs an extension or reads a remote URL | DBCode handles blocked entries according to how they started: - Telemetry is dropped quietly. DBCode does not create a log entry for every suppressed event. - Background work is skipped and logged once per blocked feature or package for the current extension session. - Interactive DBCode-hosted features show a warning with **Enable Online Services** and **Learn More**. If you select **Enable Online Services**, the requested action continues. **Learn More** opens this section. A setting managed by your administrator cannot be changed from the warning, so the action remains blocked. - When an automatic package or DuckDB extension download is required, DBCode also offers **Select File Manually**. Cancelling the picker leaves the feature unavailable instead of silently continuing without its dependency. For licensing, install an [offline license](/docs/accounts/offline-license) before or after enabling this setting. The installed license is used locally; DBCode does not need an online license refresh while the policy is active. This is a DBCode application policy, not an operating-system firewall. It does not intercept traffic created by database drivers, VS Code, webviews, custom providers or SQL and URLs that you enter. Use host firewall, proxy or network policy controls as well when you need complete egress isolation. ### Feature-specific controls You can still use the narrower controls when you do not need to disable all DBCode-hosted online services: | To stop | Do this | |---|---| | Telemetry | Set VS Code's `telemetry.telemetryLevel` to `off`. DBCode uses VS Code's telemetry logger, so this silences it at the source | | Inline completion | `dbcode.ai.inlineCompletion: false` | | All hosted AI | Set `dbcode.ai.customModel.endpoint` to your own or a local model and `dbcode.ai.customModel.only: true`, which stops any fallback to our hosted model | | Secure Sharing to our storage | [Bring your own S3-compatible storage](/docs/security#bring-your-own-storage), or do not share | | History Sync | Leave it disabled; it is opt-in | | Sign-in traffic | Use [offline license activation](/docs/accounts/offline-license) | ## MCP server The [MCP server](/docs/ai/mcp) listens on localhost and makes no outbound connections of its own. It is an inbound surface, not an egress one, and it is covered separately in [AI privacy and security](/docs/ai/privacy-and-security). --- ## Docs > Security > Password Storage ### Password Storage DBCode provides multiple password storage options to suit diverse security and usability needs. From session-only storage to encrypted synchronization, these options ensure flexibility without compromising security. When configuring a database connection or tunnel in DBCode, you can choose from the following options when storing sensitive information such as passwords: ![Password storage options](./password-storage-settings.png) ### Save Password in VSCode Secret Storage (Default) The password is stored securely using VSCode's built-in secret storage. **Benifits:** - Passwords are not included in the settings.json file, ensuring they are not synced with other connection details. - This is the **default and most secure option** for local password storage. ### Encrypt and Save Password The password is encrypted with a user-provided encryption string and the encrypted value is stored saved in the settings.json file. The encrypted will be synced across devices. **How It Works:** - You'll be prompted to set an encryption string during setup, which is not stored, and should be kept confidential. - The password is encrypted using the string before being saved with the connection information. - When the password is needed for a connection, the encrypted value is retrieved and you will be prompted to enter the original encryption string used to encrypt it. ### Save Password for Session The password is stored temporarily in memory and remains valid only for the current DBCode session. Upon restarting DBCode, the password must be re-entered. ### Don't Save Password The password is not saved and must be entered manually each time you connect. ### Save Password in Plain Text (Not Recommended) The password is stored in plain text within the settings.json file. If VSCode settings sync is enabled, this file, including the password, will be synced across devices in plain text - **Recommendation:** Avoid using this option due to security risks of storing passwords in plain text. Instead use the encrypt and save option is syncing passwords is desired. --- ## Docs > Security > Sbom ### Software Bill of Materials DBCode publishes a [CycloneDX](https://cyclonedx.org/) SBOM with every release, so you can run our component list against your own vulnerability feeds instead of taking our word that we patch things. ## Where to get it | What you want | URL | |---|---| | The current release | [`github.com/dbcodeio/public/releases/latest/download/sbom.cdx.json`](https://github.com/dbcodeio/public/releases/latest/download/sbom.cdx.json) | | A specific version | `github.com/dbcodeio/public/releases/download/v{version}/sbom.cdx.json` | | Browsable in the repo | [`github.com/dbcodeio/public/blob/main/sbom.cdx.json`](https://github.com/dbcodeio/public/blob/main/sbom.cdx.json) | It is CycloneDX 1.6 JSON, which Dependency-Track, Grype, Trivy and most commercial scanners read directly. ## What it covers The **production dependency closure** of the extension: currently about 1,340 packages, each with a name, exact version, [purl](https://github.com/package-url/purl-spec) and resolved licence. It is derived from `pnpm-lock.yaml`, so it matches the dependency graph we actually build from. **Every platform we ship to, not just the one that built it.** DBCode ships a single extension to macOS, Linux and Windows, and a handful of native dependencies differ per platform. The SBOM lists all of them, so what you scan covers what you could actually run, whichever machine you are on. Platform specific components are marked `scope: optional` and carry `dbcode:os`, `dbcode:cpu` and `dbcode:libc` properties saying which platform each one is for. It is the closure, not the contents of the bundle. We build with esbuild and package with `vsce package --no-dependencies`, so what ships is a tree-shaken subset of this list. Reporting the closure is standard practice and errs toward telling you about more than you receive, never less. ## What it does not cover, and why **Build and test tooling.** The closure is walked from the extension's production dependencies only, so the several hundred packages that exist purely to build and test DBCode never appear. You do not receive them, so they are not yours to scan. **Drivers fetched at first use.** A few engines need a driver or CLI we are not licensed to redistribute, so DBCode downloads it the first time you use that engine. These are not dependencies of the package and cannot appear in a dependency SBOM, so they are recorded in the SBOM's metadata properties and listed here: | Component | Source | Trigger | |---|---|---| | `teradatasql` | `registry.npmjs.org` | First Teradata connection | | `dmdb` | `registry.npmjs.org` | First Dameng connection | | `jtds` | `repo1.maven.org` | First JDBC (SAP ASE) connection | | `mongodb-database-tools` | `fastdl.mongodb.org` | First MongoDB import, export, backup or restore | See [Network Egress](/docs/security/network-egress) for how to block or pre-install these. ## How it is produced Generated in CI from `pnpm-lock.yaml`, committed to the repository in the same pull request as any dependency change, then copied to the public repository and attached to the release. The document carries no timestamp and its serial number is derived from the component set, so an unchanged dependency tree produces a byte-identical file no matter which machine generated it. Diffing two releases shows real changes only. The rest of the release pipeline (public build, AV gates, Sigstore attestation) is on [Build & Release Integrity](/docs/security/build-integrity). Spotted a production dependency that isn't listed? That's a bug: [security@dbcode.io](mailto:security@dbcode.io). --- ## Docs > Sql ### SQL Reference A comprehensive reference for SQL commands and syntax. Find detailed documentation on SQL statements, functions, and clauses to help you write effective database queries. Browse the sidebar to find specific SQL commands, or use the search to find what you need. --- ### OPENXML ' SELECT * FROM OPENXML (@idoc, '/Books/Book',2) WITH (Title varchar(50) 'Title', Author varchar(50) 'Author'); ``` #### Output ``` +-------+--------+ | Title | Author | +-------+--------+ | Book1 | Author1| | Book2 | Author2| +-------+--------+ ``` #### Explanation The example code first declares and sets an example XML variable containing information about books. It then uses OPENXML to provide rowset view over the XML document. The SELECT statement extracts the 'Title' and 'Author' for each 'Book' and shows them as a table. The output demonstrates the tabular representation of the extracted data. --- ### OPTIMIZER_COSTS SELECT... | +-----------+------+----------------------------------------------------+ ``` #### Explanation In the given SQL code, the `optimizer_trace` variable is initially set to `"enabled=on"`. After this point, any query run on the server will generate the optimizer cost detail. Once we run the `SELECT * FROM my_table;` statement, we can get the optimizer trace details with `SHOW WARNINGS;` as the trace details are treated as warnings. Turning off the feature by `SET optimizer_trace="enabled=off"` ensures that no further statements will generate these details. The output returns a warning message including the optimizer costs along with execution plan generated by the optimizer for the select query. --- ## Docs > Supported Databases ### Supported Databases in VS Code export const databases = (await getCollection('docs', (page) => { return page.id.startsWith('docs/supported-databases/') && page.data.logo; })).sort((a, b) => (a.data.sidebar?.label ?? a.data.title).localeCompare(b.data.sidebar?.label ?? b.data.title)); DBCode connects to **{databases.length}+** databases out of the box. Pick yours below to see setup details. --- ## Docs > Supported Databases > Access ### Microsoft Access Database Management in VS Code ## Connecting To connect to Microsoft Access, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Microsoft Access as the type, and select the `.accdb` or `.mdb` file. 4. **Connect**: Click save to connect to your Access database. 5. **Start Managing Your Databases**: Once connected, you can start managing your tables and queries directly from Visual Studio Code. For detailed instructions on connecting to Microsoft Access, refer to the [Connect](/docs/get-started/connect) article. ## Supported File Formats - **.accdb** - Access 2007 and later (recommended) - **.mdb** - Access 2000-2003 (legacy format) ## Features DBCode uses the UCanAccess JDBC driver to provide cross-platform Access database support. This means you can work with Access databases on macOS, Linux, and Windows without requiring Microsoft Access to be installed. ### Supported Objects - **Tables** - Full read/write support with data editing in the grid - **Queries** - Access Queries are displayed (read-only creation/modification) - **Columns** - Complete column metadata including data types and nullability - **Primary Keys** - Detection and display of primary key constraints - **Indexes** - View table indexes - **Foreign Keys** - Foreign key relationship detection and display ### Capabilities - Browse and query tables and views - Edit data directly in the grid - Export data to CSV, JSON, Excel, and other formats - View table relationships in the ERD (Entity Relationship Diagram) - Execute SQL queries - Read-only mode for safe browsing ## More Information By using Microsoft Access with DBCode, you can connect to your Access databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Microsoft Access, check out Microsoft Access. --- ## Docs > Supported Databases > Aerospike ### Aerospike Database Management in VS Code ## Overview Aerospike is a distributed NoSQL database designed for applications that need high throughput, low latency, and high availability at scale. Key characteristics include: - **Key-value and document storage**: Data is organized into namespaces (databases), sets (tables), and bins (columns) - **Sub-millisecond latency**: Optimized for flash/SSD storage with predictable performance - **SQL support**: Query data using SQL syntax through the JDBC driver - **Secondary indexes**: Create indexes on bins for filtered queries - **Horizontal scaling**: Automatic data distribution and rebalancing across cluster nodes - **Schema flexibility**: Bins are dynamic per record, no predefined schema required Aerospike is used in ad tech, financial services, gaming, telecommunications, and other industries requiring real-time data processing at scale. ## Connecting To connect to Aerospike in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Aerospike as the database type and enter: - Host/Server address - Port (default: 3000) - Namespace (the Aerospike namespace to connect to) - Username and password, or a Command authentication profile (if authentication is enabled) 4. **Connect**: Click save to connect to your Aerospike cluster. 5. **Start Managing Your Data**: Browse sets and run SQL queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## Aerospike Features in DBCode DBCode enhances your Aerospike development experience with: - **SQL query editor**: Write and execute SQL queries (SELECT, INSERT, UPDATE, DELETE) with syntax highlighting - **Set browsing**: Navigate through sets (tables) and their bin (column) structure - **Data grid**: View, sort, and filter records with full data grid support - **Secondary index management**: View and create secondary indexes via SQL - **Data export**: Export query results in multiple formats - **Namespace discovery**: The connection form fetches available namespaces from the cluster ### SQL Support The Aerospike JDBC driver translates SQL into native Aerospike operations: - `SELECT ... FROM set_name [WHERE ...] [LIMIT ...]` - `INSERT INTO set_name (__key, bin1, bin2) VALUES ('key', val1, val2)` - `UPDATE set_name SET bin1 = val1 WHERE __key = 'key'` - `DELETE FROM set_name WHERE __key = 'key'` - `TRUNCATE TABLE set_name` - `CREATE INDEX idx_name ON set_name (bin_name)` - `DROP INDEX idx_name ON set_name` The `__key` column is the record's primary key. Use it in INSERT statements to set the key, and in WHERE clauses for lookups. Note: JOIN, GROUP BY, and subqueries are not supported by the Aerospike JDBC driver. By using Aerospike with DBCode, you can efficiently browse your data, develop SQL queries, and manage records directly within Visual Studio Code. For more information about Aerospike, check out Aerospike. --- ## Docs > Supported Databases > Athena ### Amazon Athena in VS Code ## Overview Amazon Athena is a serverless, interactive query service that lets you analyze data stored in Amazon S3 using standard SQL. Key benefits include: - **No infrastructure to manage**: Athena automatically scales to match query demand - **Pay-per-query**: You only pay for the data scanned by each request - **Federated access**: Query data across S3, Glue Data Catalog, and supported connectors - **Integrated with AWS services**: Natively works with AWS Identity and Access Management (IAM), Glue, Lake Formation, and CloudTrail - **Fast schema-on-read analytics**: Start querying data almost immediately after it lands in S3 Athena is ideal for ad-hoc analysis, data exploration, and building lightweight analytics on top of data lakes without provisioning dedicated clusters. ## Connecting To connect Athena in DBCode: 1. **Open the DBCode extension** in Visual Studio Code and select `Add Connection`. 2. **Choose Amazon Athena** from the database type list. 3. **Configure credentials** using either an AWS access key pair or default credentials chain. Make sure the IAM principal has permissions for Athena and the target S3 buckets. 4. **Choose the AWS region and output S3 location** if you need to override the values defined by your Athena workgroup defaults (optional). 5. **Save the connection** to load the schema tree and start running queries against your S3 datasets. ## DBCode Features for Athena With an Athena connection, DBCode provides: - **Schema Browser**: Explore Glue Data Catalog databases, tables, and partitions - **SQL Editor**: Write, run, and save SQL queries with Athena-specific syntax highlighting - **Results Grid**: Inspect query results with JSON export and quick copy support - **Query History**: Track previous statements, rerun them, and compare execution times - **Saved Connections**: Share environment variables and connection templates with your team Because Athena is read-only, data editing features are disabled. To modify source data, update the files in Amazon S3 and refresh the catalog. Learn more about Athena at aws.amazon.com/athena. --- ## Docs > Supported Databases > Avro ### Avro File Viewer in VS Code ## Overview DBCode lets you open and work with Apache Avro files directly in VS Code. Browse data with sorting and filtering, and run SQL queries against your Avro files using DuckDB under the hood. ## Features - Open any `.avro` file in the data grid - Sort, filter, and group data - Run SQL queries against Avro data - View schema information - Export to other formats (CSV, Excel, Parquet, JSON) --- ## Docs > Supported Databases > Azure ### Azure SQL Database Management in VS Code ## Overview Azure SQL is a cloud-based relational database management system (RDBMS) that provides a range of features and capabilities to help you build and run your applications. With Azure SQL, you can easily scale your database resources up or down as your needs change, and you can also easily manage and monitor your database performance. ## Supported Authentiction Methods DBCode supports the following authentication methods for Azure SQL: - SQL Based Username and password - Microsoft Entra ID - Windows Integrated Authentication ## Connect Single Database To connect to a single Azure SQL database, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Azure SQL as the type, and enter the required information. 4. **Connect**: Click save to connect to your Azure SQL database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to Azure SQL, refer to the [Connect](/docs/get-started/connect) article. ## Connect Multiple Databases To connect to Azure SQL as a cloud provider and access multiple databases, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Your Provider**: Choose the Azure cloud provider from the list on the right. 4. **Authenticate**: Follow the authentication process specific to the provider. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to Azure SQL, refer to the [Connect a Cloud Provider](/docs/cloud-providers/connect) article. By using Azure SQL with DBCode, you can connect to your Azure SQL databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Azure SQL, check out Azure SQL. --- ## Docs > Supported Databases > Azuresynapse ### Azure Synapse Analytics in VS Code ## Connecting To connect to Azure Synapse, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Azure Synapse as the type, and enter the required information including server, database, and authentication details. 4. **Connect**: Click save to connect to your Synapse workspace. 5. **Start Managing Your Data**: Once connected, you can start querying your data warehouse directly from Visual Studio Code. For detailed instructions on connecting to Azure Synapse, refer to the [Connect](/docs/get-started/connect) article. By using Azure Synapse with DBCode, you can connect to your Synapse workspaces, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Azure Synapse, check out Azure Synapse Analytics. --- ## Docs > Supported Databases > Bigquery ### BigQuery Database Management in VS Code DBCode is a BigQuery extension for VS Code: connect to your Google Cloud project, browse datasets and tables, run SQL, and chart results without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Connecting To connect to BigQuery, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose BigQuery as the type, and enter the required information. 4. **Connect**: Click save to connect to your BigQuery database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to BigQuery, refer to the [Connect](/docs/get-started/connect) article. By using BigQuery with DBCode, you can connect to your BigQuery databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about BigQuery, check out BigQuery. --- ## Docs > Supported Databases > Bunny ### Bunny Database Management in VS Code ## Overview Bunny Database is Bunny.net's cloud-hosted edge database service built on libSQL (the open-source fork of SQLite). Key characteristics include: - **Edge-optimized**: Runs on Bunny.net's global CDN infrastructure for low-latency access worldwide - **SQLite compatible**: Full SQLite SQL dialect support with familiar query syntax - **Simple connectivity**: URL-based connections with token authentication - **Managed infrastructure**: No database servers to provision or maintain - **libSQL foundation**: Benefits from libSQL enhancements over standard SQLite Bunny Database is ideal for edge applications, content-driven websites, and projects that need a lightweight, globally distributed relational database. ## Connecting To connect to Bunny Database in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Bunny Database as the database type and enter: - Database URL (e.g., `libsql://your-database-id.lite.bunnydb.net`) - Auth Token from your Bunny.net dashboard 4. **Connect**: Click save to connect to your Bunny Database. 5. **Start Managing Your Data**: Browse tables, run queries, and manage your schema. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## Bunny Database Features in DBCode DBCode enhances your Bunny Database experience with: - **Schema browsing**: Navigate tables, views, indexes, and triggers - **SQL query editor**: Write and execute SQLite-compatible queries with syntax highlighting - **Data editing**: Insert, update, and delete rows directly in the data grid - **DDL management**: Create and alter tables, views, and indexes - **Data export**: Export query results in multiple formats By using Bunny Database with DBCode, you can efficiently develop and manage your edge database directly within Visual Studio Code. For more information about Bunny Database, visit bunny.net. --- ## Docs > Supported Databases > Cassandra ### Cassandra Database Management in VS Code DBCode is a Cassandra extension for VS Code: connect, browse keyspaces and tables, and query with CQL without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Apache Cassandra is an open source NoSQL distributed database trusted by thousands of companies for scalability and high availability without compromising performance. ## Connecting To connect to Cassandra, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Cassandra as the type, and enter the required information. 4. **Connect**: Click save to connect to your Cassandra database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to Cassandra, refer to the [Connect](/docs/get-started/connect) article. By using Cassandra with DBCode, you can connect to your Cassandra databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Cassandra, check out Cassandra. --- ## Docs > Supported Databases > Chromadb ### ChromaDB Vector Database Management in VS Code ## Overview ChromaDB (Chroma) is an open-source embedding database designed to make building AI applications with retrieval simple. Highlights include: - **Embeddings-first**: Store documents, metadata, and their embeddings together in a single collection - **Metadata filtering**: Combine vector similarity with structured `where` filters on metadata - **Simple data model**: Each record has an id, a document, optional metadata, and a vector - **Tenants and databases**: Organise collections under a tenant/database hierarchy - **Cloud or self-hosted**: Run locally with Docker, self-host, or use Chroma Cloud ChromaDB is commonly used for semantic search, retrieval-augmented generation (RAG), and AI assistants that need to find documents similar to a query. ## Connecting To connect to ChromaDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select ChromaDB as the database type and enter: - Host address (default port: 8000) - API token (for Chroma Cloud or any auth-protected instance) - Optional tenant and database (default to `default_tenant` / `default_database`) - Optional SSL/TLS configuration and SSH tunnel 4. **Connect**: Click save to connect to your ChromaDB instance. 5. **Start exploring**: Browse your collections, inspect records, and run vector searches. For detailed instructions, refer to the [Connect](/docs/get-started/connect) article. ## ChromaDB Features in DBCode DBCode brings the same browse-and-search workflow you already use for SQL and document databases to ChromaDB: - **Collection browsing**: Navigate collections, see record counts, and inspect document + metadata shape - **Vector cell rendering**: Vector columns are summarised inline (e.g. `[float32×384]`) and expandable on click - **Vector search**: Run nearest-neighbour searches with top-K, metadata filters, and a `_score` column - **Metadata editing**: Edit metadata fields inline and delete records; the document and embedding are read-only - **Search by text**: Configure an Ollama model or DBCode AI to embed your query text on the fly - **JS shell editor**: Drop into a JavaScript editor and run the official Chroma client directly (`client.search(...)`, `client.get(...)`, `collection('name').query(...)`, etc.) By using ChromaDB with DBCode, you get a unified workspace for traditional and vector data without leaving VS Code. For more information about ChromaDB, check out Chroma. --- ## Docs > Supported Databases > Clickhouse ### ClickHouse Database Management in VS Code DBCode is a ClickHouse extension for VS Code: connect, browse tables, run analytical SQL with schema-aware autocomplete, and chart results without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview ClickHouse is a fast open-source column-oriented database management system designed for online analytical processing (OLAP) with key characteristics: - **High performance**: Exceptionally fast query execution for analytical workloads - **Column-oriented storage**: Optimized for analytical queries on large datasets - **Linear scalability**: Scales horizontally across distributed clusters - **Real-time data ingestion**: Handles millions of inserts per second - **Efficient compression**: Reduces storage requirements while maintaining speed ClickHouse is ideal for analytics, time-series data, log processing, business intelligence, and high-volume data reporting applications. ## Connecting To connect to ClickHouse in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select ClickHouse as the database type and enter: - Host/Server address - Port (8123) - Username and password - Database name (optional, default is 'default') 4. **Connect**: Click save to connect to your ClickHouse server. 5. **Start Managing Your Data**: Explore databases, tables, and run queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## ClickHouse Features in DBCode DBCode enhances your ClickHouse development experience with: - **SQL query editor**: Write and execute ClickHouse SQL queries with syntax highlighting - **Data preview**: Quickly view sample data from large tables - **Schema browsing**: Navigate through databases and tables - **Query results visualization**: View and export query results By using ClickHouse with DBCode, you can efficiently develop and test analytical queries and data transformations directly within Visual Studio Code. For more information about ClickHouse, check out ClickHouse. --- ## Docs > Supported Databases > Cockroach ### CockroachDB Database Management in VS Code DBCode is a CockroachDB extension for VS Code: connect to a local cluster or CockroachDB Cloud, browse schemas and data, write SQL with schema-aware autocomplete, and edit rows visually without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview CockroachDB is a cloud-native, open-source, distributed SQL database that provides a scalable and fault-tolerant solution for managing and querying large volumes of structured data. With CockroachDB, you can build and run applications that require high availability, high performance, and scalability. ## Connecting To connect to CockroachDB, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose CockroachDB as the type, and enter the required information. 4. **Connect**: Click save to connect to your CockroachDB database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to CockroachDB, refer to the [Connect](/docs/get-started/connect) article. ## Kerberos / GSSAPI Authentication DBCode exposes **Integrated (Kerberos)** for CockroachDB Enterprise connections. CockroachDB Enterprise is required, and the cluster must be configured to accept GSSAPI authentication. - Select **Integrated (Kerberos)** and enter the CockroachDB username that the Kerberos identity maps to. - On Windows, DBCode uses the current signed-in identity. On macOS and Linux, it uses an existing Kerberos ticket cache. - Integrated authentication requires a host/TCP connection. DBCode does not accept or manage keytabs. - The default **Kerberos Service Name** is `postgres`. Change it only when the cluster administrator registered another service name. By using CockroachDB with DBCode, you can connect to your CockroachDB databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about CockroachDB, check out CockroachDB. --- ## Docs > Supported Databases > Couchbase ### Couchbase Database Management in VS Code ## Overview Couchbase is a distributed NoSQL document database combining the flexibility of JSON with the power of SQL++ (N1QL) queries. Key characteristics include: - **JSON document model**: Store schema-flexible JSON documents in collections - **SQL++ (N1QL) querying**: Familiar SQL syntax extended for JSON, including JOINs, UNNEST, and subqueries - **Multi-level hierarchy**: Buckets contain Scopes, which contain Collections - mapping naturally to databases, schemas, and tables - **High availability**: Built-in replication, automatic failover, and cross-datacenter replication (XDCR) - **Cloud and self-hosted**: Available as Couchbase Server (on-premises or self-managed) and Couchbase Capella (fully managed cloud) Couchbase is used for user profiles, session management, content management, real-time analytics, and applications requiring low-latency reads and writes at scale. ## Connecting To connect to Couchbase in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Couchbase as the database type and enter: - **Host**: hostname or IP of your Couchbase node (or Capella endpoint) - **Port**: management port (default: 8091); the query service is auto-discovered - **SSL/TLS**: enable for Couchbase Capella and any TLS-secured cluster - **Username / Password**: Couchbase RBAC credentials, or choose a Command auth profile 4. **Connect**: Click save to connect to your cluster. 5. **Start exploring**: Browse buckets, scopes, and collections. DBCode connects over HTTP/REST - no native Couchbase client or SDK is required. Works with both Couchbase Server (self-hosted) and Couchbase Capella (cloud). For detailed connection instructions, refer to the [Connect](/docs/get-started/connect) article. ## Data Model Couchbase's hierarchy maps to familiar database concepts in DBCode: | Couchbase | DBCode | |---|---| | Bucket | Database | | Scope | Schema | | Collection | Table | Documents are JSON. DBCode infers column structure by sampling documents via Couchbase INFER, so all columns are nullable. The document key is surfaced as a synthetic `id` column. ## Couchbase Features in DBCode DBCode enhances your Couchbase development experience with: - **SQL++ query editor**: Write and execute N1QL/SQL++ queries with syntax highlighting; multi-statement scripts are supported - **Document browsing**: Navigate buckets, scopes, and collections with row counts and inferred schemas - **Document editing**: Edit, insert, and delete documents inline in the data grid or JSON inspector (key-addressed SQL++ under the hood) - **Structural management**: Create and drop scopes and collections; create, drop, and flush buckets - **Data export**: Export query results in multiple formats By using Couchbase with DBCode, you can query and manage your document data directly within Visual Studio Code. For more information about Couchbase, visit couchbase.com. --- ## Docs > Supported Databases > Couchdb ### Apache CouchDB Database Management in VS Code ## Overview Apache CouchDB is an open-source, document-oriented NoSQL database that stores data as JSON documents and is accessed entirely over an HTTP/REST API. Key advantages include: - **Document model**: Store schema-free JSON documents, each with its own `_id` and revision (`_rev`) - **Mango queries**: Query documents with a simple JSON selector language via `_find` - **HTTP/REST API**: Everything is an HTTP request, so no native driver is required - **Multi-version concurrency control**: Lock-free reads and optimistic writes via document revisions - **Replication**: Robust, incremental, bi-directional replication for offline-first and distributed setups CouchDB is well suited to offline-first applications, content storage, and systems that need reliable replication across nodes or devices. ## Connecting To connect to CouchDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Apache CouchDB as the database type and enter: - Host and port (default `5984`, or `6984` for TLS) - Username and password (CouchDB 3.x requires a server admin user) - SSL/TLS settings (if required) - An optional default database 4. **Connect**: Click save to establish your connection. 5. **Start Managing Your Data**: Browse databases, documents, and indexes. For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. ## CouchDB Features in DBCode DBCode brings CouchDB into your editor with: - **Database tree**: Each CouchDB database shows its **All Documents** collection and its **Mango Indexes** - **Mango query editor**: Write JSON `_find` queries (for example, `{ "selector": { "year": { "$gte": 2010 } } }`) that run against the active database; point-and-click grid filtering builds Mango for you - **JSON document editing**: View and edit documents in the grid; updates are applied safely using the document's current revision (`_rev`), with clear conflict messages - **Index management**: Create and drop Mango (JSON) indexes - **EXPLAIN**: See which index a Mango query uses via CouchDB's `_explain` - **Monitoring**: Inspect active tasks, node statistics, and cluster membership - **Read-only connections**: Mark a connection read-only to block every write and DDL while still allowing queries and browsing By using CouchDB with DBCode, you can manage your document databases directly within Visual Studio Code. For more information about Apache CouchDB, check out Apache CouchDB. --- ## Docs > Supported Databases > Csv ### CSV File Viewer and Editor in VS Code ## Overview DBCode lets you open and work with CSV files directly in VS Code. Browse data with sorting and filtering, edit values inline, and run SQL queries against your CSV files using DuckDB under the hood. ## Features - Open any `.csv` file in the data grid - Sort, filter, and group data - Edit values inline - Run SQL queries against CSV data - Export to other formats (Excel, Parquet, JSON) --- ## Docs > Supported Databases > Cube ### Cube Semantic Layer in VS Code ## Overview Cube is a semantic layer (headless BI platform) that defines metrics once and serves them consistently across tools. Key characteristics include: - **Semantic data model**: Data is modeled as cubes, each exposing dimensions, measures, and segments over an underlying data source - **Postgres-compatible SQL API**: Query cubes with SQL over the Postgres wire protocol - **Consistent metrics**: Measures (aggregations) and pre-defined joins are evaluated server-side, so results are consistent regardless of the client - **Caching and pre-aggregations**: Cube accelerates queries with a caching layer and pre-aggregated rollups Cube is ideal for exploring governed metrics and data models from a SQL client without re-implementing business logic. ## Connecting To connect to Cube in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Cube as the database type and enter: - Host and port of Cube's SQL API (default: 15432) - Username and password (the `CUBEJS_SQL_USER` / `CUBEJS_SQL_PASSWORD` credentials) - Optionally, a REST API URL and API token to enrich the schema from Cube's `/meta` endpoint (descriptions, measure vs dimension roles, primary keys, views, and relationships) 4. **Connect**: Click save to connect to your Cube deployment. 5. **Start Exploring**: Browse cubes, inspect their columns, and run analytical queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## Cube Features in DBCode DBCode enhances your Cube experience with: - **Schema browsing**: All schemas are discovered, with cubes and views appearing as typed objects and their dimensions, measures, and segments listed as columns - **SQL query editor**: Write and execute Cube SQL (including `MEASURE(...)` aggregations and pre-defined cross-cube joins) with syntax highlighting - **/meta enrichment** (when a REST API URL is set): columns are annotated as measures or dimensions with descriptions, primary keys are marked, views are separated from cubes, and segments are hidden - **Relationships**: Cube's predefined joins are surfaced as foreign keys between cubes - **Execution plans**: Run EXPLAIN to see Cube's logical and physical query plan - **Monitoring**: A Sessions and Locks view of the SQL API - **Schema inspection**: View a cube's column layout as a reference CREATE TABLE definition - **Row counts**: Enable "Update Statistics" in the connection's introspection settings to include per-cube row counts - **Data exploration**: Preview and export query results - **Query cancellation and row limits**: Long-running queries can be cancelled, and the editor row limit is applied to results Cubes are defined in your Cube data model rather than via DDL, so connections are read-only: there is no insert, update, delete, or schema modification. Cube evaluates numeric dimensions as 64-bit floating point, so integer values beyond 2^53 are returned with reduced precision. This is a characteristic of Cube's SQL engine. By using Cube with DBCode, you can explore your semantic model and governed metrics directly within Visual Studio Code. For more information about Cube, visit cube.dev. --- ## Docs > Supported Databases > D1 ### Cloudflare D1 Database Management in VS Code ## Overview Create a serverless relational database in seconds with D1. With a familiar SQL query language, point-in-time recovery, and cost-effective pricing, you are empowered to build the next big thing. ## API Token Authentication Cloudflare connections for a single database, or cloud provider are made using an API token. To create an API token, follow these steps: 1. Log in to the Cloudflare dashboard. 2. Choose My Profile from the avatar menu icon in the top right corner. 3. Click the API Tokens tab. 4. Click the Create Token button. 5. Click Get Started next to the Create Custom Token option. 6. Enter a name for your token. 7. Permissions: The following permissions are required for D1 access: - Account - D1 - Edit If you wish to use the Cloudflare cloud provider, you will also need to grant the following permissions: - Account - Account Settings - Read - Account - Workers R2 Data Catalog - Read - Account - Workers R2 SQL - Read 8. Configure option token options as needed (e.g. IP allowlist, TTL) 9. Click the Continue to Summary button. 10. Click the Create Token button. 11. Copy the API token. More information on API tokens can be found in the [Cloudflare documentation](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/). ## Connect Single Database To connect to Cloudflare D1, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Cloudflare D1 as the type, enter your API token, then pick your account from the dropdown. Optionally pick a single database from the Database dropdown, or leave it blank to see every database in the account. 4. **Connect**: Click save to connect to your Cloudflare D1 account. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. The Account ID field offers a fetch button once the API token is entered: DBCode lists your accounts so you can pick instead of pasting an ID. The Database field works the same way, listing your account's databases by name. Manual entry still works for both fields. For detailed instructions on connecting to Cloudflare D1, refer to the [Connect](/docs/get-started/connect) article. ## Connect Multiple Databases To connect to Cloudflare as a cloud provider and access multiple databases, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Your Provider**: Choose the Cloudflare cloud provider from the list on the right. 4. **Authenticate**: Follow the authentication process specific to the provider. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. Each Cloudflare account gives you one D1 connection listing every database underneath it, and (if you use R2 SQL too) one R2 SQL connection listing its catalog-enabled buckets. For detailed instructions on connecting to Cloudflare D1, refer to the [Connect a Cloud Provider](/docs/cloud-providers/connect) article. By using Cloudflare D1 with DBCode, you can connect to your Cloudflare D1 databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Cloudflare D1, check out Cloudflare D1. --- ## Docs > Supported Databases > Dameng ### Dameng DM8 Database Management in VS Code ## Overview Dameng DM8 is an enterprise-grade relational database developed in China and widely used in government, finance, and large-enterprise environments. Key characteristics include: - **Oracle compatibility**: Supports a broad subset of Oracle SQL syntax, PL/SQL-style stored procedures, and familiar data types, making it accessible to Oracle-experienced teams - **Schema-based organization**: Databases are organized into schemas containing tables, views, procedures, functions, sequences, and triggers - **Standard SQL**: Full support for DML (SELECT, INSERT, UPDATE, DELETE), DDL, transactions, and stored programming objects - **Enterprise features**: Built-in user and privilege management, session monitoring, and lock visibility - **High availability**: Supports clustering, replication, and backup/recovery for production deployments Dameng DM8 is well suited for enterprise applications, government information systems, and workloads that require Oracle-compatible SQL in environments where domestic software is preferred or mandated. ## Connecting To connect to Dameng DM8 in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Dameng as the database type and enter: - **Host**: hostname or IP address of your DM8 instance - **Port**: TCP port (default: 5236) - **Username / Password**: DM8 credentials 4. **Connect**: Click save to connect to your Dameng database. 5. **Start exploring**: Browse schemas, tables, views, and stored objects, and run queries. For detailed connection instructions, refer to the [Connect](/docs/get-started/connect) article. ## Dameng Features in DBCode DBCode enhances your Dameng development experience with: - **SQL query editor**: Write and execute DM8 SQL with syntax highlighting and multi-statement support - **Schema browsing**: Navigate schemas, tables, views, procedures, functions, sequences, and triggers with column types and row counts - **Data editing**: Insert, update, and delete rows inline in the data grid - **DDL scripting**: Generate object definitions (CREATE TABLE, CREATE PROCEDURE, and similar) directly from the schema browser - **Transactions**: Pin a connection to run statements in a transaction and commit or roll back together - **Server monitoring**: View active sessions, locks, and system activity from the monitoring panel - **Data export**: Export query results in multiple formats ### Preview limitations Dameng support is in Preview. Some advanced DM8-specific syntax and dialect extensions may not get full editor IntelliSense yet. By using Dameng DM8 with DBCode, you can develop and run queries and manage your enterprise database directly within Visual Studio Code. For more information about Dameng, visit dameng.com. --- ## Docs > Supported Databases > Databricks ### Databricks Database Management in VS Code DBCode is a Databricks extension for VS Code: connect to your workspace, browse schemas and tables, run SQL with schema-aware autocomplete, and chart results without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Databricks is a unified data analytics platform built on Apache Spark, offering a collaborative environment for data engineering, data science, and machine learning: - **Unified platform**: Combines data engineering, data science, and analytics in one place - **Delta Lake**: ACID transactions and scalable metadata handling on data lakes - **Collaborative notebooks**: Share code, visualizations, and insights across teams - **Multi-cloud support**: Available on AWS, Azure, and Google Cloud - **SQL Analytics**: Run SQL queries on your data lakehouse with SQL Warehouses Databricks is ideal for building data pipelines, training ML models, running SQL analytics, and creating real-time data applications. ## Connecting To connect to Databricks in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Databricks as the database type and enter: - Host (e.g., adb-1234567890123456.7.azuredatabricks.net) - HTTP Path (from your SQL Warehouse or cluster settings) - Personal Access Token or use OAuth authentication - Catalog (optional, defaults to your workspace default) 4. **Connect**: Click save to connect to your Databricks workspace. 5. **Start Managing Your Data**: Explore catalogs, schemas, tables, and run queries. For detailed instructions on connecting to Databricks, refer to the [Connect](/docs/get-started/connect) article. ## Authentication Methods DBCode supports two authentication methods for Databricks: ### Personal Access Token Generate a personal access token in your Databricks workspace settings and use it as the password in your connection configuration. ### OAuth (U2M) Use browser-based OAuth authentication for enhanced security. When connecting, DBCode will open your browser to authenticate with your Databricks workspace. ## Databricks Features in DBCode DBCode enhances your Databricks development experience with: - **Unity Catalog browsing**: Navigate through catalogs, schemas, tables, and views - **SQL editing**: Write and execute SQL queries with syntax highlighting and autocomplete - **Data preview**: Quickly view sample data from tables - **Session variables**: Use connection pinning to maintain session state across queries - **Function support**: Browse and use user-defined functions By using Databricks with DBCode, you can efficiently develop SQL queries, explore your data lakehouse, and manage your Unity Catalog objects directly within Visual Studio Code. For more information about Databricks, check out Databricks. --- ## Docs > Supported Databases > Dataverse ### Microsoft Dataverse Management in VS Code ## Connecting To connect to Dataverse, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Dataverse as the type, and enter the required information including your environment URL and authentication details. 4. **Connect**: Click save to connect to your Dataverse environment. 5. **Start Managing Your Data**: Once connected, you can start querying your Dataverse tables directly from Visual Studio Code. For detailed instructions on connecting to Dataverse, refer to the [Connect](/docs/get-started/connect) article. By using Dataverse with DBCode, you can connect to your Dataverse environments, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Dataverse, check out Microsoft Dataverse. --- ## Docs > Supported Databases > Db2 ### IBM DB2 Database Management in VS Code DBCode is a DB2 extension for VS Code: connect, browse schemas and data, write SQL with schema-aware autocomplete, and edit rows visually without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview IBM Db2 is a family of data management products, including database servers, developed by IBM. Db2 is designed to store, analyze, and retrieve data efficiently, supporting both transactional and analytical workloads. With DBCode, you can connect to your Db2 databases, run queries, and manage your data directly from Visual Studio Code. ## Authentication IBM Db2 connections are typically made using a combination of hostname, port, database name, username, and password. Ensure you have the following information from your Db2 administrator or cloud provider: - Hostname or IP address - Port number (default is 50000) - Database name - Username - Password ## Connect to a Db2 Database To connect to a single IBM Db2 database, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the New Connection Form**: Choose IBM Db2 as the type, and enter the required connection details (hostname, port, database, username, password). 4. **Connect**: Click save to connect to your IBM Db2 database. 5. **Start Managing Your Databases**: Once connected, you can start managing your Db2 databases directly from Visual Studio Code. For detailed instructions on connecting to IBM Db2, refer to the [Connect](/docs/get-started/connect) article. ## Debugging DBCode can debug native Db2 SQL PL procedures with the VS Code debugger. See [Debugger](/docs/query/debugger) for how to start a session and use the shared debug UI. This section covers the Db2-specific scope and setup. ### Required roles and privileges The connection's effective authorization must have the `SYSDEBUG` role. When the effective authorization is not the owner of the procedure, it must also have `SYSDEBUGPRIVATE`. The authorization must be able to execute the native debugger procedures used by Db2. DBCode checks these requirements, but it does not grant roles, change privileges, or redeploy routines. Ask the database administrator to prepare the database according to the site's access policy. The exact grant statements depend on how that database manages users, groups, and roles. ### Compile a procedure for debugging Db2 must compile the procedure with debug information. On one database connection, call: ```sql CALL SYSPROC.PSMD_SET_COMPILEMODE(1); ``` Without releasing or replacing that connection, run the complete `CREATE OR REPLACE PROCEDURE` statement. Calling `PSMD_SET_COMPILEMODE` on one pooled connection and deploying on another does not prepare the procedure. Then verify the exact deployed routine: ```sql SELECT ROUTINESCHEMA, ROUTINENAME, SPECIFICNAME, DEBUG_MODE FROM SYSCAT.ROUTINES WHERE ROUTINESCHEMA = 'YOUR_SCHEMA' AND ROUTINENAME = 'YOUR_PROCEDURE'; ``` `DEBUG_MODE` must be `ALLOW` for the `SPECIFICNAME` you intend to debug. Re-run the same-connection deployment process after replacing a procedure if the catalog no longer reports `ALLOW`. ### Configure callback reachability Db2 calls back to the host that runs the DBCode extension. The database server must be able to open an inbound IPv4 TCP connection to that host. The Db2 connection's advanced settings include: - **Debugger callback host** (`debuggerAdvertisedHost`): Leave this empty to let DBCode probe candidate local IPv4 addresses. Set it to a hostname or IPv4 address that Db2 can reach when automatic discovery is not suitable. - **Debugger callback port** (`debuggerListenerPort`): The default `0` uses an ephemeral port. Set a fixed port when an inbound firewall or port-forwarding rule needs a stable destination. Check the network path from the database server's point of view: - With NAT, advertise the reachable address and forward the configured fixed port to the extension host. - With a VPN, make sure the database can route back to the extension host's VPN address. - With a containerized database, remember that the container's loopback address is not the host's loopback address. - In a remote VS Code workspace, the extension may run on the remote workspace host rather than your local computer. Db2 must reach the host where DBCode is running. - Ordinary local SSH forwarding carries the database connection toward Db2, but it does not create this reverse callback path. Arrange a reachable address, VPN route, port forward, or separate reverse tunnel as appropriate for the environment. DBCode tests the callback path before launch. If no candidate works, set the callback host explicitly and use a fixed port while checking routing and firewall rules. ### Debugger features and limits Db2 sessions support: - Entry and executable-line breakpoints - Continue, Step Over, Step Into, and Step Out - Nested call stacks - Watches by variable name - Display of `INTEGER`, `VARCHAR`, and SQL `NULL` values In the first release, value editing is limited to a mutable `INTEGER` variable in the selected top stack frame. Other types and variables in older stack frames are read-only. Pause is not supported while a procedure is running. Set a breakpoint before continuing if you need another stop point. When you stop a paused or running session, DBCode asks Db2 to terminate the target using the cleanup operation for its current state, then releases the debugger listener and dedicated connection. If cleanup cannot be confirmed, the session ends with an error instead of reporting a successful stop. ### Troubleshooting readiness failures | Check | What to verify | |---|---| | Platform | The server is Db2 LUW. The debugger is validated against 12.1.0.0, but DBCode does not enforce a server-version allowlist. | | Procedure | The target is a supported SQL PL procedure and its exact `SYSCAT.ROUTINES` row has `DEBUG_MODE = 'ALLOW'`. | | Authorization | The effective authorization has `SYSDEBUG`, has `SYSDEBUGPRIVATE` for a procedure owned by another authorization, and can execute the required native debugger procedures. | | Callback | Db2 can open an inbound IPv4 TCP connection to the advertised extension host and listener port. Check firewalls, NAT, VPN routing, containers, remote workspace placement, and tunnel direction. | --- ## Docs > Supported Databases > Derby ### Apache Derby Database Management in VS Code ## Overview Apache Derby is a relational database written entirely in Java, distributed by the Apache Software Foundation. It runs embedded inside the JVM with zero configuration, ships in a few JARs, and speaks standard SQL. Inside DBCode it works the same way SQLite or PGlite do — open a database, browse the schema, run queries — but with the JDBC-driven Java SQL surface. Highlights: - **Three connection modes**: In-Memory (data discarded when the connection closes), Embedded (a directory on disk), or Server (network). - **Pure Java**: no native binaries; runs anywhere the Java runtime that DBCode bundles runs. - **Standard SQL**: tables with constraints, views, triggers, sequences, synonyms, procedures and functions (Java method references). Derby is a great fit for prototypes, embedded data layers in Java apps, and lightweight integration test fixtures. ## Connecting To connect to a Derby database in DBCode: 1. **Open the DBCode Extension** in Visual Studio Code. 2. **Add a New Connection** and choose **Apache Derby**. 3. **Pick a connection mode**: - **In-Memory** — fastest start; pick a name like `mydb`. Set "Create if not exists" to bootstrap a fresh DB. - **Embedded (Directory)** — pick a folder. Set "Create if not exists" if it's a new database. - **Server (Network)** — point at a running Derby Network Server (default port 1527). Provide username + password. 4. **Connect**. ## Derby features in DBCode - **Full schema browser**: schemas + tables (with columns, indexes, primary keys, foreign keys, unique/check constraints, triggers) + views + procedures + functions + sequences + synonyms. - **DDL scripting for views**: views' definitions come straight from `SYS.SYSVIEWS.VIEWDEFINITION`. For other object types DDL scripting is intentionally not generated — Derby doesn't expose machine-readable definitions for tables/triggers/etc., and reconstructing them from system catalogs would mean shipping fragile parsers. Use the SQL editor to inspect or modify those objects. - **CRUD on tables**: edit data through DBCode's grid. For more information about Derby, check out db.apache.org/derby. --- ## Docs > Supported Databases > Documentdb ### Amazon DocumentDB Management in VS Code ## Overview Amazon DocumentDB is a fully managed, MongoDB-compatible document database service from AWS. It stores data as flexible JSON-like documents and speaks the MongoDB wire protocol, so you work with it in DBCode exactly as you would MongoDB: collections, documents, aggregation pipelines, and the same query editor. ## Connecting To connect to Amazon DocumentDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Choose Amazon DocumentDB**: Select Amazon DocumentDB as the database type. The form comes preset with DocumentDB-friendly defaults: the `mongodb://` protocol, SSL/TLS enabled, and `retryWrites=false` (DocumentDB does not support retryable writes). 4. **Enter your cluster details**: host (your cluster endpoint), port (27017), username, and password. 5. **Connect**: Click save to connect and start managing your collections and documents. For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. ### Connecting from outside the VPC Amazon DocumentDB clusters run inside a VPC and are not reachable from the public internet. To connect from your local machine, either run VS Code from a host inside the VPC, or use an SSH tunnel through a bastion in the VPC. DBCode has built-in SSH tunnel support under the connection's Tunnel settings. When you connect through a tunnel, the cluster's TLS certificate is issued for the cluster endpoint rather than the tunnel address, so set **Certificate Verification** to **Verify CA Only** or **No Verification** to avoid a hostname mismatch. Leave **Additional Hosts** empty so DBCode connects directly instead of attempting replica-set discovery of in-VPC hosts that are unreachable through the tunnel. For more on tunnels, see [SSH Tunnels](/docs/connections/ssh-tunnels). For more information about Amazon DocumentDB, check out Amazon DocumentDB. --- ## Docs > Supported Databases > Doris ### Apache Doris Database Management in VS Code ## Connecting To connect to Doris, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Doris as the type, and enter the required information. 4. **Connect**: Click save to connect to your Doris database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to Doris, refer to the [Connect](/docs/get-started/connect) article. By using Doris with DBCode, you can connect to your Doris databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Doris, check out Doris. --- ## Docs > Supported Databases > Druid ### Apache Druid Real-Time Analytics in VS Code ## Overview Apache Druid is a high-performance, real-time analytics database built for fast slice-and-dice queries on large datasets. Key characteristics include: - **Sub-second queries at scale**: Optimized for interactive analytics over trillions of rows - **Real-time and batch ingestion**: Stream from Kafka or Kinesis alongside batch loads from S3, HDFS, or local files - **Columnar storage with time partitioning**: Segment-based storage with bitmap indexes and automatic time-based partitioning - **SQL query interface**: Apache Calcite based SQL over an HTTP API - **Elastic, fault-tolerant architecture**: Independently scalable ingestion, querying, and storage tiers Druid is ideal for clickstream and event analytics, application performance monitoring, operational dashboards, and other high-concurrency analytical workloads. ## Connecting To connect to Apache Druid in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Apache Druid as the database type and enter: - Host and port of the Druid Router (default: 8888). Connecting directly to a Broker (8082) also works. - Username and password (if the basic-security extension is enabled) 4. **Connect**: Click save to connect to your Druid cluster. 5. **Start Exploring**: Browse schemas and datasources, inspect columns, and run analytical queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## Apache Druid Features in DBCode DBCode enhances your Apache Druid experience with: - **Schema browsing**: Navigate Druid's real schemas - `druid` (your datasources), `sys` (system tables for segments, servers, and tasks), and `lookup` - with column types and per-datasource row and size statistics - **SQL query editor**: Write and execute Druid SQL with syntax highlighting over the SQL HTTP API - **Schema inspection**: View live datasource and view column layouts from Druid's information schema; CREATE, ALTER, and DROP scripting is not available - **Execution plans**: Run EXPLAIN to see the native query plan as a tree - **Server monitoring**: Inspect cluster servers, segments, ingestion tasks, and supervisors from the monitoring panel - **Data exploration**: Preview and export query results - **Query cancellation and row limits**: Long-running queries can be cancelled, and the editor row limit is applied efficiently server-side Druid datasources are populated by ingestion rather than DDL, so connections are read-only for data: there is no insert, update, or delete. By using Apache Druid with DBCode, you can efficiently explore and query your real-time analytics data directly within Visual Studio Code. For more information about Apache Druid, visit druid.apache.org. --- ## Docs > Supported Databases > Duckdb ### DuckDB Database Management in VS Code DBCode is a DuckDB extension for VS Code: open local DuckDB files, run analytical SQL with schema-aware autocomplete, and chart results, all inside your editor with no server to set up. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview DuckDB is an embeddable SQL OLAP database management system designed specifically for analytical queries. Key features include: - **Columnar storage**: Optimized for analytical workloads with vectorized execution - **Embedded operation**: No server setup, runs directly within your application process - **ACID transactions**: Full transactional support with snapshot isolation - **Rich data format support**: Native reading and writing of CSV, Parquet, JSON, and more - **Seamless scaling**: From in-memory processing to disk-based operations as needed DuckDB is ideal for data analysis, reporting, and as an embedded analytical engine within applications, providing PostgreSQL-compatible SQL with optimizations for analytical workloads. ## Connecting To connect to DuckDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: - Select DuckDB as the database type - Choose to create a new database file or connect to an existing one - Optionally specify configuration settings like memory limits 4. **Connect**: Click save to establish your connection. 5. **Start Analyzing**: Begin querying and exploring your data. For detailed instructions on connecting to DuckDB, refer to the [Connect](/docs/get-started/connect) article. ## DuckDB Features in DBCode DBCode provides enhanced support for DuckDB's analytical capabilities: - **Direct file querying**: Query CSV, Parquet, and JSON files without importing - **SQL autocomplete**: Intelligent suggestions for DuckDB-specific functions - **EXPLAIN visualization**: Graphical query execution plan visualization By using DuckDB with DBCode, you gain a powerful analytical SQL engine directly within Visual Studio Code, perfect for data exploration, transformation, and analysis tasks without the overhead of traditional database systems. For more information about DuckDB, check out DuckDB. --- ## Docs > Supported Databases > Ducklake ### DuckLake Lakehouse Management in VS Code ## Overview DuckLake is a lakehouse solution built on [DuckDB](/docs/supported-databases/duckdb) that separates catalog metadata from data storage. Key features include: - **Flexible catalog backends**: Use a local DuckDB/SQLite file, a PostgreSQL/MySQL server, or a remote DuckDB catalog served over the quack protocol - **Multiple storage options**: Store Parquet data files locally, on Amazon S3, Google Cloud Storage, or Azure (ADLS Gen2 and Blob) - **Full SQL support**: Create, alter, and query tables using standard SQL through DuckDB - **ACID transactions**: Transactional guarantees via the underlying catalog database - **Time travel**: Query historical versions of your data DuckLake is ideal for teams that want lakehouse capabilities without the complexity of Spark or Hive, while retaining the speed and simplicity of DuckDB. ## Connecting To connect to DuckLake in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: - Select DuckLake as the database type - Choose your catalog type (local file, database server, or quack server). For a quack server, enter the host and port (default 9494) and an access token; transport uses HTTPS automatically for remote hosts and plain HTTP for localhost. - Configure the data storage location (local directory, S3 path, GCS path, or Azure path) - For S3/GCS storage, configure an AWS authentication profile; for Azure, configure an Azure Storage authentication profile (connection string, account key, SAS token, credential chain, managed identity, or service principal). For sovereign clouds, set the Endpoint Suffix (for example core.usgovcloudapi.net or core.chinacloudapi.cn). - For an existing local catalog, optionally enable **Read Only** to browse and query it without allowing writes. 4. **Connect**: Click save to establish your connection. 5. **Start Querying**: Begin creating tables and querying your lakehouse data. For detailed instructions on connecting to DuckLake, refer to the [Connect](/docs/get-started/connect) article. ## DuckLake Features in DBCode DBCode supports the core DuckLake workflow: - **Progressive schema browsing**: Explore schemas, tables, columns, and row estimates without loading the complete catalog at once - **SQL autocomplete**: Intelligent suggestions for DuckDB-specific functions and syntax - **Data editing**: Insert, update, and delete rows directly in the data grid, including precise numerics, dates, Unicode text, booleans, and NULL values - **Query cancellation**: Stop a running query from the editor and continue using the same connection - **Read-only catalog access**: Open an existing local catalog with DuckLake's read-only attach mode - **EXPLAIN visualization**: Graphical query execution plan visualization By using DuckLake with DBCode, you get a lightweight lakehouse directly within Visual Studio Code, with the full power of DuckDB's analytical engine and flexible storage backends. For more information about DuckLake, check out DuckLake. --- ## Docs > Supported Databases > Dynamodb ### Amazon DynamoDB in VS Code DBCode is a DynamoDB extension for VS Code: connect with your AWS credentials, browse tables, query and scan items, and edit data without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. Key benefits include: - **Fully managed**: No servers to provision, patch, or manage - **Highly scalable**: Automatically scales tables to adjust for capacity and maintain performance - **High availability**: Built-in replication across multiple Availability Zones - **Flexible data model**: Supports key-value and document data structures - **Pay-per-use pricing**: On-demand capacity mode charges only for reads and writes DynamoDB is ideal for applications requiring consistent, single-digit millisecond latency at any scale, such as mobile backends, gaming, IoT, and real-time analytics. ## Connecting To connect DynamoDB in DBCode: 1. **Open the DBCode extension** in Visual Studio Code and select `Add Connection`. 2. **Choose Amazon DynamoDB** from the database type list. 3. **Configure authentication** using one of the following methods: - **AWS IAM Auth Profile**: Use DBCode's centralized authentication profiles for AWS SSO, IAM Identity Center, or temporary credentials - **Access Keys**: Provide an IAM access key ID and secret access key - **Default Credentials**: Use the AWS SDK default credential chain (environment variables, shared credentials file, etc.) - **Local**: Connect to DynamoDB Local for development and testing 4. **Select the AWS region** where your DynamoDB tables are located. 5. **Save the connection** to browse your tables and start working with your data. ## DBCode Features for DynamoDB With a DynamoDB connection, DBCode provides: - **Table Browser**: Explore all tables with partition keys, sort keys, and global/local secondary indexes - **Column Discovery**: Automatically samples table data to discover all attributes beyond just key columns - **Data Grid**: View and edit table items with full support for DynamoDB's flexible schema - **CRUD Operations**: Insert, update, and delete items directly from the data grid - **Complex Types**: View and edit maps, lists, sets, and nested structures as JSON ### Key Concepts DynamoDB uses a different data model than traditional SQL databases: - **Partition Key**: The primary key attribute that DynamoDB uses to distribute data across partitions - **Sort Key**: An optional secondary key that allows range queries within a partition - **Attributes**: Each item can have different attributes (schema-less design) DBCode displays partition and sort keys separately in the schema tree, similar to how Redshift shows distribution and sort keys. ## Authentication Options ### AWS IAM Auth Profile (Recommended) Use DBCode's authentication profiles for seamless integration with AWS SSO, IAM Identity Center, or any credential provider that supports temporary credentials. This is the most secure option as credentials are automatically refreshed. ### Access Keys For development or when using IAM users, provide static access key credentials. Ensure the IAM user has appropriate DynamoDB permissions. ### DynamoDB Local For local development, connect to [DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html) running in Docker or as a JAR file. Learn more about DynamoDB at aws.amazon.com/dynamodb. --- ## Docs > Supported Databases > Elasticsearch ### Elasticsearch Database Management in VS Code DBCode is an Elasticsearch extension for VS Code: connect over HTTP or HTTPS, browse indices, and query with the SQL API without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Elasticsearch is a distributed, RESTful search and analytics engine capable of solving a growing number of use cases. Key characteristics include: - **Full-text search**: Powerful text analysis and search capabilities with relevance scoring - **Real-time analytics**: Analyze and visualize data as it arrives - **Distributed architecture**: Horizontally scalable with automatic sharding and replication - **SQL support**: Query data using familiar SQL syntax via the SQL API - **Schema-free JSON documents**: Store and index semi-structured data without predefined schemas - **RESTful API**: Simple HTTP-based interface for all operations Elasticsearch is ideal for log analytics, application search, security analytics, business analytics, and any use case requiring fast, scalable search and analytics. ## Connecting To connect to Elasticsearch in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Elasticsearch as the database type and enter: - Host/Server address - Port (default: 9200) - Username (if authentication is enabled) - Password (if authentication is enabled) - Enable SSL/TLS if required 4. **Connect**: Click save to connect to your Elasticsearch cluster. 5. **Start Managing Your Data**: Browse indices and run SQL queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## Elasticsearch Features in DBCode DBCode enhances your Elasticsearch development experience with: - **SQL query editor**: Write and execute Elasticsearch SQL queries with syntax highlighting - **Index browsing**: Navigate through indices and their field mappings - **Field type information**: View field types and nested object structures - **Query results visualization**: View and export query results - **Index mapping inspection**: View the complete mapping (schema) of any index By using Elasticsearch with DBCode, you can efficiently explore your indices, develop SQL queries, and analyze data directly within Visual Studio Code. For more information about Elasticsearch, check out Elasticsearch. --- ## Docs > Supported Databases > Exasol ### Exasol Database Management in VS Code ## Overview Exasol is a high-performance in-memory analytical database built on a massively parallel processing (MPP) architecture. Key characteristics include: - **In-memory MPP engine**: Distributes query execution across all cluster nodes for fast analytical performance - **Columnar storage**: Optimized for aggregation and analytical workloads on large datasets - **Standard SQL**: Full ANSI SQL support with extensions for analytics, scripting, and user-defined functions - **Schema-based organization**: Databases contain schemas, which contain tables, views, and functions - **Automatic compression**: Transparent data compression reduces storage and improves I/O performance Exasol is well suited for data warehousing, business intelligence, large-scale reporting, and real-time analytics. ## Connecting To connect to Exasol in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Exasol as the database type and enter: - **Host**: hostname or IP address of your Exasol instance - **Port**: WebSocket port (default: 8563) - **Username / Password**: Exasol credentials - **Encryption**: enable TLS and choose full, CA-only, or no certificate verification - **SSL Server Certificate**: optionally provide a custom CA certificate for full or CA-only verification 4. **Connect**: Click save to connect to your Exasol database. 5. **Start exploring**: Browse schemas, tables, and views, and run queries. DBCode connects via the Exasol WebSocket API - no ODBC driver or native client is required. For detailed connection instructions, refer to the [Connect](/docs/get-started/connect) article. ## Exasol Features in DBCode DBCode enhances your Exasol development experience with: - **SQL query editor**: Write and execute Exasol SQL with syntax highlighting and multi-statement support - **Schema browsing**: Navigate schemas, tables, views, and functions with column types and row counts - **Data editing**: Insert, update, and delete rows inline in the data grid - **Schema introspection**: Inspect table structure and view definitions - **Transactions**: Pin a connection to run statements in a transaction and commit or roll back together - **Session monitoring**: View active sessions and running statements from the monitoring panel - **Data export**: Export query results in multiple formats By using Exasol with DBCode, you can develop and run analytical queries and manage your data warehouse directly within Visual Studio Code. For more information about Exasol, visit exasol.com. --- ## Docs > Supported Databases > Excel ### Excel File Viewer and Editor in VS Code ## Overview DBCode lets you open and work with Excel files (`.xlsx`, `.xls`) directly in VS Code. Browse data with sorting and filtering, edit values inline, and run SQL queries against your spreadsheets using DuckDB under the hood. ## Features - Open any Excel file in the data grid - Browse multiple sheets - Sort, filter, and group data - Edit values inline - Run SQL queries against spreadsheet data - Export to other formats (CSV, Parquet, JSON) --- ## Docs > Supported Databases > Fabric ### Microsoft Fabric Database Management in VS Code ## Overview Microsoft Fabric is a unified analytics platform that combines data movement, data lakes, data engineering, data integration, data science, real-time analytics, and business intelligence: - **OneLake**: A single, unified data lake for your entire organization - **SQL Endpoints**: Query lakehouse and warehouse data using familiar T-SQL - **Data Warehouse**: Full read-write SQL warehouse with ACID transactions - **Lakehouse**: Combine the best of data lakes and data warehouses with Delta Lake format - **Real-time Analytics**: Stream and analyze data in real time Microsoft Fabric is ideal for organizations looking to consolidate their analytics workloads into a single, integrated platform on Azure. ## Connecting To connect to Microsoft Fabric in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Microsoft Fabric as the database type and enter: - Host (your Fabric SQL endpoint, e.g., `your-workspace.fabric.microsoft.com`) - Authentication (Microsoft Entra ID or SQL Server Authentication) - Database name (optional) 4. **Connect**: Click save to connect to your Fabric workspace. 5. **Start Managing Your Data**: Explore databases, schemas, tables, and run queries. For detailed instructions on connecting to Microsoft Fabric, refer to the [Connect](/docs/get-started/connect) article. ## Authentication Methods DBCode supports two authentication methods for Microsoft Fabric: ### Microsoft Entra ID Use your organizational Microsoft Entra ID credentials for secure, token-based authentication to your Fabric workspace. ### SQL Server Authentication Use a SQL username and password to connect to your Fabric SQL endpoints. ## Microsoft Fabric Features in DBCode DBCode enhances your Microsoft Fabric development experience with: - **Schema browsing**: Navigate through databases, schemas, tables, and views - **SQL editing**: Write and execute T-SQL queries with syntax highlighting and autocomplete - **Data preview**: Quickly view and explore data from Fabric tables - **Warehouse and Lakehouse support**: Connect to both Fabric Warehouse and Lakehouse SQL endpoints - **Full DDL support**: View and manage table definitions, views, and stored procedures By using Microsoft Fabric with DBCode, you can efficiently develop SQL queries, explore your data warehouse, and manage your Fabric objects directly within Visual Studio Code. For more information about Microsoft Fabric, check out Microsoft Fabric. --- ## Docs > Supported Databases > Firebase ### Firebase Database Management in VS Code DBCode is a Firebase extension for VS Code: connect to Firestore, browse collections, query documents, and subscribe to live updates without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Firebase is Google's comprehensive mobile and web application development platform that provides two powerful database solutions: - **Cloud Firestore**: A flexible, scalable NoSQL cloud database with offline support and real-time synchronization - **Realtime Database**: A cloud-hosted JSON tree database with low-latency data synchronization Key advantages include: - **Real-time synchronization**: Instantly sync data across all connected clients - **Offline capabilities**: Build responsive apps that work offline with local data caching - **Automatic scaling**: Handle everything from prototypes to production workloads - **Security rules**: Fine-grained access control with declarative security rules - **Seamless integration**: Works perfectly with other Firebase services (Auth, Storage, Functions) - **Multi-platform SDKs**: Native support for web, iOS, Android, and server environments Firebase excels in building collaborative applications, real-time dashboards, chat applications, IoT solutions, and mobile apps requiring instant data synchronization. ## Connecting To connect to Firebase in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Firebase**: Choose Firebase as the database type. 4. **Configure Connection**: - Enter your Firebase project ID - Choose authentication method: - Service Account JSON (recommended for production) - Application Default Credentials - Firebase Emulator (for local development) - For Realtime Database, provide the database URL 5. **Connect**: Click save to establish your connection. 6. **Start Managing Your Data**: Browse collections, documents, and data structures. For detailed instructions on connecting to Firebase, refer to the [Connect](/docs/get-started/connect) article. ## Authentication Methods ### Service Account Authentication For production environments, use a service account JSON file: 1. Go to Firebase Console → Project Settings → Service Accounts 2. Generate a new private key 3. Use the downloaded JSON file in DBCode's connection configuration ### Emulator Connection For local development with Firebase Emulator: 1. Start your Firebase emulator locally 2. Select "Emulator" as the authentication method 3. Specify the emulator host (default: localhost) and port ### Application Default Credentials Use Google Cloud SDK credentials when available on your system. ## Firebase Features in DBCode DBCode provides powerful tools for working with Firebase databases: ### Cloud Firestore - **Collection browsing**: Navigate through collections and subcollections - **Document editor**: Visual editing of document fields and values - **Schema inference**: Automatic detection of document structure patterns - **Data type support**: Full support for Firestore data types (timestamps, geopoints, references) ### Realtime Database - **Tree navigation**: Browse the JSON tree structure - **JSON editor**: Edit data in familiar JSON format ### Common Features - **Multiple project support**: Connect to multiple Firebase projects simultaneously - **Read and write operations**: Full CRUD capabilities for both databases - **Export/Import**: Easily move data between environments - [Live Streaming](/docs/data/streaming) (Firestore only): Subscribe to collection changes in real time. Right-click a collection and select **Subscribe** to receive create, update, and delete events as they happen By using Firebase with DBCode, you can efficiently develop and manage your cloud databases directly within Visual Studio Code, with full support for both Firestore and Realtime Database. For more information about Firebase, check out Firebase. --- ## Docs > Supported Databases > Firebird ### Firebird Database Management in VS Code ## Overview Firebird is a relational database that grew out of Borland's InterBase open-source release. It speaks standard SQL, has a small footprint, and ships with a rich PSQL stored-procedure language. DBCode connects to it over TCP using a pure-JavaScript implementation of the Firebird wire protocol — no native libraries to install. Highlights: - **Pure-JS connection** — no native client library or JDBC bridge. - **Server (TCP) mode**: host + port + database path or alias, username/password. - **Auth profiles** with the command-provider, for sourcing credentials from password managers. - **Full schema browser**: tables, views, procedures, functions, sequences, domains, exceptions, and packages. - **Engine-provided DDL** for views and packages — the editor's "Edit DDL" round-trips cleanly. - **Mixed-case identifier round-tripping** — Firebird folds unquoted names to uppercase like Oracle; the driver quotes mixed-case identifiers automatically. - **Schema support detected at connect time**: Firebird 6+ exposes user schemas (`RDB$SCHEMAS`) and the driver enables them; Firebird 5.x is treated as a single flat namespace. ## Connecting The connection form asks for: - **Host** and **Port** (default `3050`). - **Database Path or Alias** — an absolute path on the server (e.g. `/var/lib/firebird/data/employee.fdb`) or a configured alias. Firebird has no remote enumeration API, so the field is free-text. - **Username** / **Password** (default `SYSDBA`), or a configured **command** auth profile. - **SQL Role** (optional) for permission scoping — passed to `node-firebird` as `role`. - **Character Encoding** — `UTF8` by default; alternatives for legacy databases. ## What's not yet supported - **Embedded mode** — requires the native Firebird client library; not pure-JS. - **Backup / restore** via the Services API. - **DDL scripting** for tables, procedures, functions, and triggers — the engine doesn't expose a clean canonical form for those, and reconstructing it from system catalogs is fragile. Use the SQL editor to inspect or modify them. - **Pre-5.0 servers** — rejected at connect time. Firebird 5.0+ is the supported version floor. ## Versions Tested against: - `firebirdsql/firebird:5` (Firebird 5.0.4) — schema-less, single flat namespace - `firebirdsql/firebird:6-snapshot` (Firebird 6.0 alpha) — with user schemas --- ## Docs > Supported Databases > Greenplum ### Tanzu Greenplum Database Management in VS Code ## Connecting To connect to Greenplum, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Greenplum as the type, and enter the required information. 4. **Connect**: Click save to connect to your Greenplum database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to Greenplum, refer to the [Connect](/docs/get-started/connect) article. ## Kerberos / GSSAPI Authentication DBCode exposes **Integrated (Kerberos)** for Greenplum connections when the server is configured to accept PostgreSQL GSSAPI or SSPI authentication. - Select **Integrated (Kerberos)** and enter the Greenplum username that the Kerberos identity maps to. - On Windows, DBCode uses the current signed-in identity. On macOS and Linux, it uses an existing Kerberos ticket cache. - Integrated authentication requires a host/TCP connection. DBCode does not accept or manage keytabs. - The default **Kerberos Service Name** is `postgres`. Change it only when the server administrator registered another service name. By using Greenplum with DBCode, you can connect to your Greenplum databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Greenplum, check out Greenplum. --- ## Docs > Supported Databases > H2 ### H2 Database Management in VS Code ## Overview H2 is a lightweight, fast relational database written in Java with key characteristics: - **Embedded and server modes**: Run as an embedded database or standalone server - **Small footprint**: Compact JAR file (~2.5 MB) with minimal dependencies - **Fast performance**: In-memory and disk-based storage with excellent speed - **SQL compatibility**: Supports a large subset of SQL with PostgreSQL and MySQL compatibility modes - **Browser-based console**: Built-in web console for database administration H2 is ideal for development, testing, embedded applications, and scenarios requiring a lightweight database with minimal setup. ## Connecting To connect to H2 in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select H2 as the database type and enter: - Connection type (Embedded, In-Memory, TCP Server, or SSL Server) - Database path or name - Username and password (default: sa / empty) 4. **Connect**: Click save to connect to your H2 database. 5. **Start Managing Your Data**: Explore schemas, tables, and run queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## H2 Features in DBCode DBCode enhances your H2 development experience with: - **SQL query editor**: Write and execute SQL queries with syntax highlighting - **Schema browsing**: Navigate through schemas, tables, views, and other objects - **Data editing**: View and modify table data directly - **DDL generation**: Generate CREATE statements for database objects - **Multiple connection types**: Support for embedded, in-memory, and server modes By using H2 with DBCode, you can efficiently develop and test database applications directly within Visual Studio Code. For more information about H2, check out H2 Database Engine. --- ## Docs > Supported Databases > Hana ### SAP HANA Database Management in VS Code ## Overview SAP HANA is SAP's in-memory, column-oriented relational database, powering both transactional and analytical workloads across on-premise deployments and HANA Cloud. Key characteristics include: - **In-memory column store**: Data lives in memory in columnar form, making aggregations and analytical queries fast without separate indexes - **Hybrid workloads**: One engine serves OLTP and OLAP, so operational and analytical queries run on the same data - **Standard SQL**: Rich ANSI SQL support plus SQLScript stored procedures and functions - **Schema-based organization**: Databases contain schemas, which contain tables, views, sequences, and routines - **Multi-tenant architecture**: One HANA system hosts multiple isolated tenant databases SAP HANA is the foundation for SAP S/4HANA, SAP BW/4HANA, and standalone data-platform deployments. ## Connecting To connect to SAP HANA in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select SAP HANA as the database type and enter: - **Host**: hostname of your HANA Cloud instance or on-premise server - **Port**: SQL port (443 for HANA Cloud; on-premise tenant ports are typically 3NN15, e.g. 30015) - **Username / Password**: HANA database credentials - **Database**: tenant database name (optional - connects to the port's default tenant when omitted) - **SSL**: enable for HANA Cloud (required) and TLS-configured on-premise systems 4. **Connect**: Click save to connect to your SAP HANA database. 5. **Start exploring**: Browse schemas, tables, and views, and run queries. DBCode uses SAP's official `@sap/hana-client` driver. Because the driver is proprietary SAP software, DBCode does not bundle it - on first connection you are prompted to accept SAP's developer license, and the driver is downloaded from npm for your own use. For detailed connection instructions, refer to the [Connect](/docs/get-started/connect) article. ## SAP HANA Features in DBCode DBCode enhances your SAP HANA development experience with: - **SQL query editor**: Write and execute HANA SQL with syntax highlighting and multi-statement support - **Schema browsing**: Navigate schemas, tables, views, sequences, procedures, and functions with column types, row counts, and table sizes - **Data editing**: Insert, update, and delete rows inline in the data grid - **DDL scripting**: Script tables, views, and routines via HANA's built-in object-definition facility - **Execution plans**: Visualize EXPLAIN PLAN output as an interactive plan tree - **Transactions**: Pin a connection to run statements in a transaction and commit or roll back together - **Session monitoring**: View active sessions and running statements, and cancel or disconnect sessions from the monitoring panel - **Query cancellation**: Stop long-running queries from the editor - **Data export**: Export query results in multiple formats ### Preview limitations SAP HANA support is in Preview. Kerberos / Windows authentication is not yet supported - use username/password credentials. Some HANA-specific syntax (SQLScript blocks, calculation views, graph and spatial extensions) may not get full editor IntelliSense yet. By using SAP HANA with DBCode, you can develop, query, and manage HANA Cloud and on-premise HANA databases directly within Visual Studio Code. For more information about SAP HANA, visit sap.com. --- ## Docs > Supported Databases > Hive ### Apache Hive in VS Code ## Overview Apache Hive is a data warehouse infrastructure built on top of Hadoop for providing data summarization, query, and analysis. Key benefits include: - **SQL-like interface**: Query large datasets using HiveQL, a SQL-like language - **Scalable**: Designed to handle petabytes of data across distributed storage - **Schema flexibility**: Supports structured and semi-structured data - **Extensible**: User-defined functions (UDFs), custom SerDes, and storage handlers - **Integration**: Works seamlessly with Hadoop ecosystem tools like Spark, Pig, and HBase Hive is ideal for batch processing, data warehousing, and ETL workloads on large datasets stored in HDFS or cloud storage. ## Connecting To connect to Apache Hive in DBCode: 1. **Open the DBCode extension** in Visual Studio Code and select `Add Connection`. 2. **Choose Apache Hive** from the database type list. 3. **Configure the connection**: - **Host**: The HiveServer2 hostname or IP address - **Port**: Default is 10000 for TCP transport - **Database**: The default database to connect to (usually "default") 4. **Configure authentication**: - **None**: No authentication (for development environments) - **Plain**: Username and password authentication - **LDAP**: LDAP-based authentication 5. **Select transport protocol**: - **TCP**: Binary protocol (default, most common) - **HTTP**: HTTP transport for environments behind proxies 6. **Save the connection** to start browsing your Hive databases and tables. ## DBCode Features for Hive With a Hive connection, DBCode provides: - **Database Browser**: Explore databases, tables, views, and partitions - **Query Editor**: Write and execute HiveQL queries with syntax highlighting - **Data Grid**: View query results with sorting and filtering - **Table Metadata**: View column definitions, partition keys, and table properties - **DDL Generation**: Generate CREATE TABLE statements for existing tables ## Authentication Options ### No Authentication For development or unsecured environments, connect without credentials. ### Plain Authentication Username and password authentication over the Thrift protocol. ### LDAP Authentication Integrate with your organization's LDAP directory for authentication. ## Transport Options ### TCP (Binary) The default binary protocol for HiveServer2. Best performance for most deployments. ### HTTP HTTP transport mode, useful when connecting through proxies or load balancers that don't support binary protocols. Learn more about Apache Hive at hive.apache.org. --- ## Docs > Supported Databases > Ibmi ### IBM i (AS/400) Database Management in VS Code ## Overview IBM i is a fully integrated platform combining hardware, OS, and a built-in relational database (Db2 for i). DBCode connects via the JT400 JDBC driver, giving you direct access to SQL tables, views, procedures, and more from Visual Studio Code. ## Authentication IBM i connections require: - Hostname or IP address - Port number (default is 446 for DRDA) - Username (IBM i user profile) - Password SSL/TLS and SSH tunnel connections are also supported. ## Connect to an IBM i Database 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the New Connection Form**: Choose IBM i as the type, and enter the required connection details (hostname, port, username, password). 4. **Connect**: Click save to connect to your IBM i system. 5. **Start Exploring**: Browse schemas (libraries), tables, views, procedures, functions, and sequences. For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. ## IBM i Features in DBCode DBCode supports progressive schema loading for IBM i, which means large systems with thousands of tables load quickly by fetching schema contents on demand rather than all at once. Supported object types: - Tables and views with column details, indexes, constraints, and foreign keys - Stored procedures and functions with parameter metadata - Sequences - DDL generation for procedures and functions (editable and reapplicable) For more information about IBM i, check out IBM i. --- ## Docs > Supported Databases > Iceberg ### Apache Iceberg Table Management in VS Code ## Overview Apache Iceberg is an open table format designed for large-scale analytical datasets. DBCode connects to Iceberg catalogs through [DuckDB](/docs/supported-databases/duckdb)'s iceberg extension, supporting: - **AWS Glue / SageMaker Lakehouse**: Connect to Iceberg tables registered in the AWS Glue Data Catalog - **Amazon S3 Tables**: Connect directly to S3 Tables table buckets via ARN - **Schema exploration**: Browse catalogs, schemas, tables, and columns progressively in the object tree - **Standard SQL queries**: Query and modify Iceberg tables using DuckDB's analytical SQL engine - **Credential management**: AWS authentication via DBCode's auth profile system with automatic credential refresh Iceberg is ideal for teams running large-scale data lakes on AWS who want to explore and manage their Iceberg tables without spinning up Spark or EMR clusters. ## Connecting To connect to an Iceberg catalog in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: - Select Apache Iceberg as the database type - Choose your catalog type (AWS Glue or S3 Tables) - For Glue: provide your AWS Account ID and Glue endpoint - For S3 Tables: provide the table bucket ARN - Configure an AWS authentication profile with your credentials 4. **Connect**: Click save to establish your connection. 5. **Start Querying**: Browse and query your Iceberg tables. For detailed instructions on connecting to Apache Iceberg, refer to the [Connect](/docs/get-started/connect) article. ## Iceberg Features in DBCode DBCode provides access to Iceberg catalogs with: - **Progressive catalog browsing**: Explore schemas, tables, columns, and table properties in the object tree - **SQL queries and data editing**: Select, insert, update, and delete Iceberg data using DuckDB SQL - **Table management**: Create and import tables where supported by the connected catalog - **Execution plans**: Inspect structured query plans before running analytical queries - **Read-only connections**: Prevent write operations when a connection should only query catalog data - **SQL autocomplete**: Intelligent suggestions for table and column names - **Data export**: Export query results to CSV, Excel, Parquet, and other formats By using Apache Iceberg with DBCode, you can explore, query, and manage your data lake tables directly within Visual Studio Code, without needing heavyweight tools like Spark or Athena. For more information about Apache Iceberg, check out Apache Iceberg. --- ## Docs > Supported Databases > Impala ### Apache Impala in VS Code ## Overview Apache Impala is a massively parallel processing (MPP) SQL query engine for data stored in Apache Hadoop clusters. Key benefits include: - **Real-time queries**: Sub-second query response times on large datasets - **Native Hadoop integration**: Direct access to data in HDFS and Apache HBase - **ANSI SQL**: Standard SQL syntax familiar to analysts and developers - **High concurrency**: Handle multiple simultaneous queries efficiently - **Compatibility**: Works with Hive metastore for shared schema definitions Impala is ideal for interactive analytics, business intelligence, and ad-hoc querying on Hadoop data without the latency of batch processing. ## Connecting To connect to Apache Impala in DBCode: 1. **Open the DBCode extension** in Visual Studio Code and select `Add Connection`. 2. **Choose Apache Impala** from the database type list. 3. **Configure the connection**: - **Host**: The Impala daemon (impalad) hostname or IP address - **Port**: Default is 21050 for the HiveServer2 interface - **Database**: The default database to connect to (usually "default") 4. **Configure authentication** (if required): - **None**: No authentication (default for many Impala deployments) - **LDAP**: LDAP-based authentication for secured clusters 5. **Save the connection** to start querying your Impala databases. ## DBCode Features for Impala With an Impala connection, DBCode provides: - **Database Browser**: Explore databases, tables, and views - **Query Editor**: Write and execute SQL queries with syntax highlighting - **Data Grid**: View query results with sorting and filtering - **Table Metadata**: View column definitions and table statistics - **DDL Generation**: Generate CREATE TABLE statements ### Supported Object Types - **Databases**: Browse and switch between Impala databases - **Tables**: Internal and external tables including Kudu tables - **Views**: SQL views with underlying query definitions ## Authentication Options ### No Authentication (NoSasl) The default for many Impala deployments. Connects without SASL authentication. ### LDAP Authentication For secured clusters, authenticate using LDAP credentials. Learn more about Apache Impala at impala.apache.org. --- ## Docs > Supported Databases > Influxdb ### InfluxDB Database Management in VS Code ## Overview InfluxDB is a purpose-built time-series database designed for handling high volumes of timestamped data. Key characteristics include: - **Time-series optimized**: Purpose-built storage engine for time-stamped data with automatic data lifecycle management - **SQL support**: Query data using familiar SQL syntax (InfluxDB 3.0) - **High performance**: Optimized for high-write throughput and fast queries over time ranges - **Data retention policies**: Automatic data expiration and downsampling - **Built-in visualization**: Native support for time-series visualization and dashboards - **Cloud and self-hosted**: Available as managed cloud service or self-hosted deployment InfluxDB is ideal for IoT sensor data, application metrics, real-time analytics, DevOps monitoring, and any use case involving time-stamped measurements. ## Connecting To connect to InfluxDB in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select InfluxDB as the database type and enter: - Host/Server address - Port (default: 8181 for InfluxDB 3.0) - API Token for authentication - Database name - Enable SSL/TLS if required 4. **Connect**: Click save to connect to your InfluxDB instance. 5. **Start Managing Your Data**: Browse measurements and run SQL queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## InfluxDB Features in DBCode DBCode enhances your InfluxDB development experience with: - **SQL query editor**: Write and execute SQL queries with syntax highlighting - **Measurement browsing**: Navigate through databases and measurements - **Column type information**: View field types and tag keys - **Query results visualization**: View and export query results - **Time-series data display**: Optimized display for time-stamped data By using InfluxDB with DBCode, you can efficiently explore your time-series data, develop queries, and analyze metrics directly within Visual Studio Code. For more information about InfluxDB, check out InfluxDB. --- ## Docs > Supported Databases > Kafka ### Apache Kafka Message Queue Management in VS Code ## Overview Apache Kafka is a distributed event streaming platform capable of handling trillions of events a day. Key characteristics include: - **High-throughput messaging**: Process millions of events per second with low latency - **Durability and reliability**: Persistent message storage with configurable replication - **Horizontal scalability**: Scale across brokers and partitions - **Stream processing**: Built-in support for real-time stream processing - **Ordering guarantees**: Per-partition message ordering Kafka is ideal for event-driven architectures, data pipelines, log aggregation, and real-time analytics. ## Connecting To connect to Apache Kafka in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Apache Kafka as the database type and enter: - Bootstrap broker host and port (default: 9092) - Authentication method (No Auth, SASL/PLAIN, SCRAM-SHA-256, SCRAM-SHA-512) - TLS configuration, including CA trust and a client certificate/key if required 4. **Connect**: Click save to connect to your Kafka cluster. 5. **Start Browsing**: Navigate topics, view messages, and monitor consumer groups. For detailed instructions, refer to the [Connect](/docs/get-started/connect) article. ## Kafka Features in DBCode DBCode enhances your Kafka development experience with: - **Topic browsing**: Navigate topics with an approximate retained-offset span and expand for column details. This is not an exact message count - **Message inspection**: View messages with automatic JSON field expansion into columns - **Consumer group monitoring**: View group IDs and reported protocol types - **Message producing**: Insert messages via the standard DBCode grid interface - **Topic management**: Create and drop topics directly from the explorer - [Live Streaming](/docs/data/streaming): Subscribe to a topic to consume messages in real time. Right-click a topic and select **Subscribe** to open a streaming data grid that displays new messages as they arrive ## Browsing and Commands Opening a topic from the explorer shows its newest messages (the tail) across all partitions. Compressed topics are supported (gzip, Snappy, LZ4, and ZSTD). Kafka is command-based, not SQL: from a file or notebook connected to a Kafka connection you can run commands. `TOPICS` and `LIST` are equivalent commands that list all topics: ``` TOPICS LIST ``` Commands other than `TOPICS` and `LIST`, including SQL, return an error rather than running. SQL execution plans, updating or deleting individual messages, and SQL-session monitoring do not apply to Kafka connections. For more information about Kafka, visit kafka.apache.org. --- ## Docs > Supported Databases > Kingbase ### KingbaseES Database Management in VS Code KingbaseES is a commercial database built on PostgreSQL. Because it speaks the PostgreSQL wire protocol and exposes the PostgreSQL system catalogs, DBCode manages it through its PostgreSQL support. DBCode automatically detects the database's compatibility mode (PostgreSQL or Oracle) on connect, so both modes work without any extra configuration. ## Connecting To connect to KingbaseES, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose KingbaseES as the type, then enter the host, port (54321 by default), database, and credentials. 4. **Connect**: Click save to connect to your KingbaseES database. 5. **Start Managing Your Databases**: Once connected, you can browse schemas, run queries, and edit data directly from Visual Studio Code. For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. ## Kerberos / GSSAPI Authentication DBCode exposes **Integrated (Kerberos)** for KingbaseES connections when the server is configured to accept compatible GSSAPI or SSPI authentication. - Select **Integrated (Kerberos)** and enter the KingbaseES username that the Kerberos identity maps to. - On Windows, DBCode uses the current signed-in identity. On macOS and Linux, it uses an existing Kerberos ticket cache. - Integrated authentication requires a host/TCP connection. DBCode does not accept or manage keytabs. - The default **Kerberos Service Name** is `kingbase`. Change it only when the server administrator registered another service name. For more information about KingbaseES, check out KingbaseES. --- ## Docs > Supported Databases > Lancedb ### LanceDB Vector Database Management in VS Code ## Overview LanceDB is an open-source, embedded (in-process) vector database built on the [Lance](https://github.com/lancedb/lance) columnar data format. Highlights include: - **In-process, no server**: A database is a directory of Lance datasets on disk or in object storage - no service to run - **Object storage support**: Open LanceDB data from Amazon S3 or S3-compatible stores using DBCode AWS authentication profiles - **Built on the Lance format**: A fast, versioned columnar format designed for ML and vector workloads - **Strict schema**: Each table declares its columns (an Arrow schema), including the vector column (a fixed-size float list) - **SQL filtering**: Filter searches and browses with SQL expressions (evaluated by DataFusion) - **Native performance**: A prebuilt platform binary, downloaded on first connect LanceDB is commonly used for local-first semantic search, retrieval-augmented generation (RAG), and embedding-heavy applications that want embedded storage rather than a server. ## Connecting To connect to LanceDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select LanceDB as the database type, then choose **Local Directory** or **S3** storage. - For local storage, choose the **Database Directory** - the folder containing your Lance datasets. - For S3 storage, enter the `s3://bucket/path` URI and select an AWS authentication profile if you do not want LanceDB to use ambient AWS credentials. 4. **Connect**: Click save. The first connection downloads the platform binary for your OS. 5. **Start exploring**: Browse your tables, inspect the schema, and run vector searches. For detailed instructions, refer to the [Connect](/docs/get-started/connect) article. ## LanceDB Features in DBCode DBCode brings the same browse-and-search workflow you already use for SQL and document databases to LanceDB: - **Table browsing**: Navigate tables and inspect the declared Arrow schema (id, vector, and scalar columns) - **Vector cell rendering**: Vector columns are summarised inline (e.g. `[float32×768]`) and expandable on click - **Vector search**: Run nearest-neighbour searches with top-K, SQL filters, and a `_score` column (Lance returns a distance, so lower is closer) - **Editing**: Edit scalar columns inline and delete rows (the id and vector are read-only) - **Search by text**: Configure an Ollama model or DBCode AI to embed your query text on the fly (LanceDB has no built-in embedding) - **S3-compatible storage**: Connect to S3-compatible endpoints by setting an endpoint, region override, and HTTP allowance where needed - **JS shell editor**: Drop into a JavaScript editor and run the LanceDB client directly (`client.search('table', { vector, limit, where })`, `client.browse(...)`, `table('name')...`) By using LanceDB with DBCode, you get a unified workspace for traditional and vector data without leaving VS Code. For more information about LanceDB, check out LanceDB. --- ## Docs > Supported Databases > Libsql ### libSQL Database Management in VS Code ## Overview libSQL is a fork of SQLite with enhanced features for distributed, cloud-native applications. Key advantages include: - **SQLite compatibility**: Works with existing SQLite applications and tools - **Distributed architecture**: Built-in replication for high availability - **Edge-friendly**: Deploy databases close to your users for lower latency - **WebAssembly support**: Run directly in browsers and edge environments - **Enhanced security**: Built-in encryption for data protection libSQL combines SQLite's simplicity and efficiency with modern capabilities needed for cloud and edge deployments, making it ideal for applications that need a lightweight but robust database solution. ## Connecting To connect to libSQL in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: - Select libSQL as the database type - Choose local file or remote connection - For local files: Browse to your .db file - For remote: Enter URL and authentication token 4. **Connect**: Click save to connect to your libSQL database. 5. **Start Managing Your Databases**: Once connected, explore tables and execute queries. For detailed instructions on connecting to libSQL, refer to the [Connect](/docs/get-started/connect) article. ## Connect Multiple Databases Connecting to [Turso](/docs/cloud-providers/supported-providers/turso) as a cloud provider allows access to all hosted libSQL databases. To connect to multiple databases through Turso: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Your Provider**: Choose the Turso cloud provider from the list. 4. **Authenticate with Turso**: - Copy your authentication token from the Turso CLI or dashboard - Paste the token into the authentication field 5. **Explore Your Databases**: Browse all your libSQL instances in one interface. For detailed instructions on connecting to multiple libSQL databases, refer to the [Connect a Cloud Provider](/docs/cloud-providers/connect) article. ## libSQL Features in DBCode DBCode enhances your libSQL development experience with: - **SQLite compatibility**: Use familiar SQLite syntax with additional features - **Query history**: Track and reuse previous queries across instances By using libSQL with DBCode, you can leverage the simplicity of SQLite with distributed capabilities, all while working in your Visual Studio Code environment. For more information about libSQL, check out Turso. --- ## Docs > Supported Databases > Mariadb ### MariaDB Database Management in VS Code DBCode is a MariaDB extension for VS Code: connect, browse schemas and data, write queries with schema-aware autocomplete, and edit rows visually without switching tools. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview MariaDB is a community-developed, commercially supported fork of the MySQL relational database management system. It stands out with these distinctive advantages: - **Enhanced performance**: Optimized storage engines and query optimizer - **Greater storage engine support**: Including Aria, ColumnStore, Spider, and MyRocks - **Advanced features**: Window functions, common table expressions, and temporal data tables - **Stronger security**: Default encryption for tables, data, logs, and communications - **Open development model**: Community-driven with transparent governance MariaDB ensures MySQL compatibility while providing additional features, making it an excellent choice for organizations seeking a powerful, open-source database solution. ## Connecting To connect to MariaDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select MariaDB as the database type and enter: - Host address (default port: 3306) - Authentication credentials (username/password) - Database name (optional) - SSL/TLS settings (if required) 4. **Connect**: Click save to connect to your MariaDB database. 5. **Start Managing Your Databases**: Once connected, explore tables, views, and run queries. For detailed instructions on connecting to MariaDB, refer to the [Connect](/docs/get-started/connect) article. ## Connect Multiple Databases A number of cloud providers offer MariaDB as a service, including AWS RDS, Azure Database for MariaDB, and Google Cloud SQL. To connect to a cloud provider and access multiple databases: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Your Provider**: Choose the cloud provider from the list on the right. 4. **Authenticate**: Follow the authentication process specific to the provider. 5. **Start Managing Your Databases**: Once connected, you can manage multiple MariaDB instances. For detailed instructions on connecting to cloud providers, refer to the [Connect a Cloud Provider](/docs/cloud-providers/connect) article. ## DBCode Features for MariaDB With DBCode, you can perform these essential tasks when working with MariaDB: - **Data Browsing & Editing**: View and edit table data with an intuitive grid-based interface - **Schema Management**: Create, alter, and drop tables, views, and other database objects - **Procedure & Function Editor**: Create and edit stored procedures with syntax highlighting - **Data Import/Export**: Import data from CSV/JSON files and export query results - **Relationship Visualization**: View table relationships with interactive ER diagrams - **Query History**: Access and reuse your previously executed queries By using MariaDB with DBCode, you can leverage these powerful features within the familiar VS Code environment, streamlining your database development workflow. ## Advanced Connection Settings The **Advanced** section of the connection editor exposes pool tuning options alongside the existing **Editor Connection Idle Timeout** setting. ### Max Connections The maximum number of concurrent connections DBCode opens per database for this connection. The default is **10**. Lower this value when the server enforces a per-user connection limit (MariaDB `max_user_connections`). A lower ceiling serializes concurrent queries rather than returning an error when the limit is reached. ### Pool Idle Timeout How long an idle pooled connection is kept open before it is closed, in seconds. The default is **300** seconds. Lower this value to release connections sooner on servers with a tight connection limit. For more information about MariaDB, check out MariaDB. --- ## Docs > Supported Databases > Memcached ### Memcached Management in VS Code ## Overview Memcached is an open-source, high-performance, distributed memory object caching system. It is built for: - **Speed**: A simple in-memory key-value store with microsecond access times - **Simplicity**: A small, well-defined set of operations (get, set, delete, touch) - **Distribution**: Scales horizontally across many nodes - **Volatility**: Items expire or are evicted under memory pressure - Memcached is a cache, not a system of record Memcached is most commonly used to cache the results of database queries, API calls, and page rendering to reduce load and latency. ## Connecting To connect to Memcached in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Memcached as the database type and enter: - Host address (default port: 11211), or a unix socket path - Optional username / password (text-protocol auth) - Optional SSL/TLS configuration (host connections only) 4. **Connect**: Click save to connect to your Memcached server. For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. ## Memcached Features in DBCode DBCode connects over the Memcached text protocol and gives you: - **Key browsing**: Keys are listed via `lru_crawler metadump` and grouped by their `:` prefix into keyspaces, plus an "All Keys" view - **Item editing**: View and edit a key's value, TTL, and flags; create and delete keys - **Raw commands**: Run any Memcached command (`get`, `set`, `stats`, `flush_all`, and more) from the query editor - **Server stats**: Monitor connections, memory, hit rate, throughput, and slab allocation ## Notes and limitations Memcached is a cache, so a few behaviors differ from a traditional database: - **Key listing is a point-in-time snapshot.** Items can expire or be evicted between listing and reading, so a browse may not reflect every key, and very large caches are capped by the **Max Keys** connection setting. - **TTL semantics.** A TTL up to 30 days is stored as a relative offset; a larger value is converted to an absolute expiry timestamp. A TTL of 0 means "never expire". - **Authentication.** DBCode uses the text protocol (required for key browsing). Servers that require SASL authentication (binary protocol only) are not supported, because Memcached itself does not allow key enumeration over the SASL/binary protocol. For more information about Memcached, check out memcached.org. --- ## Docs > Supported Databases > Memgraph ### Memgraph Graph Database Management in VS Code ## Overview Memgraph is an in-memory graph database that excels at: - **Real-time performance**: In-memory architecture delivers millisecond query response times - **Cypher compatibility**: Full support for the Cypher query language (Neo4j compatible) - **Streaming analytics**: Native support for real-time data streaming with Kafka and Pulsar - **ACID compliance**: Full transactional support for data integrity - **Low latency**: Optimized for high-throughput, low-latency graph operations Memgraph is commonly used for real-time fraud detection, recommendation engines, network analysis, knowledge graphs, and any application requiring fast graph traversals on live data. ## Connecting To connect to Memgraph in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Memgraph as the database type and enter: - Host address (default port: 7687 for Bolt protocol) - Username and password - Database name (optional) - Optional SSL/TLS configuration 4. **Connect**: Click save to connect to your Memgraph database. 5. **Start Managing Your Data**: Once connected, begin exploring your graph data. For detailed instructions on connecting to Memgraph, refer to the [Connect](/docs/get-started/connect) article. ## Memgraph Features in DBCode DBCode enhances your Memgraph development experience with: - **Cypher query execution**: Write and execute Cypher queries with syntax highlighting - **Node and relationship browsing**: Explore your graph structure - **Label navigation**: Browse nodes organized by their labels - **Property inspection**: View and edit node and relationship properties By using Memgraph with DBCode, you can leverage the speed of in-memory graph processing while working within your familiar VS Code environment. For more information about Memgraph, check out Memgraph. --- ## Docs > Supported Databases > Milvus ### Milvus Vector Database Management in VS Code ## Overview Milvus is an open-source vector database built for production-scale similarity search and AI workloads. Highlights include: - **Scalable vector search**: Purpose-built indexes (HNSW, IVF, DiskANN, and more) for billions of vectors - **Strict schema**: Collections declare their fields up front, with typed scalar fields alongside vectors - **Expression filtering**: Filter searches with a rich boolean expression DSL (e.g. `price > 100 and tag == "news"`) - **Multi-vector collections**: Multiple vector fields per collection, each searchable independently - **Cloud or self-hosted**: Run locally with Docker, self-host the cluster, or use Zilliz Cloud Milvus is commonly used for semantic search, retrieval-augmented generation (RAG), recommendation systems, and any workload that needs high-throughput nearest-neighbour search at scale. ## Connecting To connect to Milvus in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Milvus as the database type and enter: - Host address (default port: 19530) - Username and password, or a Zilliz Cloud API key - Optional TLS for a secure gRPC channel (required by Zilliz Cloud) - Optional database and SSH tunnel 4. **Connect**: Click save to connect to your Milvus instance. 5. **Start exploring**: Browse your collections, inspect entities, and run vector searches. For detailed instructions, refer to the [Connect](/docs/get-started/connect) article. ## Milvus Features in DBCode DBCode brings the same browse-and-search workflow you already use for SQL and document databases to Milvus: - **Collection browsing**: Navigate collections and inspect the declared schema (typed scalar fields and vector fields) - **Vector cell rendering**: Vector columns are summarised inline (e.g. `[float32×768]`) and expandable on click - **Vector search**: Run nearest-neighbour searches with top-K, filter expressions, and a `_score` column - **Multi-vector support**: When a collection has multiple vector fields, pick which one to search - **Schema view**: Inspect a synthesised, read-only `CREATE COLLECTION` document with fields, indexes, and partitions - **Delete by key**: Remove records by primary key (Milvus does not support in-place field edits) - **Search by text**: Configure an Ollama model or DBCode AI to embed your query text on the fly - **JS shell editor**: Drop into a JavaScript editor and run the official Milvus client directly (`client.search(...)`, `client.query(...)`, etc.) By using Milvus with DBCode, you get a unified workspace for traditional and vector data without leaving VS Code. For more information about Milvus, check out Milvus. --- ## Docs > Supported Databases > Mongodb ### MongoDB Database Management in VS Code DBCode is a MongoDB extension for VS Code: browse collections, edit documents in a JSON editor that respects BSON types, run queries, and subscribe to change streams without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or read the [MongoDB in VS Code how-to guide](/how-to/mongodb-in-vscode). ## Overview MongoDB is a leading document-oriented NoSQL database that provides high performance, scalability, and flexibility for modern applications. Key advantages include: - **Schema flexibility**: Store documents with varying structures in the same collection - **Rich query language**: Powerful query capabilities including aggregation pipelines - **Horizontal scalability**: Easily distribute data across multiple servers with sharding - **High availability**: Built-in replication and automated failover - **Multi-model capabilities**: Work with documents, time series, geospatial data, and graphs MongoDB excels in handling large volumes of unstructured and semi-structured data, making it ideal for content management systems, mobile applications, IoT, and real-time analytics. ## Supported Authentication Methods DBCode supports MongoDB's authentication mechanisms, selectable under the connection's driver settings: - **Default / SCRAM-SHA-1 / SCRAM-SHA-256**: Username and password (SCRAM is MongoDB's default challenge-response auth) - **MONGODB-X509**: Certificate-based authentication using a client certificate - **PLAIN (LDAP)**: Delegate authentication to an external LDAP service - **GSSAPI (Kerberos)**: Single sign-on with a Kerberos ticket, no password required. Works on Windows (via SSPI), macOS, and Linux. On macOS and Linux you first obtain a ticket for your principal (for example with `kinit user@REALM`), then enter that principal as the username. Requires a Kerberos-enabled MongoDB deployment (MongoDB Enterprise). ## Connecting To connect to MongoDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select MongoDB as the database type and enter: - Connection string URI or individual connection parameters - Authentication mechanism and credentials - SSL/TLS settings (if required) - Additional connection options 4. **Connect**: Click save to establish your connection. 5. **Start Managing Your Data**: Explore databases, collections, and documents. For detailed instructions on connecting to MongoDB, refer to the [Connect](/docs/get-started/connect) article. ## Connecting to MongoDB Atlas MongoDB Atlas connections use the connection string from the Atlas dashboard: 1. **Get the connection string**: In Atlas, open your cluster, click **Connect**, and choose **Drivers**. Copy the `mongodb+srv://` connection string. 2. **Add a New Connection**: In DBCode, add a new MongoDB connection and paste the connection string, filling in your database user's password. 3. **Connect**: Click save to establish your connection. DBCode fully supports `mongodb+srv://` SRV connection strings, including TLS. ## MongoDB Features in DBCode DBCode enhances your MongoDB development experience with: - **JSON document editor**: Visually edit and validate document structures - **Schema analysis**: Understand document structure variations in collections - **BSON type support**: Work with MongoDB-specific data types - [Live Streaming](/docs/data/streaming): Subscribe to [Change Streams](https://www.mongodb.com/docs/manual/changeStreams/) on any collection to watch inserts, updates, and deletes in real time. Right-click a collection and select **Subscribe**, or run `db.collectionName.watch()` in the editor. Requires a replica set or sharded cluster By using MongoDB with DBCode, you can efficiently develop and manage your document databases directly within Visual Studio Code. ## Universal SQL Alongside the MongoDB shell, DBCode's query editor also accepts plain SQL. Any cell that starts with `SELECT`, `INSERT`, `UPDATE`, or `DELETE` (case-insensitive; comments above it are fine) runs as SQL against the current collection; anything else still runs as a shell command, unchanged. See [Query with SQL](/docs/query/universal-sql) for how the translation works across databases. ```sql SELECT name, email, status FROM users WHERE status = 'active' AND signupDate >= '2026-01-01' ORDER BY signupDate DESC LIMIT 20; ``` ```sql UPDATE users SET status = 'inactive' WHERE email = 'jane@example.com'; ``` Supported: `SELECT` (columns, `*`, or `COUNT(*)`) with `WHERE` (comparisons, `LIKE`/`ILIKE`, `IN`, `BETWEEN`, `IS [NOT] NULL`, `AND`/`OR`), `ORDER BY`, and `LIMIT`/`OFFSET`; single-row `INSERT`, `UPDATE`, and `DELETE`. String literals are compared using each field's introspected type, so date and other typed-field comparisons work as expected. Joins, `GROUP BY`, subqueries, functions, aliases, and parameters aren't supported yet - each returns a clear error naming the unsupported construct instead of running silently, and queries can't span multiple databases. `UPDATE`/`DELETE` statements without a `WHERE` clause go through the same confirmation (or deny) rules as SQL connections. ### Supported SQL | Statement | Support | |---|---| | `SELECT` (columns or `*`) | Yes | | `SELECT COUNT(*)` | Yes - can't combine with `ORDER BY` or `OFFSET` | | `INSERT` | Single row, column list required | | `UPDATE ... SET` | Yes | | `DELETE` | Yes | - **`WHERE`**: `=`, `!=`, `<>`, `>`, `>=`, `<`, `<=`; `LIKE` (`%text%`, `text%`, `%text`, or plain `text` for an exact match); `NOT LIKE` (`%text%`); `ILIKE` (case-insensitive); `IN (...)`; `BETWEEN`; `IS NULL`/`IS NOT NULL`; `AND`/`OR` with parentheses - **Ordering and paging**: `ORDER BY` runs server-side; `LIMIT` and `OFFSET` are both supported - **Comments**: `--`, `//`, and `#` are all recognized - String values compared against date fields use the collection's introspected types, so a literal like `'2026-01-01'` compares correctly against a real date field - String values compared against `_id` automatically match MongoDB `ObjectId`s - Queries can't reach another database (`db.collection`) - connect to that database instead Not yet supported: joins, `GROUP BY`/`HAVING`, `DISTINCT`, subqueries, CTEs, expressions or functions in `SELECT`, aliases, parameters, and `UNION` - each returns a clear error naming the construct, as noted above. For more information about MongoDB, check out MongoDB. --- ## Docs > Supported Databases > Motherduck ### MotherDuck Database Management in VS Code ## Overview MotherDuck is a collaborative data warehouse that extends the power of [DuckDB](/docs/supported-databases/duckdb) to the cloud. It combines the best of both worlds: - **Hybrid local-cloud processing**: Query local data or scale to the cloud seamlessly - **Serverless architecture**: No cluster management or infrastructure provisioning - **Collaborative features**: Share queries, tables and results with team members - **DuckDB compatibility**: Same intuitive SQL interface with cloud scalability - **Pay-for-use pricing**: Only pay for the compute and storage you actually use MotherDuck enables data analytics without the complexity of traditional data warehouses while maintaining the speed and simplicity of DuckDB. ## Connecting To connect to MotherDuck with DBCode, you'll need: 1. **Get a MotherDuck Access Token**: - Sign up or log in to your MotherDuck account - Go to the [dashboard settings page](https://app.motherduck.com/settings) - Generate and copy your service token 2. **Connect in DBCode**: - Open the DBCode Extension in Visual Studio Code - Click on the "Add Connection" icon - Choose MotherDuck as the database type - Paste your service token - Provide optional connection name and database path 3. **Start Analyzing Data**: Once connected, you can begin running queries across your local and cloud data. For detailed instructions on connecting to MotherDuck, refer to the [Connect](/docs/get-started/connect) article. ## MotherDuck Features in DBCode DBCode enhances your MotherDuck experience with: - **SQL query editor**: Write and execute queries with MotherDuck-specific syntax highlighting - **Data preview**: Quickly inspect sample data from tables in your MotherDuck database - **File import integration**: Easily load local CSV and other formats into MotherDuck - **Query performance visualization**: Understand and optimize your query execution - **Results export**: Save query results to local files in various formats By using MotherDuck with DBCode, you can harness the power of DuckDB in the cloud while working directly within your familiar VS Code environment. For more information about MotherDuck, check out MotherDuck. --- ## Docs > Supported Databases > Mysql ### MySQL Database Management in VS Code DBCode is a MySQL extension for VS Code: connect, browse schemas and data, write queries with schema-aware autocomplete, and edit rows visually without switching tools. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview MySQL is a widely used, open-source relational database management system (RDBMS) that provides a robust and reliable foundation for building and running complex applications. Known for its: - **Performance optimizations**: Fast query execution and caching mechanisms - **Reliability**: Proven stability across millions of deployments - **Scalability**: Support for very large databases and high-traffic applications - **Comprehensive transactional support**: ACID compliance with row-level locking - **Robust security**: Enterprise-grade authentication and encryption options MySQL powers many of the world's most visited websites and mission-critical applications with its combination of speed, reliability, and ease of use. ## Connecting To connect to MySQL in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select MySQL as the database type and enter: - Host address (default port: 3306) - Authentication credentials (username/password) - Database name (optional) - SSL configuration (if required) 4. **Connect**: Click save to connect to your MySQL database. 5. **Start Managing Your Database**: Browse tables, views, and stored procedures. For detailed instructions on connecting to MySQL, refer to the [Connect](/docs/get-started/connect) article. ## Connect Multiple Databases Many cloud providers offer MySQL as a managed service, including AWS RDS, Azure Database for MySQL, and Google Cloud SQL. To connect to a cloud provider and access multiple MySQL databases: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Your Provider**: Choose the appropriate cloud provider from the list. 4. **Authenticate**: Complete the authentication process specific to the provider. 5. **Start Managing Your Databases**: Access multiple MySQL instances through a unified interface. For detailed instructions on connecting to MySQL cloud services, refer to the [Connect a Cloud Provider](/docs/cloud-providers/connect) article. ## MySQL Features in DBCode DBCode enhances your MySQL development experience with: - **Visual stored procedure editor**: Create and edit procedures with syntax assistance - **Foreign key visualization**: Easily understand table relationships - **Data import/export tools**: Transfer data between MySQL databases By using MySQL with DBCode, you can efficiently develop, test, and manage your MySQL databases directly within Visual Studio Code. ## Advanced Connection Settings The **Advanced** section of the connection editor exposes pool tuning options alongside the existing **Editor Connection Idle Timeout** setting. ### Max Connections The maximum number of concurrent connections DBCode opens per database for this connection. The default is **10**. Lower this value when the server enforces a per-user connection limit (MySQL `max_user_connections`). A lower ceiling serializes concurrent queries rather than returning an error when the limit is reached. ### Pool Idle Timeout How long an idle pooled connection is kept open before it is closed, in seconds. The default is **300** seconds. Lower this value to release connections sooner on servers with a tight connection limit. For more information about MySQL, check out MySQL. --- ## Docs > Supported Databases > Neo4j ### Neo4j Graph Database Management in VS Code ## Overview Neo4j is a native graph database that excels at: - **Connected data queries**: Traverse relationships in milliseconds, regardless of data size - **Cypher query language**: Intuitive, pattern-based query language designed for graphs - **ACID compliance**: Full transactional support with enterprise-grade reliability - **Flexible schema**: Schema-optional design that adapts to evolving data models - **Scalability**: Supports billions of nodes and relationships Neo4j is commonly used for knowledge graphs, recommendation engines, fraud detection, network analysis, and any application where relationships between data are as important as the data itself. ## Connecting To connect to Neo4j in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Neo4j as the database type and enter: - Host address (default port: 7687 for Bolt protocol) - Username and password - Database name (optional, defaults to neo4j) - Optional SSL/TLS configuration 4. **Connect**: Click save to connect to your Neo4j database. 5. **Start Managing Your Data**: Once connected, begin exploring your graph data. For detailed instructions on connecting to Neo4j, refer to the [Connect](/docs/get-started/connect) article. ## Neo4j Features in DBCode DBCode enhances your Neo4j development experience with: - **Cypher query execution**: Write and execute Cypher queries with syntax highlighting - **Node and relationship browsing**: Explore your graph structure visually - **Label navigation**: Browse nodes organized by their labels - **Property inspection**: View and edit node and relationship properties By using Neo4j with DBCode, you can leverage the power of graph databases while working within your familiar VS Code environment. For more information about Neo4j, check out Neo4j. --- ## Docs > Supported Databases > Netezza ### Netezza Database Management in VS Code ## Overview IBM Netezza is a high-performance data warehousing appliance designed for analytics and business intelligence workloads. It's known for: - **High-performance analytics**: Massively parallel processing (MPP) architecture for fast query execution - **Scalability**: Handle petabyte-scale data warehouses with ease - **Simplicity**: Appliance-based design reduces administrative overhead - **SQL compatibility**: Standard SQL support with PostgreSQL-based foundation - **Optimized for analytics**: Purpose-built for complex analytical queries and large-scale data processing Netezza is ideal for organizations requiring fast analytics on large datasets, data warehousing, and business intelligence applications. ## Connecting To connect to Netezza in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Netezza as the database type and enter: - Host address (default port: 5480) - Authentication credentials (username/password) - Database name - SSL options (if required) 4. **Connect**: Click save to connect to your Netezza database. 5. **Start Managing Your Database**: Once connected, explore schemas, tables, and run queries. For detailed instructions on connecting to Netezza, refer to the [Connect](/docs/get-started/connect) article. ## DBCode Features for Netezza With DBCode, you can perform these essential tasks when working with Netezza: - **Schema Browser**: Navigate through databases, schemas, tables, and views - **Data Editing**: Edit table data with support for Netezza data types - **Query Execution**: Run analytical queries with full SQL support - **Bulk Data Import/Export**: Import from CSV, Excel, and JSON files By using Netezza with DBCode, you can streamline your data warehouse development workflow within the familiar VS Code environment, making complex analytical tasks more accessible. For more information about Netezza, check out IBM Netezza. --- ## Docs > Supported Databases > Opensearch ### OpenSearch Database Management in VS Code ## Overview OpenSearch is a community-driven, open source search and analytics suite derived from Elasticsearch 7.10.2. Key characteristics include: - **Full-text search**: Powerful text analysis and search capabilities with relevance scoring - **Real-time analytics**: Analyze and visualize data as it arrives - **Distributed architecture**: Horizontally scalable with automatic sharding and replication - **SQL support**: Query data using familiar SQL syntax via the SQL plugin - **Schema-free JSON documents**: Store and index semi-structured data without predefined schemas - **RESTful API**: Simple HTTP-based interface for all operations - **Open source**: Apache 2.0 licensed with active community development OpenSearch is ideal for log analytics, application search, security analytics, observability, and any use case requiring fast, scalable search and analytics. ## Connecting To connect to OpenSearch in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select OpenSearch as the database type and enter: - Host/Server address - Port (default: 9200) - Username and Password (if using basic authentication) - Or select an AWS IAM authentication profile for Amazon OpenSearch Service - Enable SSL/TLS if required 4. **Connect**: Click save to connect to your OpenSearch cluster. 5. **Start Managing Your Data**: Browse indices and run SQL queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ### Amazon OpenSearch Service DBCode supports connecting to Amazon OpenSearch Service using AWS IAM authentication: 1. Create an AWS IAM authentication profile in DBCode 2. Select "Auth Profile" as the authentication method 3. Choose your AWS IAM profile 4. Optionally specify the AWS region (defaults to profile region) 5. Select the service type: - **Amazon OpenSearch Service**: For managed OpenSearch domains - **Amazon OpenSearch Serverless**: For serverless collections ## OpenSearch Features in DBCode DBCode enhances your OpenSearch development experience with: - **SQL query editor**: Write and execute OpenSearch SQL queries with syntax highlighting - **Index browsing**: Navigate through indices and their field mappings - **Field type information**: View field types and nested object structures - **Query results visualization**: View and export query results - **Index mapping inspection**: View the complete mapping (schema) of any index By using OpenSearch with DBCode, you can efficiently explore your indices, develop SQL queries, and analyze data directly within Visual Studio Code. For more information about OpenSearch, check out OpenSearch. --- ## Docs > Supported Databases > Oracle ### Oracle Database Management in VS Code DBCode is an Oracle extension for VS Code: connect to Oracle Database, browse schemas and data, write SQL with schema-aware autocomplete, and edit rows visually without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Oracle is a relational database management system (RDBMS). It is designed to handle large volumes of data and is widely used in enterprise applications. Oracle provides a range of features and capabilities, including support for complex queries, indexing, and geospatial data. ## Supported Connection Methods DBCode supports the following connection methods for Oracle: - Thin Client - Instant Client/Thick Client ## Connecting To connect to Oracle, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Oracle as the type, and enter the required information. 4. **Connect**: Click save to connect to your Oracle database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to Oracle, refer to the [Connect](/docs/get-started/connect) article. ## Debugging DBCode can debug deployed standalone Oracle procedures and functions with the native VS Code debugger. It uses Oracle's classic `SYS.DBMS_DEBUG` package and currently requires a node-oracledb **Thin mode** connection. Thick or Instant Client connections can still run ordinary queries, but they cannot start an Oracle debug session. See [Debugger](/docs/query/debugger) for how to start a session, set breakpoints, step, inspect the call stack, and use watches. ### Prepare the database user The connected user needs `DEBUG CONNECT SESSION`. A database administrator can grant it according to the site's access policy: ```sql GRANT DEBUG CONNECT SESSION TO YOUR_USER; ``` For a routine owned by another schema, the connected user also needs effective `EXECUTE` and `DEBUG` privileges on that exact object: ```sql GRANT EXECUTE ON TARGET_SCHEMA.YOUR_PROCEDURE TO YOUR_USER; GRANT DEBUG ON TARGET_SCHEMA.YOUR_PROCEDURE TO YOUR_USER; ``` The routine owner does not need these object grants for its own routine. DBCode checks the effective setup before launch. It never grants privileges or recompiles a routine automatically. ### Compile the routine for debugging The exact deployed procedure or function must report the first two settings, and `PLSCOPE_SETTINGS` must include `IDENTIFIERS:ALL`: - `PLSQL_DEBUG=TRUE` - `PLSQL_OPTIMIZE_LEVEL=1` - `PLSCOPE_SETTINGS` includes `IDENTIFIERS:ALL` For a procedure, compile it with: ```sql ALTER PROCEDURE YOUR_SCHEMA.YOUR_PROCEDURE COMPILE DEBUG PLSQL_OPTIMIZE_LEVEL=1 PLSCOPE_SETTINGS='IDENTIFIERS:ALL'; ``` Use `ALTER FUNCTION` for a function. Recompile after replacing the routine if its settings no longer match. `IDENTIFIERS:ALL` is required because classic `DBMS_DEBUG` reads a variable by name but does not enumerate Locals. DBCode uses PL/Scope metadata and the exact deployed source to build the complete supported scalar Locals list. ### Supported values and inspection Oracle debugging supports `IN`, `OUT`, and `IN OUT` parameters and function returns for these scalar families: | Oracle type | Argument format | |---|---| | `NUMBER` | Canonical decimal text with up to 38 digits, such as `-123.45` | | `VARCHAR2` | Text up to 32,767 UTF-8 bytes | | `BOOLEAN` | `true` or `false` | | `DATE` | `YYYY-MM-DDTHH:mm:ss` | | `TIMESTAMP` | `YYYY-MM-DDTHH:mm:ss.ffffff` with exactly six fractional digits | | `TIMESTAMP WITH TIME ZONE` | `YYYY-MM-DDTHH:mm:ss.ffffff+HH:mm` with a numeric offset | Use `(null)` in the argument panel for SQL `NULL`. A scalar column `%TYPE` declaration is supported when DBCode can resolve the exact column to one of the built-in families above. Debug Source is the exact `ALL_SOURCE` text published as a read-only document. Breakpoints, Continue, Step Over, Step Into, Step Out, nested call stacks, selected-frame Locals, bare-variable watches, results, and up to 1,000 lines of `DBMS_OUTPUT` per invocation are supported. Locals are read-only. A declared value that Oracle cannot read yet is shown as unavailable instead of being omitted. ### Current limits - Package routines, wrapped source, and Thick mode are not supported. - Records, collections, cursors, LOB streams, other structured values, and `TIMESTAMP WITH LOCAL TIME ZONE` are not supported. - Variable mutation is not supported. - A paused routine can hold transaction locks. Continue or stop the session when inspection is finished. - Stop is bounded while the extension host still owns its two Oracle sessions. If the extension host process is lost while the routine is actively running, the database work can continue until Oracle terminates the session or an administrator ends it. ## Troubleshooting Thin Client Errors DBCode uses the node-oracledb Thin mode by default. Some database versions require the Thick/Instant Client driver instead and the connection attempt fails with an error similar to: ``` NJS-138: connections to this database server version are not supported by node-oracledb in Thin mode ``` To switch the connection to the Instant Client/Thick mode: 1. Download the appropriate Oracle Instant Client package for your operating system from the [Oracle Instant Client downloads page](https://www.oracle.com/database/technologies/instant-client/downloads.html). 2. Extract the archive to a local folder that DBCode can access (for example `~/oracle/instantclient_19_x`). Keep the folder path handy. 3. Edit your Oracle connection in DBCode. In the connection form, change the driver to **Instant Client / Thick** and set the client library directory to the folder you extracted in the previous step (the folder that contains `libclntsh` on macOS/Linux or `oci.dll` on Windows). 4. Save the connection and reconnect. ### Linux-specific Setup On Ubuntu and other Linux distributions, the Oracle Instant Client requires additional dependencies. If VS Code crashes or restarts when connecting, install the required library and set up the environment variables: ```bash # Install the required library sudo apt-get update sudo apt-get install libaio1t64 # Create a symbolic link for compatibility (some Ubuntu versions) sudo ln -s /usr/lib/x86_64-linux-gnu/libaio.so.1t64 /usr/lib/x86_64-linux-gnu/libaio.so.1 ``` Add these lines to your `~/.bashrc` (adjust the path to match your Instant Client location): ```bash export ORACLE_HOME=/path/to/instantclient_23_8 export LD_LIBRARY_PATH=$ORACLE_HOME:$LD_LIBRARY_PATH export PATH=$ORACLE_HOME:$PATH ``` After editing `.bashrc`, restart your terminal or run `source ~/.bashrc`, then restart VS Code. **Note:** On older Ubuntu versions, the package may be named `libaio1` instead of `libaio1t64`. Try `libaio1` if `libaio1t64` is not available. By using Oracle with DBCode, you can connect to your Oracle databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Oracle, check out Oracle. --- ## Docs > Supported Databases > Parquet ### Parquet File Viewer and Editor in VS Code ## Overview DBCode lets you open and work with Apache Parquet files directly in VS Code. Browse columnar data with sorting and filtering, and run SQL queries against your Parquet files using DuckDB under the hood. ## Features - Open any `.parquet` file in the data grid - Sort, filter, and group data - Run SQL queries against Parquet data - View column statistics and metadata - Export to other formats (CSV, Excel, JSON) --- ## Docs > Supported Databases > Pglite ### PGlite Database Management in VS Code ## Overview PGlite is the full PostgreSQL engine compiled to WebAssembly, packaged so it runs anywhere Node or a browser runs. Inside DBCode it behaves like SQLite or DuckDB — embedded, single-process, no server to start — but with the SQL surface and feature set of Postgres 17. Highlights: - **Embedded Postgres**: Real `postgres` binary running in WASM. Same dialect, same catalogs, same `EXPLAIN`. - **Two storage modes**: In-memory (data discarded when the connection closes) or a persistent directory on disk. - **No external dependencies**: PGlite ships inside DBCode; nothing to install. - **Full Postgres feature set**: tables, partitions, views, materialized views, procedures, functions, sequences, triggers, row-level security, enum/composite types, generated columns, JSONB, arrays. PGlite is a great fit for prototypes, test fixtures, throw-away analysis, or shipping a Postgres-flavored database alongside a desktop app. ## Connecting To connect to a PGlite database in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click the "Add Connection" icon and choose **PGlite**. 3. **Pick a storage type**: - **In Memory** — fastest start; data is lost when the connection closes. Good for ad-hoc work and tests. - **Directory** — persists data to a folder on disk. Pick an empty directory for a new database, or an existing PGlite directory to reopen one. 4. **Connect**: Click save to establish your connection. 5. **Query away**: PGlite supports the same SQL you'd run against any Postgres 17 server. For detailed instructions on setting up connections, refer to the [Connect](/docs/get-started/connect) article. ## PGlite features in DBCode DBCode's PGlite driver supports: - **Full schema browser**: schemas, tables, partitions, views, materialized views, procedures, functions, sequences, types, triggers, indexes, and policies — discovered via the same v3 progressive introspection used by the standard Postgres driver. - **DDL scripting**: `CREATE` statements for every supported object, generated by `pg_dump` for tables and `pg_get_*def()` for routines, views, triggers, and indexes. - **Execution plans**: `EXPLAIN` and `EXPLAIN (ANALYZE, BUFFERS)` rendered in DBCode's plan visualizer. - **Row counts on demand**: PGlite has no autovacuum, so `pg_class.reltuples` stays at -1 until you ask for it. Toggle **Update Statistics** on the connection (Advanced → Introspection) to run `ANALYZE` automatically when you refresh a schema. ## Storage tips - **In-memory mode** is exactly what it sounds like - close the connection and the data is gone. Use it for scratch databases. - **Directory mode** writes a full Postgres data directory at the path you choose. Back it up like you would any Postgres `PGDATA` folder. - **Don't share a directory between concurrent connections.** PGlite is single-process; opening the same directory from two clients at once will conflict. ## Limitations A few things real Postgres has that embedded PGlite does not: - **No foreign data wrappers** (FDW) — there's no extension loader, so external tables and foreign servers aren't available. - **No logical replication / publications / subscriptions.** - **No autovacuum** — see the **Update Statistics** toggle above for live row counts. - **Single connection** — PGlite serializes all queries through one WASM instance. For more information about PGlite, check out pglite.dev. --- ## Docs > Supported Databases > Pinecone ### Pinecone Vector Database Management in VS Code ## Overview Pinecone is a fully managed, cloud-native vector database designed for high-performance similarity search at scale. Highlights include: - **Fully managed**: No servers to run; the control plane lives at api.pinecone.io and each index has its own data-plane host - **Serverless and pod-based indexes**: Pay-as-you-go serverless indexes or dedicated pods - **Metadata filtering**: Combine vector similarity with structured metadata filters (`$eq`, `$gt`, `$in`, ...) - **Namespaces**: Partition records within an index for multi-tenancy; each query targets a single namespace - **Simple data model**: Each record has an id, a vector (`values`), and optional metadata Pinecone is commonly used for semantic search, retrieval-augmented generation (RAG), recommendations, and AI assistants that need fast nearest-neighbour lookups over large vector sets. ### How Pinecone maps into DBCode Pinecone has two containers above records, so DBCode mirrors its [MongoDB](/docs/supported-databases/mongodb/mongodb) layout: - A Pinecone **index** appears as a **database** (it owns the vector dimension and distance metric) - A Pinecone **namespace** appears as a **collection** you can browse and search - Each **record** has an `id`, a `values` vector, and metadata fields Because queries in Pinecone never cross namespaces, browse and search always operate on a single namespace at a time. ## Connecting To connect to Pinecone in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Pinecone as the database type and enter: - Your Pinecone **API key** (found in the [Pinecone console](https://app.pinecone.io)). There is no host or port - Pinecone resolves index hosts automatically. - Optionally pick a default **Index** (you can also expand any index in the tree). 4. **Connect**: Click save to connect to your Pinecone project. 5. **Start exploring**: Expand an index to see its namespaces, inspect records, and run vector searches. For detailed instructions, refer to the [Connect](/docs/get-started/connect) article. ## Pinecone Features in DBCode DBCode brings the same browse-and-search workflow you already use for SQL and document databases to Pinecone: - **Index and namespace browsing**: Navigate indexes (databases) and their namespaces (collections), and inspect the metadata shape - **Vector cell rendering**: Vector columns are summarised inline (e.g. `[float32×1536]`) and expandable on click - **Vector search**: Run nearest-neighbour searches with top-K, metadata filters, and a `_score` column - **Metadata editing**: Edit metadata fields inline and delete records; the id and vector are read-only - **Search by text**: Configure an Ollama model or DBCode AI to embed your query text on the fly (Pinecone has no usable server-side embedding for standard indexes) - **JS shell editor**: Drop into a JavaScript editor and run the Pinecone client directly (`client.search(...)`, `client.browse(...)`, `client.fetch(...)`, `client.listIndexes()`) :::note Browsing records uses Pinecone's id listing, which is available on **serverless** indexes. On pod-based indexes, use vector search to explore records. ::: By using Pinecone with DBCode, you get a unified workspace for traditional and vector data without leaving VS Code. For more information about Pinecone, check out Pinecone. --- ## Docs > Supported Databases > Pinot ### Apache Pinot Real-Time Analytics in VS Code ## Overview Apache Pinot is a real-time distributed OLAP datastore built for low-latency, high-throughput analytics. Key characteristics include: - **Sub-second query latency**: Optimized for user-facing analytical queries at scale - **Real-time and batch ingestion**: Stream data from Kafka, Pulsar, or Kinesis alongside batch loads from HDFS, S3, or Spark - **Columnar storage with rich indexing**: Inverted, StarTree, range, text, JSON, and geospatial indexes - **Horizontal scalability**: Scales to petabytes of data across distributed clusters - **SQL query interface**: Full SQL support via Apache Calcite with multi-stage query engine for JOINs Pinot is ideal for user-facing analytics dashboards, real-time business intelligence, metrics APIs, anomaly detection, and high-concurrency analytical workloads. ## Connecting To connect to Apache Pinot in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Apache Pinot as the database type and enter: - Controller host and port (default: 9000) - Broker host and port (optional, auto-discovered from controller) - Username and password (if authentication is enabled) 4. **Connect**: Click save to connect to your Pinot cluster. 5. **Start Exploring**: Browse tables, view schemas, and run analytical queries. :::note When connecting through an SSH tunnel, fill in **Broker Port** if your broker is not on the default 8000. ::: For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## Apache Pinot Features in DBCode DBCode enhances your Apache Pinot experience with: - **Table browsing**: Navigate tables with type indicators (OFFLINE, REALTIME, HYBRID) and column details showing dimension, metric, and dateTime field categories - **SQL query editor**: Write and execute Pinot SQL queries with syntax highlighting using the multi-stage query engine - **Schema inspection**: View table configurations and schema definitions as formatted JSON - **Data exploration**: Preview and export data from Pinot tables - **Table management**: Drop tables and reload segments directly from the explorer By using Apache Pinot with DBCode, you can efficiently explore and query your real-time analytics data directly within Visual Studio Code. For more information about Apache Pinot, visit pinot.apache.org. --- ## Docs > Supported Databases > Postgres ### PostgreSQL Database Management in VS Code DBCode is a PostgreSQL extension for VS Code: connect to local Postgres or cloud providers like Neon and Supabase, browse schemas and data, write SQL with schema-aware autocomplete, and edit rows visually without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview PostgreSQL is a powerful, open-source relational database management system (RDBMS) with over 30 years of active development. It's known for: - **Advanced features**: Robust support for JSON, full-text search, and geospatial data - **Extensibility**: Custom data types, functions, and procedural languages - **Strong standards compliance**: SQL standard compatibility and ACID compliance - **Concurrency**: Multi-version concurrency control (MVCC) for high performance - **Community support**: Large ecosystem of extensions and tools PostgreSQL is the preferred choice for applications requiring data integrity, complex queries, and handling large datasets, from small projects to enterprise systems. ## Connecting To connect to PostgreSQL in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select PostgreSQL as the database type and enter: - Host address (default port: 5432) - Authentication method and PostgreSQL username - Password when using username/password authentication - Database name - SSL options (if required) 4. **Connect**: Click save to connect to your PostgreSQL database. 5. **Start Managing Your Database**: Once connected, explore schemas, tables, and run queries. For detailed instructions on connecting to PostgreSQL, refer to the [Connect](/docs/get-started/connect) article. ## Kerberos / GSSAPI Authentication DBCode can authenticate to compatible PostgreSQL servers with your current operating-system credential. Select **Integrated (Kerberos)** instead of entering a database password. - On Windows, DBCode uses the current signed-in identity through the Kerberos SSP. It does not use Negotiate or fall back to NTLM. - On macOS and Linux, obtain a ticket before connecting, for example with `kinit user@REALM`. DBCode uses the existing ticket cache and does not acquire a ticket for you. - PostgreSQL still requires a username in its startup message. Enter the database role that your server maps the Kerberos identity to. - Integrated authentication requires a host/TCP connection. It is not available for Unix sockets. - DBCode does not accept or manage keytabs. Ticket and service-account setup stays with your operating system and environment administrator. ### Server and connection setup 1. Ask the environment administrator to configure PostgreSQL `gss` or Windows `sspi` authentication in `pg_hba.conf`, register the exact service principal name (SPN) to the PostgreSQL service account, and map the Kerberos identity to a database role. 2. Use the server's DNS hostname in **Host**. On Windows, DBCode uses the `postgres/` SSPI target. On macOS and Linux, it passes `postgres@` as the GSS host-based service target, which corresponds to a registered Kerberos service principal such as `postgres/@REALM`. Change **Kerberos Service Name** only when the administrator registered PostgreSQL under another service name. 3. Select **Integrated (Kerberos)** and enter the mapped PostgreSQL username. 4. Leave **Kerberos Principal** empty to use the default ambient credential. On macOS and Linux you can select another principal that already exists in the credential cache. This setting does not run `kinit` or acquire a ticket. Explicit principal selection is not supported on Windows. 5. Configure SSL/TLS normally. Kerberos authenticates the user, while TLS encrypts the connection. Full certificate verification also verifies the server certificate chain and hostname; trust-certificate mode does not verify server identity. When using an SSH tunnel, keep **Host** set to the remote PostgreSQL hostname. DBCode routes the TCP connection through the local tunnel while retaining the remote hostname for the SPN and, when full TLS verification is enabled, the certificate hostname check. DBCode does not expose GSS encrypted transport or `gssencmode`. The native binding cannot verify per-record confidentiality, so use SSL/TLS when the connection must be encrypted. ### Debugger and client tools Integrated authentication is used for ordinary pooled connections and for the PostgreSQL debugger's readiness, target, proxy, and stop/control connections. Each physical connection creates its own Kerberos context and does not reuse a password. Table DDL, backup, and restore operations run through local PostgreSQL client tools (`pg_dump`, `pg_restore`, and `psql`). For integrated authentication: - Install PostgreSQL 16 or newer client tools with GSSAPI or SSPI support. - DBCode disables password prompts and requires a GSSAPI server authentication request, while preserving the connection's TLS verification mode. - These operations always use the default ambient credential. If the connection selects an explicit principal, clear it before running table DDL, backup, or restore. - On Windows, the server must use PostgreSQL GSSAPI authentication for these tool operations. DBCode rejects the client tools' server-side SSPI path because it can use Negotiate and NTLM. ### Troubleshooting | Error or symptom | What to check | | --- | --- | | Kerberos context initialization fails | Confirm the current ticket with `klist`, the realm and DNS configuration, and the exact service SPN. | | PostgreSQL rejects the mapped role | Check the username, `pg_hba.conf`, `pg_ident.conf`, and the server's identity mapping. | | Principal selection fails on Windows | Clear **Kerberos Principal**. Windows uses only the current signed-in identity. | | Client tools require PostgreSQL 16 or newer | Install newer `pg_dump`, `pg_restore`, and `psql` tools, then retry. | | Client tools report no GSSAPI or SSPI support | Install a PostgreSQL client build that includes integrated authentication support. | | TLS hostname verification fails | Connect with the DNS hostname present in the server certificate instead of a local tunnel address or IP alias. | | Integrated authentication is unavailable | Switch from a socket to a PostgreSQL host/TCP connection and confirm that **Integrated (Kerberos)** is available in the authentication options. | ## Connect Multiple Databases A number of cloud providers offer PostgreSQL as a service, including AWS RDS, Azure Database for PostgreSQL, and Google Cloud SQL. To connect to a cloud provider and access multiple databases: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Your Provider**: Choose the cloud provider from the list on the right. 4. **Authenticate**: Follow the authentication process specific to the provider. 5. **Start Managing Your Databases**: Explore multiple PostgreSQL instances from a single connection. For detailed instructions on connecting to PostgreSQL cloud services, refer to the [Connect a Cloud Provider](/docs/cloud-providers/connect) article. ## DBCode Features for PostgreSQL With DBCode, you can perform these essential tasks when working with PostgreSQL: - **Schema Browser**: Navigate through databases, schemas, tables, views, and extensions - **Data Editing**: Edit table data with full support for PostgreSQL data types including JSON/JSONB - **Stored Procedure Management**: Create and edit functions in SQL, PL/pgSQL, Python, and other languages - **Bulk Data Import/Export**: Import from CSV, Excel, and JSON files with type conversion - [Live Streaming](/docs/data/streaming): Subscribe to PostgreSQL [LISTEN/NOTIFY](https://www.postgresql.org/docs/current/sql-listen.html) channels to receive real-time events in the data grid. Right-click a channel or run `LISTEN channel_name;` in the editor ## Debugging DBCode can debug PL/pgSQL functions and procedures with breakpoints, stepping, variables, and watches, using the native VS Code debug UI. See [Debugger](/docs/query/debugger) for what the debugger does and how a session works; this section covers what a PostgreSQL server needs before it can be used. Debugging is built on the `pldebugger` plugin, which is maintained alongside PostgreSQL and ships as a standard package on most distributions. Three things have to be in place. ### 1. Load the plugin_debugger plugin The plugin has to be loaded when the server starts, so it must be listed in `shared_preload_libraries`. Install the package for your server version first, for example on Debian or Ubuntu with the PostgreSQL APT repository: ```bash sudo apt-get install postgresql-17-pldebugger ``` Then add it to `postgresql.conf` and restart the server: ```ini shared_preload_libraries = 'plugin_debugger' ``` This setting can only be changed with a restart, and it is server-wide rather than per database. If you already load other libraries, add `plugin_debugger` to the existing comma-separated list rather than replacing it. On a managed or hosted PostgreSQL service you set the same thing through the provider's parameter settings (a parameter group, flag, or configuration page) instead of editing `postgresql.conf` directly, and apply the restart from the provider's console. Whether a given service exposes `plugin_debugger` and ships the package varies, so check your provider's documentation for the parameter and the available extensions. To confirm it is loaded: ```sql SHOW shared_preload_libraries; ``` ### 2. Install the pldbgapi extension The plugin exposes its API through an extension, which is created per database. Run this in each database you want to debug in: ```sql CREATE EXTENSION pldbgapi; ``` When the extension is available on the server but not yet created in the database you are connected to, DBCode offers to install it for you when you start a debug session, so you do not have to run this by hand. ### 3. Connect with a role that can debug Attaching a debugger to a routine requires the connected role to be a **superuser**, or the **owner** of the routine being debugged. This is enforced by PostgreSQL itself rather than by DBCode, and it cannot be granted: a `GRANT` on the routine does not make a role eligible. Be aware that the elevated roles offered by managed services (such as `rds_superuser`) are not true superusers, so a role holding one still needs to own the routine it is debugging. ### What can be debugged Only routines written in `LANGUAGE plpgsql` can be debugged, which covers PL/pgSQL functions and procedures. Routines in `sql`, `c`, or another language cannot be stepped through, and DBCode tells you which language it found instead of failing quietly. ### Checking the setup DBCode checks all three requirements when you start a debug session, so you do not have to work out which piece is missing. When everything passes, the session just starts. If the `pldbgapi` extension is available on the server but has not been created in the database you are connected to, DBCode offers to create it for you. Accept and the session carries on. Anything else stops the session with a message naming what is missing and what to do about it, along with a **Setup guide** button that opens this page. By using PostgreSQL with DBCode, you can streamline your database development workflow within the familiar VS Code environment, making complex database tasks more accessible. For more information about PostgreSQL, check out PostgreSQL. --- ## Docs > Supported Databases > Posthog ### PostHog Product Analytics in VS Code ## Overview PostHog is a product analytics platform that stores event, person, and session data in ClickHouse. Key characteristics include: - **HogQL query language**: PostHog's ClickHouse-flavored SQL dialect, queried through PostHog's own query API - **Virtual tables**: Every project exposes `events`, `persons`, `sessions`, and `groups`, plus any data warehouse tables and views you've connected in PostHog - **Cloud or self-hosted**: Connect to PostHog Cloud (US or EU) or your own self-hosted instance - **Read-only**: HogQL is SELECT-only, so there is no data editing DBCode connects to PostHog's query API using a personal API key, so you can explore your product analytics data with SQL without leaving Visual Studio Code. ## Connecting To connect to PostHog in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select PostHog as the database type and enter: - **Region**: US Cloud, EU Cloud, or Self-hosted (enter your instance URL) - **Personal API Key**: create one in PostHog under **Settings > Personal API Keys** with the `query:read`, `project:read`, and `organization:read` scopes, then paste it here 4. **Connect**: Click save to establish your connection. 5. **Start Exploring**: Projects appear as databases; pick one and start browsing tables. The `organization:read` scope lets DBCode list every project across every organization the key can reach, with the organization name shown next to each project in the picker. A key without that scope still works, but only sees its own project. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## PostHog Features in DBCode DBCode enhances your PostHog experience with: - **Schema browsing**: Browse `events`, `persons`, `sessions`, `groups`, and any data warehouse tables or views in the object tree - **SQL query editor**: Write and run [HogQL](https://posthog.com/docs/sql) with syntax highlighting, including `properties.foo` property access - **Compiled SQL**: See the ClickHouse SQL PostHog compiles your HogQL into, including the joins HogQL adds behind the scenes - **Data exploration**: Preview and export query results - **Query cancellation**: Long-running queries can be cancelled HogQL is SELECT-only, so PostHog connections are read-only: there is no insert, update, delete, or schema modification. By using PostHog with DBCode, you can explore your product analytics data with SQL directly within Visual Studio Code. For more information about PostHog, visit posthog.com. --- ## Docs > Supported Databases > Powerbi ### Power BI Semantic Models in VS Code ## Overview Power BI semantic models define tables, relationships, measures, calculations, and business rules for analytical queries. DBCode uses paginated Power BI REST calls to discover workspaces and semantic models, then uses the Arrow-based Execute DAX Queries API as its only query transport. Power BI Semantic Models is separate from DBCode's [Microsoft Fabric](/docs/supported-databases/fabric) driver: - **Power BI Semantic Models** queries semantic models with DAX and exposes model metadata. - **Microsoft Fabric** connects to relational Warehouse and Lakehouse SQL endpoints over TDS and uses T-SQL. One DBCode connection targets one Power BI workspace. Each semantic model in that workspace appears as a database. Semantic models do not expose queryable schemas, so their tables appear directly under the model. ## Prerequisites Before connecting, confirm that: - The semantic model is assigned to a supported Power BI capacity: Premium, Fabric, or Embedded. A [Fabric trial capacity](https://learn.microsoft.com/en-us/fabric/fundamentals/fabric-trial) can be used for evaluation. - A Power BI or Fabric administrator has enabled **Dataset Execute Queries REST API** and **Allow XMLA endpoints and Analyze in Excel with on-premises semantic models** in the tenant's Integration settings. See [Integration admin settings](https://learn.microsoft.com/en-us/fabric/admin/service-admin-portal-integration). - Your identity can discover the workspace and semantic model. Delegated credentials require the `Workspace.Read.All` scope documented by [Get Groups](https://learn.microsoft.com/en-us/rest/api/power-bi/groups/get-groups). Service principals use the Power BI tenant and workspace permissions described below. - Your identity has Read and Build permissions on the semantic model. See [Semantic model permissions](https://learn.microsoft.com/en-us/power-bi/connect-data/service-datasets-permissions). The Arrow-based API used by DBCode is available only for semantic models on capacity. Microsoft describes this requirement in the [Execute DAX Queries best practices](https://learn.microsoft.com/en-us/power-bi/developer/execute-dax-queries-arrow/best-practices). ## Connecting To connect: 1. Open DBCode and add a connection. 2. Select **Power BI Semantic Models**. 3. In VS Code, select **Microsoft Entra ID (Editor sign-in)**. **Microsoft Entra ID (Default credentials)** and compatible DBCode authentication profiles are also available. 4. Select a workspace. A connection is scoped to this one workspace. 5. Select a semantic model. DBCode treats it as the connection's database. 6. Save the connection and start exploring. Editor sign-in uses VS Code's built-in Microsoft authentication flow with DBCode's own Microsoft Entra application. It requests only the delegated `Workspace.Read.All` and `Dataset.Read.All` scopes needed by this driver. VS Code manages the token, and DBCode connects directly to Microsoft's Power BI APIs. Editor sign-in issues a token for your Microsoft account's default tenant. If the workspace lives in a tenant you only have guest access to, use an authentication profile with the **Tenant ID** field set instead. Default credentials support service principals, managed identities, and compatible Azure CLI credentials. The selected identity must be able to obtain a Power BI token and must have access to the workspace and semantic model. ### Authentication profiles DBCode authentication profiles can provide a compatible OAuth2 or command-sourced Power BI access token. This is useful when an organization already has a supported Power BI authentication flow that should remain outside the saved connection. For service principals, an administrator must enable the **Allow service principals to use Power BI APIs** tenant setting, and the service principal must be granted access to the target workspace and semantic model. Microsoft documents this requirement under the service principal limitations for [Execute DAX Queries in Group](https://learn.microsoft.com/en-us/rest/api/power-bi/datasets/execute-dax-queries-in-group). For general connection form guidance, see [Connect](/docs/get-started/connect). ## Features in DBCode - **DAX execution**: Run complete DAX queries against the selected semantic model. - **Multiple result sets**: A query with multiple `EVALUATE` statements produces a separate DBCode result set for each returned Arrow stream. - **Typed results**: Power BI's Apache Arrow response preserves numbers, dates, timestamps, booleans, strings, nulls, and other supported values for the DBCode results grid. - **Model browsing**: Browse tables directly under the semantic model, then load columns, measures, and relationships progressively as you explore. - **Locked progressive introspection**: The metadata loading strategy stays enabled so large models are not scanned eagerly. - **Hidden metadata**: Hidden tables, columns, and measures remain visible and are marked as hidden. Hidden state is model presentation metadata, not a permission boundary. - **Data exploration**: Preview table data and export query results. The [Execute DAX Queries in Group API](https://learn.microsoft.com/en-us/rest/api/power-bi/datasets/execute-dax-queries-in-group) supports one DAX query per request, with multiple `EVALUATE` statements in that query. ## Query behavior DBCode sends the complete DAX selection to Power BI unchanged. It does not split queries on semicolons or blank lines because both can appear inside valid formatted DAX. If a file contains several independent queries, select the query you want to run before executing it. A complete query can contain `DEFINE`, variables, comments, formatting, and multiple `EVALUATE` statements. ```dax DEFINE MEASURE 'Sales'[Average Order Value] = DIVIDE([Total Sales], [Order Count]) EVALUATE SUMMARIZECOLUMNS( 'Sales'[Region], "Average Order Value", [Average Order Value] ) ``` ## Troubleshooting ### HTTP 401 after the connection succeeds DBCode discovers workspaces and semantic models over the Power BI REST API, but runs metadata lookups and queries through the Arrow Execute DAX Queries API. The second API has stricter requirements than the first, so a connection can save and connect normally and then fail with `HTTP 401, code: Unauthorized` as soon as DBCode loads the model's tables. That combination points at the [Prerequisites](#prerequisites) rather than at sign-in. Check them in this order: 1. The semantic model is on Premium, Fabric, or Embedded capacity. A model on shared capacity appears in the model list and then rejects every query. 2. The **Dataset Execute Queries REST API** tenant setting is enabled, along with **Allow XMLA endpoints and Analyze in Excel with on-premises semantic models**. 3. Your identity has Build permission on the semantic model, not only Read. Read is enough to see the model but not to query it. ## Preview limitations Power BI Semantic Models support is in Preview: - Connections are read-only. DBCode does not create, update, refresh, or delete model objects or data. - DAX and DAX `INFO` functions are supported. SQL, MDX, DMV queries, and raw XMLA are not supported. - Cancelling a query stops DBCode's request and local result processing. Power BI might continue the server-side work until it completes or reaches the configured query timeout. For more information about the API and its supported query types, permissions, and limitations, see [Execute DAX Queries in Group](https://learn.microsoft.com/en-us/rest/api/power-bi/datasets/execute-dax-queries-in-group). --- ## Docs > Supported Databases > Qdrant ### Qdrant Vector Database Management in VS Code ## Overview Qdrant is a vector database and similarity search engine designed for production AI workloads. Highlights include: - **High-performance vector search**: HNSW indexing tuned for low-latency nearest-neighbour retrieval - **Rich payload filtering**: Combine vector similarity with structured filters on metadata - **Named multi-vectors**: Multiple embeddings per point (e.g. title and body) in a single collection - **Quantization options**: Scalar, product, and binary quantization for memory-efficient deployments - **Cloud or self-hosted**: Run locally with Docker, on-prem, or via Qdrant Cloud Qdrant is commonly used for semantic search, retrieval-augmented generation (RAG), recommendation systems, and any workload that needs to find "things similar to this" across millions of high-dimensional embeddings. ## Connecting To connect to Qdrant in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Qdrant as the database type and enter: - Host address (default port: 6333) - API key (for Qdrant Cloud or any auth-protected instance) - Optional SSL/TLS configuration - Optional SSH tunnel 4. **Connect**: Click save to connect to your Qdrant instance. 5. **Start exploring**: Browse your collections, inspect points, and run vector searches. For detailed instructions, refer to the [Connect](/docs/get-started/connect) article. ## Qdrant Features in DBCode DBCode brings the same browse-and-search workflow you already use for SQL and document databases to Qdrant: - **Collection browsing**: Navigate collections, see point counts, and inspect payload shape - **Vector cell rendering**: Vector columns are summarised inline (e.g. `[float32×384]`) and expandable on click - **Vector search**: Run nearest-neighbour searches with top-K, filters, and a `_score` column - **Multi-vector support**: When a collection has named multi-vectors, pick which vector to search - **Search by text**: Configure a Qdrant-managed embedder, an Ollama model, or DBCode AI to embed your query text on the fly - **JS shell editor**: Drop into a JavaScript editor and run the official Qdrant SDK directly (`client.search(...)`, `client.scroll(...)`, etc.) By using Qdrant with DBCode, you get a unified workspace for traditional and vector data without leaving VS Code. For more information about Qdrant, check out Qdrant. --- ## Docs > Supported Databases > Questdb ### QuestDB Database Management in VS Code ## Overview QuestDB is a high-performance time-series database designed for fast data ingestion and real-time analytics with key characteristics: - **High-speed ingestion**: Handles millions of rows per second with minimal hardware - **SQL support**: Query time-series data using standard SQL with time-series extensions - **Column-oriented storage**: Optimized for analytical queries on time-series data - **PostgreSQL wire protocol**: Compatible with PostgreSQL clients and tools - **Built-in web console**: Includes a web-based SQL editor and data visualization QuestDB is ideal for financial market data, IoT sensor data, application metrics, monitoring systems, and any time-series workloads requiring high throughput. ## Connecting To connect to QuestDB in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select QuestDB as the database type and enter: - Host/Server address - Port (8812 for PostgreSQL wire protocol) - Username (default: admin) - Password (default: quest) - Database name (optional, default is 'qdb') 4. **Connect**: Click save to connect to your QuestDB server. 5. **Start Managing Your Data**: Explore tables and run queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## QuestDB Features in DBCode DBCode enhances your QuestDB development experience with: - **SQL query editor**: Write and execute QuestDB SQL queries with syntax highlighting - **Time-series functions**: Use QuestDB's time-series specific functions like SAMPLE BY - **Schema browsing**: Navigate through tables and columns - **Query results visualization**: View and export query results By using QuestDB with DBCode, you can efficiently develop and test time-series queries and data transformations directly within Visual Studio Code. For more information about QuestDB, check out QuestDB. --- ## Docs > Supported Databases > R2sql ### Cloudflare R2 SQL Query Support in VS Code ## Overview R2 SQL is Cloudflare's serverless, distributed query engine for Apache Iceberg tables stored in [R2 Data Catalog](https://developers.cloudflare.com/r2/data-catalog/). DBCode connects directly to the R2 SQL API, so you can explore and query your data lake without exporting it to an external warehouse. - **Serverless queries**: SQL runs on Cloudflare's network next to your R2 storage; DBCode streams back the results - **Schema browsing**: namespaces, tables, and Iceberg column types in the object tree, fetched from the free catalog API - **EXPLAIN visualization**: graphical query plans via R2 SQL's `EXPLAIN FORMAT JSON` - **Read-only by design**: R2 SQL is a query engine; data is written by [Pipelines](https://developers.cloudflare.com/pipelines/) or other Iceberg engines ## API Token Authentication Create an R2 API token with **Admin Read only** (or Admin Read & Write) permissions, which covers all three reads R2 SQL needs: R2 storage, R2 Data Catalog, and R2 SQL. 1. In the Cloudflare dashboard, go to **R2 object storage** 2. Under **Account Details**, select **Manage** next to **API Tokens** 3. Create an Account API token with **Admin Read only** permission 4. Copy the token value If you scope a custom token instead of using **Admin Read only**, include **all three** permissions: **Workers R2 Storage - Read**, **Workers R2 Data Catalog - Read**, and **Workers R2 SQL - Read**. R2 SQL reads the underlying Iceberg data files with credentials that inherit your token's R2 storage permission, so a token missing R2 storage read can browse your buckets but returns a `Corrupted Catalog` error when you run a query. ## Connecting 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: - Select Cloudflare R2 SQL as the database type - Enter your API token, then pick your account from the dropdown - Optionally pick a catalog-enabled bucket from the dropdown, or leave it blank to see every catalog-enabled bucket in the account 4. **Connect**: Click save to establish your connection. 5. **Start Querying**: Query your Iceberg tables with SQL, for example `SELECT * FROM default.my_table LIMIT 100`. The connection covers your whole account: every catalog-enabled bucket appears underneath it as a database. You can also reach the same connection through the [Cloudflare cloud provider](/docs/cloud-providers/supported-providers/cloudflare). For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. For more information about R2 SQL, check out Cloudflare's documentation. --- ## Docs > Supported Databases > Rabbitmq ### RabbitMQ Message Broker Management in VS Code ## Overview RabbitMQ is a widely deployed open-source message broker that provides reliable messaging for distributed systems. Key characteristics include: - **Flexible routing**: Direct, fanout, topic, and header exchange types for complex message flows - **Reliability**: Message acknowledgment, persistence, and publisher confirms - **Multiple protocols**: AMQP 0-9-1, MQTT, and STOMP support - **Clustering and high availability**: Mirrored queues and quorum queues for fault tolerance - **Management interface**: Built-in HTTP API for monitoring and administration RabbitMQ is ideal for microservices communication, task queues, event distribution, and asynchronous processing. ## Connecting To connect to RabbitMQ in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select RabbitMQ as the database type and enter: - Host and port (default AMQP: 5672, management: 15672) - Username and password (default: guest/guest) - Virtual host if not using the default - SSL/TLS configuration if required 4. **Connect**: Click save to connect to your RabbitMQ broker. 5. **Start Browsing**: Navigate exchanges, queues, and bindings. For detailed instructions, refer to the [Connect](/docs/get-started/connect) article. ## RabbitMQ Features in DBCode DBCode enhances your RabbitMQ management experience with: - **Queue browsing**: View queues with message counts and consumer information - **Message peeking**: Inspect message content and properties without consuming - **Exchange topology**: Expand exchanges to see bound queues and routing keys - **Message publishing**: Publish messages via the standard DBCode grid interface - **Queue management**: Create and drop queues directly from the explorer - [Live Streaming](/docs/data/streaming): Subscribe to a queue to consume messages in real time. Right-click a queue and select **Subscribe** to open a streaming data grid that displays new messages as they arrive For more information about RabbitMQ, visit rabbitmq.com. --- ## Docs > Supported Databases > Ravendb ### RavenDB Database Management in VS Code ## Overview RavenDB is a high-performance, ACID-compliant NoSQL document database designed for modern applications. Key advantages include: - **ACID transactions**: Full transactional support across multiple documents and collections - **RQL query language**: SQL-like query syntax specifically designed for document databases - **Built-in indexing**: Automatic and manual indexes with full-text search capabilities - **Multi-model support**: Documents, time series, counters, and attachments in a single database - **High availability**: Distributed architecture with automatic failover and replication RavenDB excels at handling complex data models with its flexible document structure while maintaining strong consistency guarantees, making it ideal for enterprise applications, content management, and real-time systems. ## Connecting To connect to RavenDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select RavenDB as the database type and enter: - Host and port (default port is 8080) - Database name - Authentication method (None for development, Certificate for production) - SSL/TLS settings (if required) 4. **Connect**: Click save to establish your connection. 5. **Start Managing Your Data**: Explore databases, collections, and documents. For detailed instructions on connecting to RavenDB, refer to the [Connect](/docs/get-started/connect) article. ## RavenDB Features in DBCode DBCode enhances your RavenDB development experience with: - **RQL editor**: Write and execute RQL queries with auto-completion and syntax highlighting - **Document browser**: Navigate and edit JSON documents in collections - **Index management**: View auto-generated and manual indexes - **Query cancellation**: Cancel long-running queries when needed - [Live Streaming](/docs/data/streaming): Subscribe to collection changes in real time using the Changes API. Right-click a collection and select **Subscribe** to receive document change events as they happen By using RavenDB with DBCode, you can efficiently develop and manage your document databases directly within Visual Studio Code. For more information about RavenDB, check out RavenDB. --- ## Docs > Supported Databases > Redis ### Redis Database Management in VS Code DBCode is a Redis extension for VS Code: connect, browse keys, run commands, and subscribe to Pub/Sub channels live, all without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Redis is an open-source, in-memory data structure store that excels at: - **Lightning-fast operations**: Microsecond response times with in-memory architecture - **Versatile data structures**: Strings, hashes, lists, sets, sorted sets, streams, and more - **Pub/Sub messaging**: Built-in publish/subscribe messaging capabilities - **Persistence options**: RDB snapshots and AOF logs for data durability - **High availability**: Replication and Redis Sentinel support Redis is commonly used for caching, real-time messaging, session stores, leaderboards, and as a fast data structure server. ## Connecting To connect to Redis in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Redis as the database type and enter: - Host address (default port: 6379) - Authentication password (if enabled) - Optional SSL/TLS configuration 4. **Connect**: Click save to connect to your Redis database. 5. **Start Managing Your Data**: Once connected, begin exploring your Redis keys and data structures. For detailed instructions on connecting to Redis, refer to the [Connect](/docs/get-started/connect) article. ## Redis Features in DBCode DBCode enhances your Redis development experience with: - **Key browsing**: Easily navigate through your Redis keyspace - **Data structure visualization**: View hashes, lists, sets in a structured format - **TTL management**: Monitor and adjust key expiration times - **CLI access**: Run raw Redis commands directly from VS Code - [Live Streaming](/docs/data/streaming): Subscribe to Redis Pub/Sub channels to receive messages in real time. Right-click a database and select **Subscribe**, or run `SUBSCRIBE channel_name` in the query editor By using Redis with DBCode, you can leverage Redis's speed and flexibility while working within your familiar VS Code environment. For more information about Redis, check out Redis. --- ## Docs > Supported Databases > Redshift ### Redshift Database Management in VS Code DBCode is a Redshift extension for VS Code: connect to your cluster or serverless workgroup, browse schemas, run queries with schema-aware autocomplete, and chart results without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Amazon Redshift is a fully managed, petabyte-scale data warehouse service in the cloud that enables you to analyze all your data using standard SQL and your existing business intelligence tools. Key features include: - **Massively parallel processing**: Query performance across petabytes of data - **Columnar storage**: Optimized for analytical workloads with compression - **Query optimization**: Intelligent query execution and distribution - **Data lake integration**: Query data directly in Amazon S3 with Redshift Spectrum - **Machine learning capabilities**: ML predictions directly in the data warehouse Redshift is ideal for data warehousing, business intelligence, and complex analytical queries on large datasets. ## Connecting To connect to Amazon Redshift in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Redshift as the database type and enter: - Cluster endpoint (hostname and port, typically 5439) - Authentication credentials (username/password) - Database name - SSL settings (recommended for security) 4. **Connect**: Click save to connect to your Redshift cluster. 5. **Start Managing Your Data Warehouse**: Once connected, explore schemas, tables, and run analytical queries. For detailed instructions on connecting to Redshift, refer to the [Connect](/docs/get-started/connect) article. ## Redshift Features in DBCode DBCode enhances your Redshift development experience with: - **Distribution and sort key visualization**: Understand your table optimization - **Query performance analysis**: Identify bottlenecks and execution issues - **Cross-database querying**: Execute federated queries across Redshift and other data sources By using Redshift with DBCode, you can efficiently develop, test, and optimize analytical queries and data pipelines directly within Visual Studio Code. For more information about Amazon Redshift, check out Amazon Redshift. --- ## Docs > Supported Databases > Risingwave ### RisingWave Streaming Database Management in VS Code ## What is RisingWave? RisingWave is an open-source SQL streaming database designed for processing and analyzing real-time data streams at scale. Built with cloud-native architecture, RisingWave simplifies stream processing with standard SQL, enabling businesses to extract valuable insights from streaming data without the complexity of traditional streaming frameworks. ### Key Features - **SQL-Based Stream Processing**: Uses familiar SQL syntax for stream processing tasks - **Materialized Views**: Continuously updated views that reflect the latest state of your data streams - **Event Time Processing**: Process events based on when they occurred rather than when they arrived - **Scalable Architecture**: Easily scales horizontally to handle growing data volumes - **Exactly-Once Semantics**: Ensures reliable processing even in the face of failures - **Integration with Data Sources**: Connects seamlessly with Kafka, Pulsar, Redpanda, and other data systems - **Low-Latency Analytics**: Delivers millisecond-level insights on streaming data ## Common Use Cases - **Real-Time Analytics**: Monitor business metrics and KPIs as they change - **Anomaly Detection**: Identify unusual patterns in streaming data - **IoT Data Processing**: Process and analyze data from connected devices - **Financial Data Analysis**: Track market movements and trading patterns in real-time - **User Behavior Tracking**: Understand how users interact with applications ## Connecting To connect to RisingWave in VS Code using DBCode, follow these steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon in the sidebar. 3. **Complete the connection form**: - Select "RisingWave" as the database type - Enter your host address - Specify the port (default is `4566`) - Enter your username (default is `root`) - Enter your password if configured - Optionally specify a database name 4. **Save and Connect**: Click the save button to establish your connection. 5. **Start Managing Your Streaming Data**: Once connected, you can browse database objects, write and execute SQL queries, and visualize your streaming data results. For detailed instructions on connecting to RisingWave and other databases, refer to the [Connect](/docs/get-started/connect) article. ## Working with RisingWave in DBCode After connecting to RisingWave, you can: - Create and manage materialized views to continuously transform streaming data - Write SQL queries to analyze real-time data - Set up source connectors to ingest data from Kafka, Pulsar, and other systems - Create sinks to output processed data to external systems By using RisingWave with DBCode, you can connect to your streaming databases, query and manage your real-time data streams, and visualize your results, all directly from Visual Studio Code. For more information about RisingWave, check out RisingWave or visit their GitHub repository. --- ## Docs > Supported Databases > Salesforce ### Salesforce Database Management in VS Code ## Overview Salesforce is the world's leading CRM platform. DBCode allows you to connect to your Salesforce org and: - **Browse objects**: Explore standard and custom objects in your org - **Query data**: Write and execute SOQL queries - **View relationships**: See object relationships and field metadata - **Export data**: Export query results to various formats ## Prerequisites Before connecting, you need to create a **Connected App** in Salesforce. This is a one-time setup that takes about 5 minutes. ## Creating a Connected App 1. **Log in to Salesforce** and go to **Setup** (gear icon → Setup) 2. In the left sidebar, navigate to **Platform Tools** → **Apps** → **External Client Apps** 3. Click **Settings** and enable **Allow creation of connected apps** (if not already enabled) 4. Go back to **External Client Apps** and click **New Connected App** 5. Fill in the basic information: - **Connected App Name**: `DBCode` - **API Name**: `DBCode` (auto-fills) - **Contact Email**: Your email address 6. Under **API (Enable OAuth Settings)**: - Check **Enable OAuth Settings** - **Callback URL**: `http://localhost:9876/callback` - **Selected OAuth Scopes**: Add these scopes: - `Manage user data via APIs (api)` - `Perform requests at any time (refresh_token, offline_access)` - `Access unique user identifiers (openid)` - **Security settings** (important): - ✅ Keep **Require Proof Key for Code Exchange (PKCE)** enabled - ❌ Uncheck **Require Secret for Web Server Flow** - ❌ Uncheck **Require Secret for Refresh Token Flow** 7. Click **Save** 8. Wait 2-10 minutes for the Connected App to be provisioned 9. Go back to **External Client Apps**, find your app, and click to view it 10. Click **Manage Consumer Details** (you may need to verify your identity) 11. Copy the **Consumer Key** (this is your Client ID) ## Connecting in DBCode 1. **Open DBCode** and click **Add Connection** 2. Select **Salesforce** as the database type 3. Configure the connection: - **Instance URL**: - Production: `https://login.salesforce.com` - Sandbox: `https://test.salesforce.com` - Custom domain: `https://yourdomain.my.salesforce.com` - **API Version**: `59.0` (or your preferred version) 4. For **Authentication**, click **Create Auth Profile** 5. In the auth profile form: - **Client ID**: Paste the Consumer Key from your Connected App - Other fields are pre-filled for Salesforce 6. Click **Save** - your browser will open for Salesforce login 7. Log in to Salesforce and authorize the app 8. Return to VS Code - you're connected! ## Querying Data Salesforce uses **SOQL** (Salesforce Object Query Language), which is similar to SQL: ```sql -- Query accounts SELECT Id, Name, Industry FROM Account LIMIT 10 -- Query with relationships SELECT Id, Name, Account.Name FROM Contact WHERE Account.Industry = 'Technology' -- Aggregate queries SELECT COUNT(Id), Industry FROM Account GROUP BY Industry ``` ## Supported Features | Feature | Support | |---------|---------| | Browse objects | Yes | | SOQL queries | Yes | | View field metadata | Yes | | Export results | Yes | | Insert/Update/Delete | Yes | ## Troubleshooting ### "Invalid Client ID" error - Wait 2-10 minutes after creating the Connected App - Verify you copied the Consumer Key correctly ### "Callback URL mismatch" error - Ensure the callback URL is exactly `http://localhost:9876/callback` - Check for trailing slashes or typos ### "Access Denied" error - Your Salesforce user may not have API access - Contact your Salesforce admin to enable API access for your profile ## Resources - [Salesforce SOQL Documentation](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/) - [Connected App Documentation](https://help.salesforce.com/s/articleView?id=sf.connected_app_overview.htm) For more information about Salesforce, visit Salesforce. --- ## Docs > Supported Databases > Scylla ### ScyllaDB Database Management in VS Code ## Overview ScyllaDB is a high-performance NoSQL database compatible with Apache Cassandra. It's designed for low latency and high throughput, making it ideal for data-intensive applications. ScyllaDB uses the same CQL (Cassandra Query Language) interface, allowing seamless migration from Cassandra. ## Connecting To connect to ScyllaDB, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose ScyllaDB as the type, and enter the required information including host, port (default 9042), and optionally the local data center name. 4. **Connect**: Click save to connect to your ScyllaDB database. 5. **Start Managing Your Databases**: Once connected, you can start managing your keyspaces and tables directly from Visual Studio Code. For detailed instructions on connecting to ScyllaDB, refer to the [Connect](/docs/get-started/connect) article. ## Features - Browse and manage keyspaces - View and query tables - Execute CQL queries - Switch between keyspaces using USE command - Create and manage user-defined functions By using ScyllaDB with DBCode, you can connect to your ScyllaDB databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about ScyllaDB, check out ScyllaDB. --- ## Docs > Supported Databases > Singlestore ### SingleStore Database Management in VS Code ## Connecting To connect to SingleStore, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose SingleStore as the type, and enter the required information including host, port (default 3306), username, and password. 4. **Connect**: Click save to connect to your SingleStore database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to SingleStore, refer to the [Connect](/docs/get-started/connect) article. By using SingleStore with DBCode, you can connect to your SingleStore databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about SingleStore, check out SingleStore. --- ## Docs > Supported Databases > Snowflake ### Snowflake Database Management in VS Code DBCode is a Snowflake extension for VS Code: connect to your account, browse databases and schemas, run queries with schema-aware autocomplete, and chart results without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview Snowflake is a cloud-based data warehousing platform designed for the modern data needs with key characteristics: - **Cloud-native architecture**: Built from the ground up for the cloud - **Separation of storage and compute**: Scale resources independently as needed - **Multi-cluster shared data**: Query the same data concurrently without conflicts - **Cross-cloud compatibility**: Available on AWS, Azure, and Google Cloud - **Data sharing**: Securely share data without moving or copying it Snowflake is ideal for data warehousing, data lakes, data engineering, data science, data application development, and secure data sharing. ## Connecting To connect to Snowflake in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select Snowflake as the database type and enter: - Account identifier (e.g., xy12345.us-east-1.snowflakecomputing.com) - Authentication type (Username and Password, Key Pair, or Single sign-on) and the matching credentials - Role (optional) - Warehouse (the compute resource to use) - Database and schema (optional) 4. **Connect**: Click save to connect to your Snowflake account. 5. **Start Managing Your Data**: Explore databases, schemas, tables, and run queries. For detailed instructions on connecting to Snowflake, refer to the [Connect](/docs/get-started/connect) article. ## Authentication DBCode supports three authentication types for Snowflake. Pick one from the **Authentication Type** dropdown when you create or edit the connection. ### Username and Password Enter your Snowflake username and password. If your account enforces MFA, you are prompted on the first connection and DBCode caches the MFA token so you are not challenged again on every query. For the cached token to persist, your Snowflake account must allow MFA token caching: ```sql ALTER ACCOUNT SET ALLOW_CLIENT_MFA_CACHING = TRUE; ``` If caching is disabled on the account, each new connection has to re-authenticate. ### Key Pair Key pair authentication uses a private key instead of a password, so there is no browser prompt and no MFA challenge per query. This is the best option when MFA or SSO would otherwise interrupt every statement. 1. Generate a key pair and assign the public key to your Snowflake user. See Snowflake's key-pair authentication guide. 2. Set **Authentication Type** to **Key Pair**. 3. Enter your **Username**. 4. Select your **Private Key** file (the PEM-encoded private key, usually a `.p8` file). 5. If the key is encrypted, enter the **Private Key Passphrase**. ### Single Sign-On (SSO) DBCode supports Snowflake's browser-based SSO authentication, including identity providers such as Okta. When using SSO, the extension opens your default browser for authentication. DBCode caches the SSO token so you are not signed in repeatedly across connections. For the token to persist, your Snowflake account must allow ID token caching: ```sql ALTER ACCOUNT SET ALLOW_ID_TOKEN = TRUE; ``` If this is disabled on the account, every new connection has to sign in through your identity provider again. This account setting is controlled by your Snowflake administrator, not DBCode. #### Dev Container Support When using SSO authentication in dev containers or remote environments, you may want to use a fixed port for the authentication callback instead of a random port. This simplifies port forwarding configuration. Set the `SF_AUTH_SOCKET_PORT` environment variable to specify a fixed port: ```bash export SF_AUTH_SOCKET_PORT=8765 ``` Then configure your dev container to forward this port in `.devcontainer/devcontainer.json`: ```json "forwardPorts": [8765] ``` If `SF_AUTH_SOCKET_PORT` is not set, the Snowflake SDK uses a random available port (default behavior). ## Snowflake Features in DBCode DBCode enhances your Snowflake development experience with: - **Query profiling**: Visualize query execution plans and performance metrics - **Data preview**: Quickly view sample data from large tables - **Schema browsing**: Navigate through databases, schemas, tables, and views By using Snowflake with DBCode, you can efficiently develop and test data pipelines, analytical queries, and data transformations directly within Visual Studio Code. For more information about Snowflake, check out Snowflake. --- ## Docs > Supported Databases > Spanner ### Google Cloud Spanner Database Management in VS Code ## Connecting To connect to Google Cloud Spanner, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Google Cloud Spanner as the type, and enter the required information. 4. **Connect**: Click save to connect to your Google Cloud Spanner database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to Google Cloud Spanner, refer to the [Connect](/docs/get-started/connect) article. By using Google Cloud Spanner with DBCode, you can connect to your Spanner databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about Google Cloud Spanner, check out Google Cloud Spanner. --- ## Docs > Supported Databases > Sqlite ### SQLite Database Management in VS Code DBCode is a SQLite extension for VS Code: open local database files, browse tables and data, run SQL with schema-aware autocomplete, and edit rows visually, all inside your editor with no server to set up. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview SQLite is a self-contained, serverless relational database management system (RDBMS) that provides a lightweight and efficient solution for local data storage. Key advantages include: - **Zero configuration**: No server setup or administration required - **Portable**: The entire database is stored in a single cross-platform file - **Embedded**: Can be directly integrated into applications - **Reliable**: ACID-compliant with atomic transactions - **Small footprint**: Less than 600KB fully configured SQLite is ideal for development, testing, embedded systems, and applications that need local data storage without the overhead of a client-server database. ## Connecting To connect to SQLite databases in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select SQLite as the database type and: - Browse to select your .db file or create a new one - No authentication required - SQLite uses file system permissions 4. **Connect**: Click save to connect to your SQLite database. 5. **Start Exploring**: Begin working with your tables, views, and data. For detailed instructions on connecting to SQLite, refer to the [Connect](/docs/get-started/connect) article. ## SQLite Features in DBCode DBCode enhances your SQLite development experience with: - **Schema visualization**: View your database structure with entity relationship diagrams - **Query history**: Track and reuse previous queries - **Export capabilities**: Save query results in various formats - **Syntax highlighting**: SQL syntax specifically optimized for SQLite dialect - **Table data editing**: Modify your data directly within Visual Studio Code By using SQLite with DBCode, you can quickly develop and test database-driven applications within your familiar VS Code environment. ## Extensions DBCode supports loading SQLite extensions to add functionality beyond what SQLite provides natively. Extensions are available in the **Advanced** section of the connection form. ### Bundled Extensions These extensions are downloaded and managed automatically when selected: | Extension | Version | Description | |-----------|---------|-------------| | mod_spatialite | 5.1.0 | Spatial SQL with geometry, geography, and GIS functions | | sqlite-vec | 0.1.6 | Vector search and embeddings | | sqlite-regex | 0.2.3 | Regular expressions via PCRE2 | | sqlite-js | 1.1.3 | User-defined functions in JavaScript | | sqlean | 0.27.2 | Collection of utilities including crypto, math, text, uuid, and more | ### Custom Extensions You can load any SQLite-compatible extension from disk, which is useful for extensions not in the bundled list, or for your own builds. 1. Open the connection form and expand the **Advanced** section 2. Enter the full path to your compiled extension file in **Custom Extensions** 3. Reconnect To load more than one, separate the paths with commas: ``` /opt/sqlite/spellfix.dylib, /opt/sqlite/uuid.dylib ``` The extension file must be a compiled shared library (`.dylib` on macOS, `.so` on Linux, `.dll` on Windows) compatible with your platform and architecture. Custom extensions load on connect, at the same point as the bundled ones, so virtual tables that depend on them resolve when the schema is read. For more information about SQLite, check out SQLite. --- ## Docs > Supported Databases > Sqlserver ### SQL Server Database Management in VS Code DBCode is a SQL Server extension for VS Code: connect to on-prem SQL Server or Azure, browse databases and data, write T-SQL with schema-aware autocomplete, and edit rows visually without leaving your editor. [Install DBCode](/docs/get-started/install) to get started, or see how it [compares to standalone database tools](/compare). ## Overview SQL Server is a robust relational database management system (RDBMS) developed by Microsoft that powers enterprise-scale applications. Key strengths include: - **Mission-critical performance**: In-memory technologies and advanced query processing - **Security innovations**: Always Encrypted, Dynamic Data Masking, and Row-Level Security - **Advanced analytics**: Integration with R and Python for machine learning - **Comprehensive high availability**: AlwaysOn Availability Groups and Failover Clustering - **Hybrid capabilities**: Consistent experience across on-premises and cloud SQL Server is ideal for organizations requiring enterprise-grade reliability, security, and performance for their data platform needs. ## Supported Authentication Methods DBCode supports these SQL Server authentication options: - **SQL Server Authentication**: Traditional username and password - **Windows Authentication**: Authenticate with a Windows domain account (domain, username, and password) - **Integrated (Kerberos)**: Automatic authentication using your current login session, no password required. Works on Windows (via SSPI), macOS, and Linux. On macOS and Linux you first obtain a Kerberos ticket for your domain (for example with `kinit user@REALM`); DBCode then authenticates using that ticket. - **Microsoft Entra ID**: Modern cloud-based identity service (via Azure SQL) ## Connection Types ### TCP/IP The standard connection method using host and port. Supports named instances by specifying the instance name separately (e.g., host: `myserver`, instance: `SQLEXPRESS`). ### Named Pipes (Windows only) Connect via Windows named pipes instead of TCP/IP. This includes: - **Named pipe path**: Direct pipe path (e.g., `\\.\pipe\sql\query`) - **LocalDB**: SQL Server LocalDB for local development - just enter the instance name (e.g., `MSSQLLocalDB`) and DBCode will automatically discover the pipe ## Connecting To connect to SQL Server in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select SQL Server as the database type and enter: - Server address or named instance - Authentication method and credentials - Database name (optional) - Connection encryption options 4. **Connect**: Click save to establish the connection. 5. **Start Managing Your Database**: Explore objects and execute queries. For detailed instructions on connecting to SQL Server, refer to the [Connect](/docs/get-started/connect) article. ## Connect Multiple Databases Major cloud providers offer SQL Server as a managed service. To connect to a cloud provider and access multiple SQL Server databases: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Select Your Provider**: Choose the cloud provider from the list. 4. **Authenticate**: Follow the authentication process for that provider. 5. **Start Managing Your Databases**: Navigate between servers and databases through a unified interface. For detailed instructions on connecting to cloud-hosted SQL Server databases, refer to the [Connect a Cloud Provider](/docs/cloud-providers/connect) article. ## SQL Server Features in DBCode DBCode enhances your SQL Server development experience with: - **T-SQL IntelliSense**: Smart code completion for SQL Server's dialect - **Execution plan visualization**: Analyze and optimize query performance By using SQL Server with DBCode, you can efficiently manage your databases while leveraging the productivity features of Visual Studio Code. For more information about SQL Server, check out SQL Server. --- ## Docs > Supported Databases > Starrocks ### StarRocks Database Management in VS Code ## Connecting To connect to StarRocks, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose StarRocks as the type, and enter the required information including host, port (default 9030), username, and password. 4. **Connect**: Click save to connect to your StarRocks database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to StarRocks, refer to the [Connect](/docs/get-started/connect) article. By using StarRocks with DBCode, you can connect to your StarRocks databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about StarRocks, check out StarRocks. --- ## Docs > Supported Databases > Stripe ### Stripe Payments and Billing Data in VS Code ## Overview Stripe is a payments platform for online businesses. DBCode connects to your Stripe account's API and presents its payments and billing data as read-only tables. Key characteristics include: - **Read-only API bridge**: DBCode calls the Stripe API rather than connecting to a database, so every table is a live view of your Stripe account - **Typed columns**: Fields are typed from Stripe's object model, so amounts, timestamps, and status enums display correctly in the grid - **Relationship navigation**: Foreign-key-style links between tables, for example a charge to its customer, let you jump between related records - **Test and live modes**: Test-mode keys expose Stripe's sandbox data, live keys expose your real account data DBCode is ideal for exploring and filtering your Stripe data without leaving Visual Studio Code or writing code against the Stripe API. ## Connecting To connect to Stripe in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Create a restricted API key in Stripe**: In the Stripe Dashboard, go to **Developers > API keys > Create restricted key** and grant read permissions on the resources you want to browse, for example Customers, Charges, and Subscriptions 4. **Complete connection form**: Select Stripe as the database type and paste the key into **API Key** 5. **Connect**: Click save to establish your connection. 6. **Start exploring**: The database node is named `test` or `live`, matching the mode of the key you used. Secret keys (`sk_...`) also work, but a restricted key scoped to only the resources you need is recommended. Publishable keys (`pk_...`) cannot be used, since they don't grant API read access. Test-mode keys show Stripe's test data, live-mode keys show your real account data. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## Stripe Features in DBCode DBCode enhances your Stripe experience with: - **18 tables**: `balance_transactions`, `charges`, `checkout_sessions`, `coupons`, `credit_notes`, `customers`, `disputes`, `events`, `invoice_items`, `invoices`, `payment_intents`, `payouts`, `prices`, `products`, `promotion_codes`, `refunds`, `setup_intents`, and `subscriptions` - **Typed columns**: Money fields are stored in Stripe's minor units (for example cents) as integers, alongside a separate currency column, matching how Stripe's API represents amounts - **Relationship navigation**: Jump between related records, such as a charge and its customer, using DBCode's relationship links - **Data exploration**: Preview and export table data ### Filtering Grid filters push down to the Stripe API wherever Stripe supports server-side filtering: created-date ranges, status, customer, and email are supported broadly, and Stripe's [Search API](https://stripe.com/docs/search) adds richer filters on seven searchable resources (`charges`, `customers`, `invoices`, `payment_intents`, `prices`, `products`, and `subscriptions`). If you apply a filter Stripe's API can't evaluate server-side, DBCode shows a clear message rather than returning the wrong rows. ### Preview limitations Stripe support is in Preview, and some limitations apply: - **No sorting**: Rows are always returned newest-first, since Stripe's API has no server-side sort, so columns cannot be sorted - **No row counts**: Total row counts are not available for Stripe tables - **Read-only**: The connection is read-only, there is no insert, update, or delete - **SELECT-only SQL**: SQL queries support `SELECT` only, see [Universal SQL](#universal-sql) below ## Universal SQL Stripe query editors accept SQL `SELECT` statements. The connection is read-only, so `INSERT`, `UPDATE`, and `DELETE` return a clear error rather than running. See [Universal SQL](/docs/query/universal-sql) for how the translation works across databases. ```sql SELECT * FROM customers WHERE created > '2026-01-01' LIMIT 10 ``` ```sql SELECT * FROM charges WHERE id = 'ch_123' ``` Filters push down to the Stripe API: `created` and other date ranges and resource-specific equality parameters are sent directly, `id` lookups (a single id or an `IN` list) fetch those records directly, and other fields use Stripe's [Search API](https://stripe.com/docs/search) where the resource supports it. Results always return newest-first - `ORDER BY` is not supported and returns a clear error, as does any SQL construct the API cannot serve, such as `JOIN`s or `GROUP BY`. ### Supported SQL | Statement | Support | |---|---| | `SELECT` | Yes | | `SELECT COUNT(*)` | No | | `INSERT` / `UPDATE` / `DELETE` | No - read-only, returns a clear error | - **`created` and other date columns**: ranges or date equality push down directly; a bare date like `'2026-03'` expands to that period - **Resource-specific equality filters**: whichever columns Stripe's list API accepts for that resource, for example `status`, `customer`, or `email` - **`id`**: equality or an `IN` list fetches those records directly - **Other searchable fields**: pushed through Stripe's [Search API](https://stripe.com/docs/search) where the resource supports it - **`WHERE` combinators**: `AND` only - `OR` is not supported - `LIMIT` and `OFFSET` are both supported; `OFFSET` is applied client-side over the API's cursor paging - Results always return newest-first; `ORDER BY` returns a clear error Not supported: joins, `GROUP BY`, aggregates, subqueries, aliases, `UNION`, and `OR` - each returns a clear error naming the construct. By using Stripe with DBCode, you can explore your payments and billing data directly within Visual Studio Code. For more information about Stripe, visit stripe.com. --- ## Docs > Supported Databases > Surrealdb ### SurrealDB Database Management in VS Code ## Overview SurrealDB is a next-generation multi-model database designed for modern applications. Key characteristics include: - **Multi-model architecture**: Combines document, graph, and relational data models in one database - **SurrealQL**: Powerful query language with SQL-like syntax plus graph traversal capabilities - **Real-time subscriptions**: Built-in support for live queries and real-time data updates - **Schemaless or schemafull**: Flexible schema options to suit your application needs - **Built-in authentication**: Row-level security and authentication built into the database - **Namespace isolation**: Multi-tenancy support with namespace and database hierarchies SurrealDB is ideal for applications requiring flexible data modeling, real-time features, and simplified backend architecture. ## Connecting To connect to SurrealDB in DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select SurrealDB as the database type and enter: - Host/Server address - Port (default: 8000) - Protocol (WebSocket or HTTP) - Namespace - Database - Username and Password (if authentication is enabled) 4. **Connect**: Click save to connect to your SurrealDB instance. 5. **Start Managing Your Data**: Browse tables and run SurrealQL queries. For detailed instructions on connecting to databases, refer to the [Connect](/docs/get-started/connect) article. ## SurrealDB Features in DBCode DBCode enhances your SurrealDB development experience with: - **SurrealQL query editor**: Write and execute queries with syntax highlighting - **Namespace/Database browsing**: Navigate through namespaces, databases, and tables - **Document editing**: View and edit documents directly in the data grid - **Schema inspection**: View table definitions and field types - **Query results visualization**: View and export query results - [Live Streaming](/docs/data/streaming): Subscribe to table changes in real time using LIVE SELECT. Right-click a table and select **Subscribe**, or run `LIVE SELECT * FROM table_name;` in the query editor By using SurrealDB with DBCode, you can efficiently explore your data, develop queries, and manage documents directly within Visual Studio Code. For more information about SurrealDB, check out SurrealDB. --- ## Docs > Supported Databases > Sybase ### SAP ASE (Sybase) Database Management in VS Code ## Overview SAP Adaptive Server Enterprise (ASE), formerly known as Sybase, is a high-performance relational database management system designed for transaction-heavy environments. Key strengths include: - **High transaction throughput**: Optimized for OLTP workloads with advanced locking and caching - **Enterprise reliability**: Proven in financial services, healthcare, and government - **T-SQL compatibility**: Shares SQL dialect roots with SQL Server - **Cross-platform support**: Runs on Linux, Windows, and Solaris SAP ASE is widely used in industries requiring high availability and consistent performance for mission-critical applications. ## Connecting To connect to SAP ASE in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select SAP ASE (Sybase) as the database type and enter: - Server address and port (default 5000) - Username and password - Database name (optional) - SSL/TLS options if required 4. **Connect**: Click save to establish the connection. 5. **Start Managing Your Database**: Explore schemas, tables, views, procedures, and more. For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. ## SAP ASE Features in DBCode DBCode enhances your SAP ASE development experience with: - **Schema browsing**: Navigate owners, tables, views, procedures, functions, triggers, sequences, and user-defined types - **DDL scripting**: View and edit definitions for views, procedures, functions, and triggers - **Data grid**: Browse and edit table data with identity column support By using SAP ASE with DBCode, you can efficiently manage your databases while leveraging the productivity features of Visual Studio Code. For more information about SAP ASE, check out SAP ASE. --- ## Docs > Supported Databases > Teradata ### Teradata Database Management in VS Code ## Overview Teradata is a massively parallel enterprise data warehouse used for large-scale analytics in finance, telecom, retail, and government. Key characteristics include: - **Database-as-schema model**: A Teradata "database" is the namespace that owns tables, views, macros, procedures, and functions. DBCode surfaces each database as a schema. - **Standard plus dialect SQL**: ANSI-style SQL with Teradata-specific features such as `QUALIFY`, `TOP`, and `SAMPLE` for row limiting. - **Object variety**: Tables, views, macros (a Teradata-specific object), stored procedures, and user-defined functions. - **Enterprise scale**: Shared-nothing MPP architecture, primary indexes, and statistics-driven optimization. DBCode connects over Teradata's native protocol using Teradata's official driver, so you can explore and query a Teradata Vantage environment - including a free [ClearScape Analytics Experience](https://www.teradata.com/getting-started/demos/clearscape-analytics) instance - without leaving Visual Studio Code. ## Connecting To connect to Teradata in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click the "Add Connection" icon. 3. **Complete the connection form**: Select Teradata as the database type and enter: - **Host**: hostname of your Teradata system (for ClearScape, the environment host) - **Port**: TCP port (default: 1025) - **Logon Mechanism**: `TD2` (username / password) or `LDAP` - **Username / Password**: Teradata credentials 4. **Accept the driver download**: Teradata's driver is proprietary, so DBCode does not bundle it. On first connect you are prompted to download Teradata's official `teradatasql` driver from the public npm registry for your own use, under Teradata's license. 5. **Connect**: Click save to connect, then browse databases, tables, views, and macros and run queries. For detailed connection instructions, refer to the [Connect](/docs/get-started/connect) article. ## Teradata Features in DBCode DBCode enhances your Teradata workflow with: - **SQL query editor**: Write and execute Teradata SQL with syntax highlighting and multi-statement support. - **Schema browsing**: Navigate databases, tables, views, macros, procedures, and functions, with column types, primary keys, foreign keys, and table sizes. - **Data editing**: Insert, update, and delete rows inline in the data grid. - **DDL scripting**: Generate object definitions with `SHOW TABLE`, `SHOW VIEW`, `SHOW MACRO`, and `SHOW PROCEDURE` directly from the schema browser. - **Execution plans**: View Teradata's `EXPLAIN` text plan for a query. - **Transactions**: Pin a connection to run statements in a transaction and commit or roll back together. - **Server monitoring**: View active sessions and system information from the monitoring panel. - **Statistics**: Optionally run `COLLECT STATISTICS` to refresh row counts during introspection. ### Preview limitations Teradata support is in Preview: - **High-precision DECIMAL**: Teradata's driver returns `DECIMAL`/`NUMBER` values as 64-bit floating point, so values beyond roughly 15-16 significant digits may lose precision in the grid. `BIGINT` integer values are returned exactly. - **Lock monitoring**: Teradata does not expose current locks through a system view, so the monitoring panel shows sessions and system info but not locks. - **Editor IntelliSense**: Some Teradata-specific syntax (such as `QUALIFY` and `SAMPLE`) does not yet get full editor completion. By using Teradata with DBCode, you can explore, query, and manage your data warehouse directly within Visual Studio Code. For more information about Teradata, visit teradata.com. --- ## Docs > Supported Databases > Tidb ### TiDB Database Management in VS Code ## Overview TiDB is an open-source, cloud-native, distributed SQL database built by PingCAP. It provides: - **MySQL compatibility**: Seamlessly migrate from MySQL with minimal changes - **Horizontal scalability**: Scale out compute and storage independently - **HTAP capabilities**: Run transactional and analytical workloads on the same data - **Strong consistency**: ACID transactions with distributed architecture - **High availability**: Built-in fault tolerance with automatic failover TiDB is designed to handle both OLTP and OLAP workloads, making it ideal for modern applications that require real-time analytics on operational data. ## Connecting To connect to TiDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select TiDB as the database type and enter: - Host address (default port: 4000) - Authentication credentials (username/password) - Database name (optional) - SSL configuration (if required) 4. **Connect**: Click save to connect to your TiDB database. 5. **Start Managing Your Database**: Browse databases, tables, views, and stored procedures. For detailed instructions on connecting to TiDB, refer to the [Connect](/docs/get-started/connect) article. ## TiDB Cloud TiDB is available as a fully managed service through [TiDB Cloud](https://tidbcloud.com/). To connect to TiDB Cloud: 1. Create a cluster in TiDB Cloud console 2. Get your connection credentials from the cluster details 3. Use the provided host, port, and credentials in DBCode ## TiDB Features in DBCode DBCode enhances your TiDB development experience with: - **Full MySQL compatibility**: Use familiar MySQL syntax and tools - **Schema exploration**: Navigate databases, tables, views, and procedures - **Query execution**: Run queries with syntax highlighting and autocomplete - **Data export/import**: Transfer data between TiDB instances By using TiDB with DBCode, you can efficiently develop, test, and manage your TiDB databases directly within Visual Studio Code. For more information about TiDB, check out TiDB by PingCAP. --- ## Docs > Supported Databases > Timescale ### Timescale Database Management in VS Code ## Overview TimescaleDB is a scalable time-series database designed to handle high-resolution metrics and time-series data based on PostgreSQL. It is designed to be highly available, scalable, and performant, making it an ideal choice for storing and analyzing large volumes of time-series data. ## Connecting To connect to TimescaleDB, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose TimescaleDB as the type, and enter the required information. 4. **Connect**: Click save to connect to your TimescaleDB database. 5. **Start Managing Your Databases**: Once connected, you can start managing your databases directly from Visual Studio Code. For detailed instructions on connecting to TimescaleDB, refer to the [Connect](/docs/get-started/connect) article. ## Kerberos / GSSAPI Authentication DBCode exposes **Integrated (Kerberos)** for TimescaleDB connections when the server is configured to accept PostgreSQL GSSAPI or SSPI authentication. - Select **Integrated (Kerberos)** and enter the TimescaleDB username that the Kerberos identity maps to. - On Windows, DBCode uses the current signed-in identity. On macOS and Linux, it uses an existing Kerberos ticket cache. - Integrated authentication requires a host/TCP connection. DBCode does not accept or manage keytabs. - The default **Kerberos Service Name** is `postgres`. Change it only when the server administrator registered another service name. By using TimescaleDB with DBCode, you can connect to your TimescaleDB databases, query and manage your data, and visualize your results, all directly from Visual Studio Code. For more information about TimescaleDB, check out TimescaleDB. --- ## Docs > Supported Databases > Trino ### Trino Query Engine in VS Code ## Connecting To connect to Trino, follow these general steps: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete new connection form**: Choose Trino as the type, and enter the required information including host, port (default 8080), and catalog. 4. **Connect**: Click save to connect to your Trino cluster. 5. **Start Managing Your Data**: Once connected, you can start querying your data directly from Visual Studio Code. For detailed instructions on connecting to Trino, refer to the [Connect](/docs/get-started/connect) article. By using Trino with DBCode, you can connect to your Trino clusters, query data across multiple sources, and visualize your results, all directly from Visual Studio Code. For more information about Trino, check out Trino. --- ## Docs > Supported Databases > Typedb ### TypeDB Database Management in VS Code ## Overview TypeDB is a polymorphic database built around a conceptual data model and the TypeQL query language. Highlights include: - **Conceptual model**: Data is modelled as entity, relation, and attribute types rather than tables - relations are first-class and can play roles in other relations - **Strong, inheritable types**: Types form `sub` hierarchies, and ownership/role constraints (`@key`, `@unique`, `@card`) are enforced by the database - **TypeQL**: A declarative, pattern-based query language for matching, inserting, updating, and defining schema - **Transactional**: Read, write, and schema transactions with commit/rollback - **TypeDB 3.x**: DBCode connects over the TypeDB HTTP API (default port 8000) TypeDB is commonly used for knowledge graphs, identity and access models, complex domain modelling, and any application where the relationships and constraints between concepts are as important as the data itself. ## Connecting To connect to TypeDB in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select TypeDB as the database type and enter: - Host address (default HTTP API port: 8000) - Username and password - Database name - Optional SSL/TLS configuration 4. **Connect**: Click save to connect to your TypeDB server. 5. **Start exploring**: Browse your entity, relation, and attribute types, and run TypeQL. For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. ## TypeDB Features in DBCode DBCode enhances your TypeDB development experience with: - **TypeQL execution**: Write and run TypeQL with results rendered in the grid - **Type browsing**: Explore entity, relation, and attribute types with owned attributes, roles, super-types, annotations, and instance counts; schema functions are not listed - **Data editing**: Add records and edit or delete existing records from the grid. DBCode identifies existing records by their unique TypeDB instance ID (`iid`). Text, numbers, dates, and similar values can be edited; nested values can only be viewed - **Schema DDL**: Create and drop entity, relation, and attribute types, truncate a type's instances, and view a type's `define` definition - **Database management**: Create and drop databases from the connection tree - **Query analysis**: Run EXPLAIN on a TypeQL query to inspect its typed pipeline - the match/select/sort/limit stages and the constraints TypeDB resolves - without executing the query - **Lossless 64-bit integers**: Large `integer` values are preserved exactly, beyond JavaScript's safe-integer range By using TypeDB with DBCode, you can model and query your data with TypeQL while working within your familiar VS Code environment. For more information about TypeDB, check out TypeDB. --- ## Docs > Supported Databases > Vertica ### Vertica Database Management in VS Code ## Overview Vertica (now OpenText Analytics Database) is a columnar, massively parallel processing (MPP) analytics database built for large-scale data warehousing and high-concurrency analytical workloads. It's known for: - **Columnar MPP architecture**: Column storage with projections for fast analytical queries over very large datasets - **Projections**: Physical, pre-optimized storage structures that Vertica tunes for query performance - **Scale and concurrency**: Designed for petabyte-scale warehouses and many concurrent analytical users - **SQL with analytics extensions**: ANSI SQL plus a rich set of in-database analytic functions - **Deployment flexibility**: Runs on-premises, in the cloud, and in Eon mode with separated compute and storage Vertica suits organizations running data warehousing, BI, and large-scale analytics where query performance over big data matters. ## Connecting To connect to Vertica in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Vertica as the database type and enter: - Host address (default port: 5433) - Authentication credentials (username/password) - Database name - SSL options (if required) 4. **Connect**: Click save to connect to your Vertica database. 5. **Start Managing Your Database**: Once connected, browse schemas, tables, views, projections, and run queries. For detailed instructions on connecting, refer to the [Connect](/docs/get-started/connect) article. ## DBCode Features for Vertica With DBCode, you can perform these essential tasks when working with Vertica: - **Schema Browser**: Navigate schemas, tables, views, columns, constraints, projections, sequences, and functions - **Data Editing**: Edit table data with support for Vertica data types - **Query Execution**: Run analytical queries with full SQL support, including EXPLAIN execution plans - **Server Monitoring**: Inspect sessions, locks, and resource pool usage - **DDL Scripting**: Generate object DDL via Vertica's EXPORT_OBJECTS - **Read-Only Connections**: Open a connection in read-only mode to guard against accidental changes - **Bulk Data Import/Export**: Import from CSV, Excel, and JSON files By using Vertica with DBCode, you can manage your analytics database directly within the familiar VS Code environment. For more information about Vertica, check out OpenText Analytics Database (Vertica). --- ## Docs > Supported Databases > Weaviate ### Weaviate Vector Database Management in VS Code ## Overview Weaviate is an open-source, schema-strict vector database designed for AI-native applications. Highlights include: - **Hybrid search**: Combine vector similarity (nearVector, nearText) with keyword BM25 search in a single query - **Server-managed vectorizers**: Attach a `text2vec-*` module (e.g. `text2vec-openai`, `text2vec-cohere`) to a class and Weaviate generates embeddings at write time - no client-side embedding required - **Declared class schema**: Each class (collection) has a defined property schema; objects must conform to it - **gRPC + REST**: Fast binary transport over gRPC (port 50051) with a REST management API (port 8080) - **Cloud or self-hosted**: Run locally with Docker, on-prem, or via Weaviate Cloud (WCD) Weaviate is commonly used for semantic search, retrieval-augmented generation (RAG), recommendation systems, and any workload that benefits from combining structured filters with high-dimensional vector similarity. ## Connecting To connect to Weaviate in DBCode: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete the connection form**: Select Weaviate as the database type and enter: - Host address (REST default port: 8080; gRPC default port: 50051) - API key (for Weaviate Cloud or any auth-protected instance) - Optional SSL/TLS configuration - Optional SSH tunnel 4. **Connect**: Click save to connect to your Weaviate instance. 5. **Start exploring**: Browse your collections, inspect objects, and run vector searches. For detailed instructions, refer to the [Connect](/docs/get-started/connect) article. ## Weaviate Features in DBCode DBCode brings the same browse-and-search workflow you already use for SQL and document databases to Weaviate: - **Collection browsing**: Navigate Weaviate classes (collections), see object counts, and inspect the declared property schema - **Vector cell rendering**: Vector columns are summarised inline and expandable on click - **Vector search**: Run nearest-neighbour searches with `nearVector`, returning results with a `_distance` column; combine with metadata filters for precision - **Text search**: Use `nearText` or `hybrid` queries to search by meaning and keyword simultaneously - leveraging the server-managed vectorizer configured on each class - **Object editing**: Edit object properties inline via the data grid; the object UUID and vectors are read-only - **Monitoring panels**: View cluster node status and per-collection object counts at a glance - **JS shell editor**: Drop into a JavaScript editor and run the official Weaviate client v3 SDK directly: ```js // Nearest-neighbour vector search collection('Article').query.nearVector([...], { limit: 10, returnMetadata: ['distance'] }); // Fetch objects with filters collection('Article').query.fetchObjects({ limit: 20 }); // Text search collection('Article').query.nearText(['query term'], { limit: 5 }); // Hybrid search (vector + keyword) collection('Article').query.hybrid('search terms', { limit: 10 }); ``` By using Weaviate with DBCode, you get a unified workspace for traditional and vector data without leaving VS Code. ## Multi-tenancy Weaviate collections can be created with multi-tenancy enabled, which partitions their data into isolated per-tenant shards. DBCode surfaces this structure directly in the connection tree. **Browsing tenants**: A multi-tenant collection expands to show its tenants rather than opening data directly - the collection itself holds no rows without a tenant selected. Clicking a tenant opens that tenant's objects in the data grid. Edits made in the grid apply only to the selected tenant. **Vector search and filters**: Searches and metadata filters run scoped to the active tenant. The workflow is the same as for non-tenant collections - select a tenant, then query or filter as usual. **Tenant activity status**: Each tenant displays its activity status alongside its name in the tree - `ACTIVE`, `INACTIVE`, or `OFFLOADED`. Inactive and offloaded tenants must be activated before their data can be browsed. DBCode will show an error if you attempt to open a tenant that is not active. **Managing tenants**: Right-click a collection or tenant in the tree for lifecycle operations: - **Collection context menu** - Create Tenant: adds a new tenant to the collection. - **Tenant context menu** - Activate: brings an inactive or offloaded tenant online. Deactivate: unloads the tenant's data from memory (data is preserved). Offload: moves the tenant's data to cold storage (data is preserved but requires reactivation to access). Drop: permanently deletes the tenant and all its data. For more information about Weaviate, check out Weaviate. --- ## Docs > Supported Databases > Yugabyte ### YugabyteDB Database Management in VS Code ## Overview YugabyteDB is a distributed SQL database that provides high availability, scalability, and performance based on PostgreSQL. It is designed to handle large volumes of data and is widely used in enterprise applications. YugabyteDB combines the best aspects of traditional RDBMS systems with cloud-native architecture: - **PostgreSQL compatibility**: Use familiar SQL syntax and tools - **Distributed architecture**: Built for cloud-native, high-availability deployments - **Linear scalability**: Easily scale horizontally by adding nodes - **Strong consistency**: ACID compliant transactions across distributed nodes ## Connecting To connect to YugabyteDB with DBCode, you'll need: 1. **Open the DBCode Extension**: Launch Visual Studio Code and open the DBCode extension. 2. **Add a New Connection**: Click on the "Add Connection" icon. 3. **Complete connection form**: Select YugabyteDB as the database type and enter: - Host address (default port: 5433) - Authentication details (username/password) - Database name (default: yugabyte) 4. **Connect**: Click save to connect to your YugabyteDB database. 5. **Start Managing Your Databases**: Once connected, you can start exploring your tables and data. For detailed instructions on connecting to YugabyteDB, refer to the [Connect](/docs/get-started/connect) article. ## Features in DBCode With YugabyteDB in DBCode, you can: - Run SQL queries across your cluster - View and manage your distributed tables and indexes - Visualize query results in a user-friendly format - Use the built-in SQL editor with syntax highlighting and auto-completion By using YugabyteDB with DBCode, you can leverage the power of distributed SQL while enjoying the productivity benefits of working within Visual Studio Code. For more information about YugabyteDB, check out YugabyteDB. --- ## Docs > Telemetry ### Telemetry To continuously improve the DBCode experience, we collect non-personally identifiable telemetry data when this setting is enabled in Visual Studio Code. Telemetry helps us understand which features are most used, the types of databases accessed, and instances of errors or crashes. This data provides valuable insights that enable us to identify and prioritize areas for improvement. ### How Telemetry Works - **Data Collected:** Telemetry data includes information about the types of databases accessed, the features used within DBCode, and error occurrences. No personally identifiable information is collected. - **Respect for VS Code Telemetry Settings:** DBCode follows the Visual Studio Code telemetry setting. If telemetry is disabled in your VS Code settings, DBCode will not collect any data. - **Privacy Policy:** For more information on how we handle telemetry data, please review our [Privacy Policy](/legal/privacy-policy). ### What Happens if Telemetry is Disabled? If telemetry is disabled in Visual Studio Code, DBCode will not collect or send any usage data. This setting will not impact your ability to use any DBCode features. ### Disabling Telemetry DBCode follows the Visual Studio Code telemetry setting. To disable telemetry for DBCode, set the VS Code telemetry level to `off`: 1. **Open Settings:** Press Cmd+, on macOS or Ctrl+, on Windows and Linux. 2. **Search for Telemetry:** Search for `telemetry`. 3. **Disable Telemetry:** Find **Telemetry: Telemetry Level**, open the dropdown, and choose `off`. ![Telemetry level setting](./telemetry.png) Enabling telemetry helps us improve DBCode by providing valuable insights while respecting your privacy. If telemetry is disabled, DBCode will continue to function normally. --- ## Support - Email: help@dbcode.io - Website: https://dbcode.io - Documentation: https://dbcode.io/docs ## License DBCode is proprietary software. See https://dbcode.io/legal/terms for terms of service.