Registry / database / pgspecial

pgspecial

JSON →
library2.2.1pypypi✓ verified 85d ago

pgspecial is a Python package that provides an API to execute PostgreSQL meta-commands, also known as 'special' or 'backslash commands', typically used in interactive PostgreSQL clients like psql or pgcli. It offers programmatic access to these commands, allowing developers to integrate them into their own applications. The current version is 2.2.1, and it is actively maintained, with releases often coinciding with its primary consumer, pgcli.

pip install pgspecial
INSTALL
IMPORT
SIG · PGSPECIAL
P
pgspecial
databasepythonv2.2.1
Install
2.0s avg
Import
Disk
20MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.2.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.000s · 21.4MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 2.0s · import 0.000s · 22MB
20MB installed
● package 20MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PGSpecial
from pgspecial.main import PGSpecial
NamedQueries
from pgspecial.namedqueries import NamedQueries
import pgspecial.namedqueries
The common pattern is to import the NamedQueries class directly for instantiation or class-level attribute setting.

This quickstart demonstrates how to initialize `PGSpecial` and use its `execute` method with a `psycopg2` database cursor to run PostgreSQL meta-commands. It includes an example of listing tables (`\dt`) and describing a specific table (`\d table_name`). Ensure you have a running PostgreSQL instance and provide connection details, ideally via environment variables.

import os import psycopg2 from pgspecial.main import PGSpecial try: # Connection details from environment variables for security/flexibility DB_NAME = os.environ.get('PG_DB_NAME', 'postgres') DB_USER = os.environ.get('PG_DB_USER', 'postgres') DB_PASSWORD = os.environ.get('PG_DB_PASSWORD', '') DB_HOST = os.environ.get('PG_DB_HOST', 'localhost') DB_PORT = os.environ.get('PG_DB_PORT', '5432') conn = psycopg2.connect( dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST, port=DB_PORT ) cur = conn.cursor() pgspecial = PGSpecial() # Example: List tables in the current database print("\n--- Executing \\dt ---") for title, rows, headers, status in pgspecial.execute(cur, '\\dt'): if title: print(f"Title: {title}") if headers: print(f"Headers: {', '.join(headers)}") if rows: for row in rows: print(f"Row: {row}") if status: print(f"Status: {status}") # Example: Describe a specific table (if one exists, e.g., 'your_table_name') # You might need to create a dummy table for this to show results try: cur.execute("CREATE TABLE IF NOT EXISTS pgspecial_example (id SERIAL PRIMARY KEY, name VARCHAR(50))") conn.commit() print("\n--- Executing \\d pgspecial_example ---") for title, rows, headers, status in pgspecial.execute(cur, '\\d pgspecial_example'): if title: print(f"Title: {title}") if headers: print(f"Headers: {', '.join(headers)}") if rows: for row in rows: print(f"Row: {row}") if status: print(f"Status: {status}") except psycopg2.Error as e: print(f"Could not create/describe example table: {e}") except psycopg2.Error as e: print(f"Error connecting to PostgreSQL: {e}") print("Please ensure PostgreSQL is running and connection details (PG_DB_NAME, PG_DB_USER, PG_DB_PASSWORD, PG_DB_HOST, PG_DB_PORT) are correct.") finally: if 'conn' in locals() and conn: conn.close()
Debug
Known issues
gotchaThe `PGSpecial.execute()` method requires an active `psycopg2` (or compatible DB-API 2.0) cursor object as its first argument. Passing `None` or an invalid cursor will result in errors.
fix
Always provide a valid database cursor obtained from an active database connection to `pgspecial.execute()`.
affects: All
gotchapgspecial is designed to handle PostgreSQL meta-commands (e.g., `\d`, `\l`), not standard SQL queries. Attempting to execute `SELECT * FROM table;` through `pgspecial.execute()` will likely not work as expected or raise an error; use the database cursor directly for SQL.
fix
Differentiate between meta-commands (for `pgspecial`) and SQL queries (for the database cursor). For SQL, call `cursor.execute("SELECT ...")`.
affects: All
gotchaTo use features like named queries from configuration files, the `configobj` package is required, and `NamedQueries.instance` needs to be explicitly initialized. This is not part of the core `PGSpecial` class.
fix
Install `configobj` (`pip install configobj`) and initialize `NamedQueries.instance` from your configuration file as shown in the documentation: `NamedQueries.instance = NamedQueries.from_config(ConfigObj('~/.config_file_name'))`.
affects: All
breakingSupport for Python 3.3 was removed in `pgspecial` versions around 1.10.0 (released March 2018). Newer versions (including 2.x) require Python 3.9 or later.
fix
Ensure your environment uses Python 3.9 or newer. The `requires_python` metadata for 2.2.1 already enforces `>=3.9`.
affects: <=1.9.x to >=1.10.x and 2.x
Errors
Common errors & fixes
KeyError: 'SELECT'
This error occurs when attempting to execute a standard SQL query (like 'SELECT') using `pgspecial.execute()`, which is designed only for PostgreSQL meta-commands (backslash commands like `\d`, `\l`).
fix
Differentiate between meta-commands and SQL queries; use the database cursor directly for SQL queries. Example: `cursor.execute("SELECT * FROM my_table;")` for SQL, and `pgspecial.execute(cursor, "\\d my_table")` for meta-commands.
ModuleNotFoundError: No module named 'typing_extensions'
This error indicates a missing dependency, `typing_extensions`, which is required by `psycopg` (a dependency of `pgspecial`) for type hinting support.
fix
Install the missing package: `pip install typing-extensions`.
ImportError: pgspecial not installed
This error can occur even if `pgspecial` is installed, often due to an incorrect Python environment, an un-refreshed Jupyter kernel, or issues with how the environment is being accessed.
fix
Ensure you are in the correct Python environment where `pgspecial` is installed. If using an IDE or Jupyter, restart the kernel or the application to refresh the environment's package paths. Verify installation with `pip show pgspecial`.
'ProtocolSafeCursor' object has no attribute 'mogrify'
This error typically arises from an incompatibility between `pgspecial` and the underlying PostgreSQL driver (`psycopg2` vs. `psycopg3`). Older versions of `pgspecial` might expect methods like `mogrify` that are present in `psycopg2` but not in `psycopg3`'s cursor objects.
fix
Ensure that `pgspecial` and your `psycopg` driver (e.g., `psycopg2` or `psycopg3`) are compatible versions. Often, upgrading `pgspecial` to its latest version will resolve compatibility issues with newer `psycopg` drivers. If using `psycopg3`, ensure your `pgspecial` version explicitly supports it.
Upgrade
Version history
2.2.1latest on PyPI · released Apr 28, 2025
Audit
Dependencies
clickrequiredCommand-line interface toolkit dependency.
psycopg2optionalCommonly used PostgreSQL adapter for database connections required by quickstart examples and typical usage. While 'psycopg' is also seen as a dependency in some contexts, psycopg2 is prevalent in examples.
sqlparserequiredSQL parsing library used internally.
configobjoptionalRequired for loading named queries from configuration files.
Agent activity
4 hits · last 30 days
node
4
Resources
pgspecial — pip install pgspecial · libregistry