Basic Usage
Basic Usage
Section titled “Basic Usage”Welcome to the complete DBCrust user guide! This page covers everything you need to know to become productive with DBCrust.
🚀 Starting DBCrust
Section titled “🚀 Starting DBCrust”Command Line Interface
Section titled “Command Line Interface”DBCrust follows a simple pattern: dbcrust [OPTIONS] <CONNECTION_URL>
# Basic connectiondbcrust postgres://user:password@localhost:5432/database
# With smart URL scheme completiondbc pos[TAB] → postgres://dbc docker://my[TAB] → docker://my-postgres-containerdbc session://prod[TAB] → session://production_db
# File formats (Parquet, CSV, JSON)dbcrust parquet:///data/sales_2024.parquetdbcrust csv:///logs/*.csv?header=truedbcrust json:///api_responses.json
# With optionsdbcrust --ssh-tunnel jumphost.com postgres://user@db.internal/app
# Short aliasdbc postgres://user:password@localhost/databaseInteractive vs Non-Interactive Mode
Section titled “Interactive vs Non-Interactive Mode”Interactive Mode
# Start interactive sessiondbcrust postgres://user:pass@localhost/mydb
# You'll see the promptmydb=#Non-Interactive Mode
# Execute single querydbcrust postgres://user:pass@localhost/mydb \ --query "SELECT COUNT(*) FROM users"
# Execute filedbcrust postgres://user:pass@localhost/mydb \ --file report.sql🎯 The DBCrust Prompt
Section titled “🎯 The DBCrust Prompt”When you enter interactive mode, you’ll see a rich prompt with context:
postgres://localhost:5432/myapp as postgresmyapp=#The prompt shows:
- Database type and connection details
- Current database name
- User you’re connected as
- Transaction state (if in a transaction)
Server Information Display
Section titled “Server Information Display”When connecting to databases, DBCrust displays server version information (similar to pgcli):
$ dbcrust postgres://postgres@localhost/myappServer: PostgreSQL 17.5 (Debian 17.5-1.pgdg120+1)Version: 0.16.1✓ Successfully connected to databaseConnected! Type \h for help or \q to quit.
postgres://localhost:5432/myapp as postgresmyapp=#What’s shown:
- Server: Database type and version string
- Version: DBCrust client version
- Connection status: Success/failure indication
Control server info display:
-- Toggle server info on/off\serverinfo
-- Status shows current settingServer info display is now disabled.Configuration:
# In ~/.config/dbcrust/config.tomlshow_server_info = true # Default: true📝 Basic Query Execution
Section titled “📝 Basic Query Execution”Simple Queries
Section titled “Simple Queries”-- Basic SELECTSELECT * FROM users LIMIT 5;
-- With WHERE clauseSELECT name, email FROM users WHERE created_at > '2024-01-01';
-- AggregationsSELECT status, COUNT(*) as countFROM ordersGROUP BY status;Multi-line Queries
Section titled “Multi-line Queries”DBCrust automatically detects when you’re typing a multi-line query:
-- Start typing...SELECT u.name, u.email, COUNT(o.id) as order_countFROM users uLEFT JOIN orders o ON u.id = o.user_idGROUP BY u.id, u.name, u.emailHAVING COUNT(o.id) > 5;-- Press Enter to execute🧠 Smart Autocompletion
Section titled “🧠 Smart Autocompletion”DBCrust provides intelligent, context-aware autocompletion that understands both your database schema and SQL syntax context:
SQL Context-Aware Completion
Section titled “SQL Context-Aware Completion”DBCrust automatically detects what SQL clause you’re in and suggests appropriate completions:
✨ NEW: Cursor Context-Aware Completion
Section titled “✨ NEW: Cursor Context-Aware Completion”DBCrust now supports forward-looking completion - it can read the full line and suggest columns even when the table appears after the cursor:
-- 🎯 NEW: Forward-looking column completion works!SELECT [TAB] FROM users-- Suggests: id, name, email, created_at, status (reads 'users' after cursor!)
-- Works with complex queriesSELECT u.[TAB] FROM users u JOIN orders o ON u.id = o.user_id-- Suggests: id, name, email, created_at, status (from users table)
-- Even with aliases and multiple tablesSELECT [TAB] FROM users u, orders o WHERE u.id = o.user_id-- Suggests columns from BOTH users and orders tablesSELECT Clause Suggestions
Section titled “SELECT Clause Suggestions”SELECT [TAB]-- Context-aware suggestions:-- • If FROM clause present after cursor: column names from those tables-- • Otherwise: *, COUNT(, SUM(, AVG(, MAX(, MIN(, DISTINCT
-- Column completion works when table is visible before cursor:SELECT * FROM users WHERE [TAB]-- Suggests: id, name, email, created_at, status (from users table)WHERE Clause Intelligence
Section titled “WHERE Clause Intelligence”-- After WHERE, suggests only column names (no tables or functions)SELECT * FROM users WHERE [TAB]-- Suggests: id, name, email, created_at, status, active-- Does NOT suggest: users, orders, COUNT(, *
-- Works with complex queries and multiple tablesSELECT * FROM users u JOIN orders o ON u.id = o.user_id WHERE [TAB]-- Suggests columns from BOTH users and orders tablesFROM Clause Behavior
Section titled “FROM Clause Behavior”-- After FROM, suggests table names (existing behavior preserved)SELECT * FROM [TAB]-- Suggests: users, orders, products, categories-- Does NOT suggest: *, COUNT(, column namesTraditional Schema-Based Completion
Section titled “Traditional Schema-Based Completion”Table Name Completion
Section titled “Table Name Completion”SELECT * FROM us[TAB]-- Suggests: users, user_sessions, user_preferencesColumn Completion with Dot Notation
Section titled “Column Completion with Dot Notation”-- After table.dot, suggests columns from that specific tableSELECT users.[TAB] FROM users-- Suggests: id, name, email, created_at, status
-- Works with aliases tooSELECT u.[TAB] FROM users u-- Suggests: id, name, email, created_at, statusMulti-Level Nested Field Completion
Section titled “Multi-Level Nested Field Completion”For file formats (Parquet, JSON) and databases with nested structures, DBCrust supports deep nested field navigation:
-- Navigate nested structures (Parquet/JSON files)SELECT data.[TAB] FROM sales-- Suggests: data, data.customer, data.customer.address, data.order
-- Navigate to any depthSELECT data.customer.[TAB] FROM sales-- Suggests: data.customer.name, data.customer.email, data.customer.address
-- Navigate even deeperSELECT data.customer.address.[TAB] FROM sales-- Suggests: data.customer.address.city, data.customer.address.state, data.customer.address.zip
-- Works with complex field names containing special charactersSELECT data.exact_paths.[TAB] FROM policies-- Suggests: auth/token/create, aws_okta/creds/management-ecr, sys/mounts/aws_okta
-- Navigate through multiple levelsSELECT data.exact_paths.auth/token/create.[TAB] FROM policies-- Suggests: capabilities
-- Use in WHERE clauses tooSELECT * FROM res WHERE data.exact_paths.[TAB]-- Suggests nested paths for filteringSchema Display for Nested Fields:
When you describe a table with nested structures, DBCrust shows both a summary and detailed nested field information:
\d policies
Table: policiesColumn | Type-----------------+--------------------id | Int64data | Struct<4 fields>timestamp | Utf8
Nested field details: data (Struct): - chroot_namespace: Utf8 - exact_paths: Struct<25 fields> - glob_paths: Struct<10 fields> - root: Utf8Features:
- Deep Navigation: Navigate nested fields to any depth
- Direct Children Only: Autocomplete shows immediate children, not all descendants
- Context-Aware: Works in SELECT, WHERE, ORDER BY, and all SQL clauses
- Special Characters: Handles field names with
/,-, and other characters - Performance: Fast even with deeply nested structures
SQL Keywords
Section titled “SQL Keywords”SEL[TAB] name FR[TAB] users WH[TAB] active = true-- Expands to: SELECT name FROM users WHERE active = trueAdvanced Context Examples
Section titled “Advanced Context Examples”🎯 Forward-Looking Completion Examples
Section titled “🎯 Forward-Looking Completion Examples”The breakthrough cursor context-aware completion enables these previously impossible patterns:
-- All of these NOW WORK with forward-looking completion!
-- Basic forward completionSELECT i[TAB] FROM users-- Suggests: id (from users table that comes after cursor)
-- Multiple tablesSELECT u[TAB] FROM users u, orders o-- Suggests: user_id, username, updated_at (prefixed completions)
-- Complex JOINs with aliasesSELECT p[TAB] FROM users u JOIN orders o ON u.id = o.user_id JOIN products p ON o.product_id = p.id-- Suggests: price, product_name, product_id (from products table)
-- Subqueries and CTEsSELECT name[TAB] FROM ( SELECT id, first_name, last_name FROM users) u-- Suggests: first_name, last_name (from subquery columns)ORDER BY and GROUP BY
Section titled “ORDER BY and GROUP BY”-- After ORDER BY, suggests columns from FROM tablesSELECT * FROM users ORDER BY [TAB]-- Suggests: id, name, email, created_at, status
-- Same for GROUP BYSELECT COUNT(*) FROM users GROUP BY [TAB]-- Suggests: status, created_at, department_idHAVING Clause
Section titled “HAVING Clause”-- After HAVING, suggests aggregate functions AND column namesSELECT status, COUNT(*) FROM users GROUP BY status HAVING [TAB]-- Suggests: COUNT(, SUM(, AVG(, MAX(, MIN( and column namesMultiple Table Support
Section titled “Multiple Table Support”-- Autocompletion understands complex FROM clausesSELECT * FROM users u, orders o, products p WHERE [TAB]-- Suggests columns from users, orders, AND products tables
-- Works with JOINs tooSELECT * FROM users u LEFT JOIN orders o ON u.id = o.user_id JOIN products p ON o.product_id = p.idWHERE [TAB]-- Suggests: u.id, u.name, o.status, o.total, p.name, p.price, etc.📊 Result Display Options
Section titled “📊 Result Display Options”Default Table Format
Section titled “Default Table Format”╭────┬─────────────┬──────────────────────┬────────────╮│ id │ name │ email │ created_at │├────┼─────────────┼──────────────────────┼────────────┤│ 1 │ John Doe │ john@example.com │ 2024-01-15 ││ 2 │ Jane Smith │ jane@example.com │ 2024-01-16 │╰────┴─────────────┴──────────────────────┴────────────╯Expanded Display
Section titled “Expanded Display”For wide tables, toggle expanded display:
\x -- Toggle expanded display
SELECT * FROM users WHERE id = 1;Output:
-[ RECORD 1 ]----------id | 1name | John Doeemail | john@example.comcreated_at | 2024-01-15status | activebio | Software engineer with 10 years of experience...psql-Compatible Output
Section titled “psql-Compatible Output”\pset border 2 -- Set border style\pset format aligned -- Set format🔍 Query Analysis with EXPLAIN
Section titled “🔍 Query Analysis with EXPLAIN”Enable EXPLAIN mode to see query execution plans:
\e -- Toggle EXPLAIN mode
-- Now all queries show execution plansSELECT * FROM users WHERE email = 'john@example.com';Output:
○ Execution Time: 0.89 ms○ Planning Time: 0.12 ms
Index Scan using email_idx on users│ Index Cond: (email = 'john@example.com'::text)│ ○ Cost: 0.29..8.31│ ○ Rows: 1│ ○ Width: 156└─ Returns: id, name, email, created_at, status, bioEXPLAIN Options
Section titled “EXPLAIN Options”-- Enable different EXPLAIN modes\e on -- Basic EXPLAIN\e analyze -- EXPLAIN ANALYZE\e verbose -- EXPLAIN VERBOSE\e buffers -- EXPLAIN (ANALYZE, BUFFERS)
-- Disable EXPLAIN\e off💾 History and Sessions
Section titled “💾 History and Sessions”Command History
Section titled “Command History”DBCrust maintains a persistent history of your commands:
-- Search history with Ctrl+R-- Navigate with Up/Down arrows-- History is saved between sessionsSession Management
Section titled “Session Management”DBCrust provides two distinct features for managing connections:
Saved Sessions
Section titled “Saved Sessions”Named sessions for frequently used connections:
-- Save current connection as a session\ss production
-- List all saved sessions\s
-- Connect to a saved session interactively\s production
-- Delete a saved session\sd old_stagingCommand line access:
# Connect using saved sessiondbcrust session://production
# Run query on saved sessiondbcrust session://production -c "SELECT version()"Connection History
Section titled “Connection History”Automatic tracking of all connections:
-- List recent connections with full URLs\r
-- Clear connection history\rcInteractive reconnection:
# Select from recent connections interactivelydbcrust recent://📁 File Operations
Section titled “📁 File Operations”Executing SQL Files
Section titled “Executing SQL Files”-- Execute a SQL file\i scripts/create_tables.sql
-- Execute with relative path\i ../migrations/001_add_users.sqlSaving Queries
Section titled “Saving Queries”-- Write last query to file\w my_query.sql
-- Write specific content\w backup_script.sqlSELECT pg_dump('mydb');External Editor
Section titled “External Editor”For complex queries, use your preferred editor:
-- Open external editor (uses $EDITOR)\ed
-- Edit, save, and close - query executes automaticallyEditor integration works with:
- vim/nvim - Full syntax highlighting
- VS Code -
code --waitfor integration - nano - Simple editing
- emacs - Advanced editing features
🏷️ Named Queries
Section titled “🏷️ Named Queries”Save frequently used queries with parameters:
-- Save a parameterized query\ns active_users SELECT * FROM users WHERE status = '$1' AND created_at > '$2';
-- Use the named queryactive_users premium '2024-01-01'active_users trial '2024-06-01'
-- List all named queries\n
-- Delete a named query\nd active_usersParameter Substitution
Section titled “Parameter Substitution”Named queries support flexible parameter substitution:
-- Single parameter\ns user_by_id SELECT * FROM users WHERE id = $1;
-- Multiple parameters\ns user_orders SELECT * FROM orders WHERE user_id = $1 AND status = '$2';
-- All remaining parameters\ns search_users SELECT * FROM users WHERE name ILIKE '%$*%';🎨 Customization
Section titled “🎨 Customization”Display Preferences
Section titled “Display Preferences”-- Toggle various display options\x -- Expanded display\pset border 1 -- Border style (0, 1, 2)\pset null 'NULL' -- How to display NULL values\timing on -- Show query execution timeConfiguration
Section titled “Configuration”View and modify settings:
-- Show current configuration\config
-- Configuration is stored in ~/.config/dbcrust/config.tomlExample configuration:
[database]default_limit = 1000expanded_display_default = falseshow_execution_time = true
[display]null_display = "NULL"border_style = 1date_format = "%Y-%m-%d"
[editor]command = "code --wait"temp_dir = "/tmp"⌨️ Keyboard Shortcuts
Section titled “⌨️ Keyboard Shortcuts”| Shortcut | Action |
|---|---|
Ctrl+C | Cancel current input |
Ctrl+D | Exit DBCrust |
Ctrl+L | Clear screen |
Ctrl+R | Search command history |
Ctrl+A | Move to beginning of line |
Ctrl+E | Move to end of line |
Ctrl+U | Delete to beginning of line |
Ctrl+K | Delete to end of line |
Ctrl+W | Delete previous word |
Tab | Autocomplete |
Shift+Tab | Previous autocomplete suggestion |
Up/Down | Navigate command history |
Ctrl+Up/Down | Navigate multi-line input |
🚪 Exiting DBCrust
Section titled “🚪 Exiting DBCrust”-- Any of these will exit\q\quitexit-- Or press Ctrl+D