{"id":51058540,"url":"https://github.com/cumulus13/psqlc","last_synced_at":"2026-06-22T23:02:14.835Z","repository":{"id":319645407,"uuid":"1075949056","full_name":"cumulus13/psqlc","owner":"cumulus13","description":"A production-ready, feature-rich command-line interface tool for managing PostgreSQL databases with beautiful output formatting and intelligent auto-detection capabilities.","archived":false,"fork":false,"pushed_at":"2025-12-13T18:04:51.000Z","size":1125,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-12-15T12:15:34.457Z","etag":null,"topics":["asyncpg","django","environment","postgresql"],"latest_commit_sha":null,"homepage":"https://psqlc.readthedocs.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cumulus13.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"docs/contributing.rst","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-14T07:51:35.000Z","updated_at":"2025-12-14T21:40:35.000Z","dependencies_parsed_at":null,"dependency_job_id":"9c2f326b-da66-42d7-a66e-ec2bb0e98a85","html_url":"https://github.com/cumulus13/psqlc","commit_stats":null,"previous_names":["cumulus13/psqlc"],"tags_count":27,"template":false,"template_full_name":null,"purl":"pkg:github/cumulus13/psqlc","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cumulus13%2Fpsqlc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cumulus13%2Fpsqlc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cumulus13%2Fpsqlc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cumulus13%2Fpsqlc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cumulus13","download_url":"https://codeload.github.com/cumulus13/psqlc/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cumulus13%2Fpsqlc/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34668499,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-22T02:00:06.391Z","response_time":106,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asyncpg","django","environment","postgresql"],"created_at":"2026-06-22T23:02:13.593Z","updated_at":"2026-06-22T23:02:14.828Z","avatar_url":"https://github.com/cumulus13.png","language":"Python","funding_links":["https://www.buymeacoffee.com/cumulus13","https://ko-fi.com/cumulus13","https://www.patreon.com/cumulus13"],"categories":[],"sub_categories":[],"readme":"# PostgreSQL Manager CLI Tool\n\nFeature-rich command-line interface tool for managing PostgreSQL databases. Built with `asyncpg` and featuring beautiful output formatting with Rich, it provides intelligent auto-detection of database configurations from Django settings, environment files, and various configuration formats.\n\n\n## ✨ Features\n\n- 🚀 **Async Operations**: Built on asyncpg for high-performance database operations\n- 🎯 **Intuitive Sub-commands** - Natural command structure (e.g., `show dbs`, `show tables`)\n- 🔍 **Auto-detection** - Automatically finds and parses Django `settings.py` files\n- 🎨 **Beautiful Output** - Rich formatted tables with color-coded messages\n- 🔐 **Security First** - Confirmation prompts for destructive operations, read-only mode for queries\n- 📊 **Comprehensive Info** - Database sizes, table structures, indexes, connections, and more\n- 🛡️ **Production Ready** - Robust error handling, connection timeouts, transaction management, Error handling, logging, and safety features\n\n## 📋 Requirements\n\n```bash\npip install psqlc\n# or\npip install git+https://github.com/cumulus13/psqlc\n```\n\n## 🚀 Quick Start\n\n### Basic Usage\n\n```bash\n# Show version\npsqlc --version\n\n# List all databases\npsqlc show dbs\n\n# List tables in current project's database (auto-detected)\npsqlc show tables\n\n# Show database users\npsqlc show users\n\n# Show all databases\npsqlc show dbs -U postgres -P password\n\n# Show tables in a database\npsqlc show tables -d mydb -U postgres\n\n# Create user and database\npsqlc create newuser newpass newdb -U postgres\n\n# Execute a query\npsqlc query -d mydb -q \"SELECT * FROM users LIMIT 10\" -U postgres\n```\n\n## 🔧 Configuration Auto-Detection\n\n### 1. Django settings.py\n\n#### Using Django Settings Auto-detection\n\nIf you have a Django `settings.py` file in your project to extract PostgreSQL configuration. It searches:\n\n1. Current working directory\n2. Recursively down to 5 levels deep\n3. Explicit paths provided as arguments\n\nthe tool will automatically detect and use the database configurations from:\n\n```python\n# settings.py\nDATABASES = {\n    'default': {\n        'ENGINE': 'django.db.backends.postgresql',\n        'NAME': 'mydatabase',\n        'USER': 'myuser',\n        'PASSWORD': 'mypassword',\n        'HOST': 'localhost',\n        'PORT': '5432',\n    }\n}\n```\n\n```bash\n# No need to specify database credentials!\npsqlc show tables\npsqlc show dbs\npsqlc describe -t users\n```\n\n### 2. Environment Files (.env)\n```bash\n# .env\nPOSTGRESQL_USERNAME=myuser\nPOSTGRESQL_PASSWORD=mypassword\nPOSTGRESQL_DB_NAME=mydatabase\nPOSTGRESQL_HOST=localhost\nPOSTGRESQL_PORT=5432\n```\n\n### 3. JSON/YAML Configuration\n```json\n{\n    \"engine\": \"postgresql\",\n    \"user\": \"myuser\",\n    \"password\": \"mypassword\",\n    \"database\": \"mydatabase\",\n    \"host\": \"localhost\",\n    \"port\": 5432\n}\n```\n\n\nThe tool searches recursively (up to 5 levels deep) for `settings.py|.env|.json|.yaml|.ini` files and extracts PostgreSQL configuration automatically.\n\n\n### Auto-detection Priority\n\n1. **Command-line arguments** (highest priority)\n2. **Django settings.py -\u003e .env -\u003e .json -\u003e .yaml -\u003e .ini** (if no CLI args provided)\n3. **Interactive prompt** (for passwords only)\n\n### Manual Settings Path\n\n```bash\n# Specify settings.py file\npsqlc create /path/to/settings.py\npsqlc create /path/to/*.env\npsqlc create /path/to/anyfile.env\npsqlc create /path/to/*.json\npsqlc create /path/to/anyfile.json\npsqlc create /path/to/*.yaml\npsqlc create /path/to/anyfile.yaml\npsqlc create /path/to/*.ini\npsqlc create /path/to/anyfile.ini\n\n# Specify directory containing settings.py\npsqlc create /path/to/project/\n```\n\n\n## 📚 Commands Reference\n\n### Global Options\n\nThese options can be used with any command:\n\n| Option | Description | Default |\n|--------|-------------|---------|\n| `-H, --hostname` | PostgreSQL server address | `222.222.222.5` |\n| `-U, --user` | PostgreSQL superuser | `postgres` |\n| `-P, --passwd` | PostgreSQL superuser password | Auto-detect or prompt |\n| `--port` | PostgreSQL server port | `5432` |\n| `--debug` | Enable debug mode | `False` |\n\n### SHOW Commands\n\nDisplay various database information with beautiful formatted tables.\n\n#### List Databases `show dbs`\n```bash\npsqlc show dbs\n```\nShows all databases with sizes, encoding, and collation.\n\n**Example Output:**\n```\n┌───────────────────┬─────────┬───────────┬────────────┐\n│ Database          │ Size    │ Encoding  │ Collation  │\n├───────────────────┼─────────┼───────────┼────────────┤\n│ myapp_production  │ 15 MB   │ UTF8      │ en_US.utf8 │\n│ myapp_development │ 8 MB    │ UTF8      │ en_US.utf8 │\n│ postgres          │ 8 MB    │ UTF8      │ en_US.utf8 │\n└───────────────────┴─────────┴───────────┴────────────┘\n```\n\n#### List Tables `show tables`\n\nList all tables in a database with size and column count.\n\n```bash\npsqlc show tables -d mydatabase\n# Or auto-detect database from settings\npsqlc show tables\n```\n\n**Example Output:**\n```\n┌────────┬──────────────────┬────────┬─────────┐\n│ Schema │ Table            │ Size   │ Columns │\n├────────┼──────────────────┼────────┼─────────┤\n│ public │ auth_user        │ 256 KB │ 11      │\n│ public │ django_session   │ 128 KB │ 4       │\n│ public │ products_product │ 512 KB │ 8       │\n└────────┴──────────────────┴────────┴─────────┘\n```\n\n**Options:**\n- `-d, --database` - Database name (auto-detects from settings.py if not provided)\n\n#### List Users `show users`\n\nList all PostgreSQL users/roles with their permissions.\n\n```bash\npsqlc show users\n```\n\n**Output:**\n```\n┌──────────────┬───────────┬───────────┬─────────────┬───────────┬──────────────┐\n│ Username     │ Superuser │ Create DB │ Create Role │ Can Login │ Replication  │\n├──────────────┼───────────┼───────────┼─────────────┼───────────┼──────────────┤\n│ postgres     │ True      │ True      │ True        │ True      │ True         │\n│ myapp_user   │ False     │ True      │ False       │ True      │ True         │\n└──────────────┴───────────┴───────────┴─────────────┴───────────┴──────────────┘\n```\n\n#### Show Connections `show connections`\n\nDisplay active database connections with client information.\n\n```bash\npsqlc show connections\n```\n\n#### Show Indexes `show indexes`\n\nDisplay indexes in database or specific table.\n\n```bash\n# Show all indexes in database\npsqlc show indexes\n\n# Show indexes for specific table\npsqlc show indexes -d mydb -t users\n```\n\n**Options:**\n- `-d, --database` - Database name (auto-detect if not provided)\n- `-t, --table` - Table name (optional, shows all if not provided)\n\n#### Show Sizes `show size`\n\nDisplay size information for databases or tables.\n\n```bash\n# Show all database sizes\npsqlc show size\n\n# Show table sizes in a database\npsqlc show size -d mydb\n\n# Show size of specific table\npsqlc show size -d mydb -t users\n```\n\n**Options:**\n- `-d, --database` - Database name (auto-detect if not provided)\n- `-t, --table` - Table name (optional, shows all tables if not provided)\n\n**Example Output:**\n```\n📊 Size of table 'users':\n   Total Size:   15 MB\n   Table Size:   12 MB\n   Indexes Size: 3 MB\n```\n\n### CREATE Command\n\nCreate a new PostgreSQL user and database with proper privileges.\n\n```bash\n# Method 1: Direct arguments\npsqlc create username password dbname -U postgres\n\n# Method 2: Named arguments\npsqlc create -u username -p password -d dbname -U postgres\n\n# Method 3: Auto-detect from settings.py\npsqlc create -U postgres\n\n# Method 4: From Django settings file\npsqlc create /path/to/settings.py -U postgres\n```\n\n**Options:**\n- `CONFIG` - Positional arguments: `NEW_USERNAME NEW_PASSWORD NEW_DB`\n- `-u, --username` - New PostgreSQL username\n- `-p, --password` - Password for new user\n- `-d, --database` - Database name to create\n\n**Features:**\n- Automatically creates user with LOGIN, CREATEDB, REPLICATION, BYPASSRLS privileges\n- Checks for existing database and prompts for confirmation before dropping\n- Supports Django settings.py auto-detection\n\n### DESCRIBE Command\n\nShow detailed table structure including columns, data types, and constraints.\n\n```bash\n# Auto-detect database\npsqlc describe -t users\n\n# Specify database\npsqlc describe -d mydb -t users\n```\n\n**Options:**\n- `-d, --database` - Database name (auto-detect if not provided)\n- `-t, --table` - Table name (required)\n\n**Output:**\n```\n┌──────────────┬──────────────┬────────────┬──────────┬─────────────┐\n│ Column       │ Type         │ Max Length │ Nullable │ Default     │\n├──────────────┼──────────────┼────────────┼──────────┼─────────────┤\n│ id           │ integer      │ -          │ NO       │ nextval()   │\n│ username     │ varchar      │ 150        │ NO       │ -           │\n│ email        │ varchar      │ 255        │ YES      │ -           │\n│ created_at   │ timestamp    │ -          │ NO       │ now()       │\n└──────────────┴──────────────┴────────────┴──────────┴─────────────┘\n```\n\n### QUERY Command\n\nExecute custom SQL queries with safety features.\n\n```bash\n# Basic query\npsqlc query -d mydb -q \"SELECT * FROM users LIMIT 10\"\n\n# Read-only mode (prevents destructive operations)\npsqlc query -d mydb -q \"SELECT * FROM users\" --readonly\n\n# Limit rows displayed\npsqlc query -d mydb -q \"SELECT * FROM logs\" --limit 50\n```\n\n**Options:**\n- `-d, --database` - Database name (auto-detect if not provided)\n- `-q, --query` - SQL query to execute (required)\n- `--readonly` - Prevent destructive operations (blocks DROP, DELETE, TRUNCATE, ALTER, CREATE, INSERT, UPDATE)\n- `--limit` - Limit number of rows displayed (default: 100)\n\n**Safety Features:**\n- Read-only mode blocks all destructive SQL commands\n- Automatic transaction rollback on errors\n- Row limit prevents memory issues with large result sets\n\n### BACKUP Command\n\nGenerate backup command for a database using pg_dump.\n\n```bash\n# Auto-detect database\npsqlc backup\n\n# Specify database\npsqlc backup -d mydb\n```\n\n```bash\npsqlc backup -d mydatabase\n```\n\n**Output:**\n```\n🗄️ Creating backup of 'mydatabase'...\n💡 Run this command manually:\n   pg_dump -h 127.0.0.1 -p 5432 -U postgres -d mydatabase -F p -f mydatabase_backup_20231014_143022.sql\n```\n\n**Options:**\n- `-d, --database` - Database name to backup (auto-detect if not provided)\n\n**Note:** This command generates the pg_dump command for you to run manually. Direct backup execution requires pg_dump to be installed and accessible in your PATH.\n\n### DROP Commands\n\nSafely drop databases or users with confirmation prompts.\n\n#### Drop Database `drop database`\n\nDrop a database with safety confirmation.\n\n```bash\n# Auto-detect database\npsqlc drop database\n\n# Specify database\npsqlc drop database -d mydb\n```\n\n**Options:**\n- `-d, --database` - Database name to drop (auto-detect if not provided)\n\n**Safety Features:**\n- Requires typing the exact database name for confirmation\n- Automatically terminates all active connections before dropping\n- Cannot be undone - use with caution!\n\n#### Drop User `drop user`\n\nDrop a PostgreSQL user/role with safety confirmation.\n\n```bash\npsqlc drop user -u username\n```\n\n**Options:**\n- `-u, --username` - Username to drop (required)\n\n**Safety Features:**\n- Requires typing the exact username for confirmation\n- Cannot be undone - use with caution!\n\n## Advanced Usage\n\n### Using with Custom Configuration Files\n\n```bash\n# Use specific settings file\npsqlc --debug show tables\n\n# Custom host and port\npsqlc -H db.example.com --port 5433 show dbs\n\n# Different superuser\npsqlc -U admin show users\n```\n\n### Debug Mode\n\nEnable debug mode for detailed logging:\n\n```bash\npsqlc --debug show dbs\n```\n\nOr set environment variable:\n```bash\nexport DEBUG=1\npsqlc show tables\n```\n\n## API Reference\n\n### Core Functions\n\n#### `parse_django_settings(settings_path: str = None) -\u003e Optional[Dict[str, Any]]`\nParse Django settings.py or config files for database configuration.\n\n**Parameters:**\n- `settings_path`: Optional path to settings file\n\n**Returns:** Database configuration dictionary or None\n\n#### `get_connection(host: str, port: int, user: str, password: str, database: str = \"postgres\", auto_settings: bool = True, settings_path = None)`\nCreate async database connection.\n\n#### `show_databases(args)`\nList all databases with detailed information.\n\n#### `create_user_db(args)`\nCreate PostgreSQL user and database with proper privileges.\n\n## Error Handling\n\npsqlc includes comprehensive error handling:\n\n- Connection failures are clearly reported\n- Invalid queries show descriptive errors\n- Destructive operations require confirmation\n- Debug mode provides detailed error information\n\n## 💡 Examples\n\n### Example 1: Complete Database Setup\n\n```bash\n# Create user and database from Django settings\npsqlc create -U postgres\n\n# Verify creation\npsqlc show dbs\npsqlc show users\n\n# Check table structure\npsqlc show tables\npsqlc describe -t auth_user\n```\n\n### Example 2: Database Inspection\n\n```bash\n# Check database sizes\npsqlc show size\n\n# Check specific database details\npsqlc show size -d mydb\npsqlc show tables -d mydb\npsqlc show indexes -d mydb\n\n# Monitor connections\npsqlc show connections\n```\n\n### Example 3: Safe Query Execution\n\n```bash\n# Read-only query (safe)\npsqlc query -q \"SELECT COUNT(*) FROM users\" --readonly\n\n# Regular query with limit\npsqlc query -q \"SELECT * FROM logs ORDER BY created_at DESC\" --limit 20\n\n# Complex query\npsqlc query -q \"\nSELECT u.username, COUNT(o.id) as order_count\nFROM users u\nLEFT JOIN orders o ON u.id = o.user_id\nGROUP BY u.username\nORDER BY order_count DESC\n\" --readonly\n```\n\n### Example 4: Database Maintenance\n\n```bash\n# Backup database\npsqlc backup -d production_db\n\n# Check sizes before cleanup\npsqlc show size -d production_db\n\n# Drop old test database\npsqlc drop database -d old_test_db\n\n# Drop old user\npsqlc drop user -u old_test_user\n```\n\n### Example 5: Complete Workflow Example\n\n```bash\n# 1. Check existing databases\npsqlc show dbs\n\n# 2. Create new user and database\npsqlc create -u myapp -p mypass123 -d myapp_db\n\n# 3. List tables in new database\npsqlc show tables -d myapp_db\n\n# 4. Execute setup queries\npsqlc query -d myapp_db -q \"CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(100))\"\n\n# 5. Check table structure\npsqlc describe -d myapp_db -t users\n\n# 6. Monitor database size\npsqlc show size -d myapp_db\n\n# 7. Generate backup command\npsqlc backup -d myapp_db\n```\n\n### Example 6: Integration with Django Projects\n\nWhen working in a Django project directory, psqlc automatically detects your `settings.py`:\n\n```bash\ncd /path/to/your/django/project\npsqlc show tables  # Auto-detects database from settings.py\npsqlc describe -t auth_user  # No need to specify database\n```\n\n### Example 7: Production Monitoring\n\n```bash\n# Monitor active connections\npsqlc show connections\n\n# Check database sizes regularly\npsqlc show size\n\n# Monitor user activity\npsqlc show users\n```\n\n\n## 🔐 Security Best Practices\n\n1. **Never hardcode passwords** - Use environment variables or settings files\n2. **Use read-only mode** for SELECT queries in production\n3. **Always confirm** before dropping databases or users\n4. **Limit query results** to prevent memory issues\n5. **Use connection timeouts** (built-in: 10 seconds)\n6. **Regular backups** before major operations\n\n## 🐛 Troubleshooting\n\n### Enable Debug Mode\n\n```bash\npsqlc --debug show dbs\n```\n\n### Enable full traceback:\n\n```bash\nexport TRACEBACK=1\npsqlc show dbs\n```\n\nDebug mode shows:\n- Settings.py detection attempts\n- Connection details\n- Detailed error messages\n- full traceback\n\n### Common Issues\n\n### \"Connection Refused**\n\n```bash\n# Check if PostgreSQL is running\npsqlc -H localhost --port 5432 show dbs\n```\n\n#### \"Connection failed\"\n- Check hostname, port, username, and password\n- Verify PostgreSQL server is running\n- Check firewall settings\n\n```bash\n   # Provide password explicitly\npsqlc -U postgres -P yourpassword show dbs\n```\n\n#### \"Settings.py not found\"\n- Ensure settings.py exists in current directory or subdirectories\n- Try specifying the path explicitly\n- Use `--debug` to see search paths\n\n```bash\n# Specify settings file directly\npsqlc --debug show tables\n```\n\n#### \"Permission denied\"\n- Verify user has sufficient privileges\n- Some operations require superuser access\n- Check PostgreSQL user permissions\n\n## 📝 Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `DEBUG` | Enable debug output | `0` |\n| `TRACEBACK` | Show full tracebacks on errors | `0` |\n| `HOST` | Database host | empty/None |\n| `PORT` | Database port | `5432` |\n| `USER` | Database user | `postgres` |\n| `PASSWORD` | Database password | empty/None |\n| `DATABASE`/`DB_NAME`/`DB` | Database name | empty/None |\n\nSet environment variables:\n\n```bash\n# Linux/Mac\nexport DEBUG=1\npsqlc show dbs\n\n# Windows\nset DEBUG=1\npsqlc show dbs\n```\n\n## 🤝 Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 👤 Author\n\n[Hadi Cahyadi](mailto:cumulus13@gmail.com)\n    \n\n[![Buy Me a Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/cumulus13)\n\n[![Donate via Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/cumulus13)\n \n[Support me on Patreon](https://www.patreon.com/cumulus13)\n\n## 🙏 Acknowledgments\n\n- Built with [psycopg2](https://www.psycopg.org/) for PostgreSQL connectivity\n- Styled with [Rich](https://github.com/Textualize/rich) for beautiful terminal output\n- Argument parsing with [licface](https://github.com/cumulus13/licface) for custom help formatting\n\n## 📞 Support\n\nFor issues, questions, or contributions, please visit the project repository or contact the author.\n\n---\n\n**Note:** This tool is designed for PostgreSQL database management. Always test commands in a development environment before using in production.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcumulus13%2Fpsqlc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcumulus13%2Fpsqlc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcumulus13%2Fpsqlc/lists"}