Skip to main content

Python wrapper for HTTPS requesting SQL via Go

Project description

PyGoSQL

Python Version License: MIT Code Style: Black

A powerful Python wrapper for HTTPS-based SQL operations via Go backend services.

Basic Usage

import asyncio
from pathlib import Path
from pygosql import PyGoSQL

async def main():
    # Initialize client with your Go SQL server
    client = PyGoSQL(
        sql_root=Path("./sql"),           # Directory containing SQL files
        verbose=True                      # Enable detailed logging
    )
    
    # Launch the server and discover endpoints
    await client.launch()
    
    # Use discovered table namespaces
    users = await client.users.select()
    new_user = await client.users.insert(name="Alice", email="alice@example.com")
    
    # Access server health and documentation
    health_status = await client.health()
    api_docs = await client.docs()
    
    # Clean shutdown
    await client.stop()

# Run the async function
asyncio.run(main())

Advanced Configuration

from pygosql import PyGoSQL
from pathlib import Path

client = PyGoSQL(
    sql_root=Path("./database/queries"),  # Custom SQL directory
    go_file=Path("./server/main.go"),     # Custom Go server location
    db_path=Path("./data/app.db"),        # Database file path
    port=8080,                            # Specific port (auto-assigned if None)
    base_url="/api/v2",                   # Custom API base path
    debug=True,                           # Enable debug mode
    cors=True,                            # Enable CORS headers
    verbose=True                          # Detailed logging
)

PyGoSQL follows a specific directory structure that maps SQL files to HTTP endpoints. Understanding this structure is crucial for effective customization.

Required Directory Layout

<sql_root>/
├── <Database>/
│   ├── <database>.db              # SQLite database file
│   ├── GET/                       # Global GET operations
│   │   └── *.sql                  # SQL files for GET endpoints
│   ├── POST/                      # Global POST operations
│   │   └── *.sql                  # SQL files for POST endpoints
│   ├── DELETE/                    # Global DELETE operations
│   │   └── *.sql                  # SQL files for DELETE endpoints
│   └── PUT/                       # Global PUT operations
│       └── *.sql                  # SQL files for PUT endpoints
├── schema.sql                     # Database schema definition
└── <Tables>/
    └── <TableName>/               # Table-specific operations
        ├── GET/
        │   ├── select.sql         # Standard select operation
        │   └── fetch_by_role.sql  # Custom query example
        ├── POST/
        │   └── insert.sql         # Standard insert operation
        ├── DELETE/
        │   └── delete.sql         # Standard delete operation
        └── PUT/
            └── update.sql         # Standard update operation

Example Project Structure

project/
├── main.py                        # Your Python application
├── gosql/
│   └── main.go                    # Go server implementation
└── sql/                           # SQL root directory
    ├── database/
    │   ├── app.db                 # SQLite database
    │   ├── GET/
    │   │   └── health_check.sql   # System-wide health check
    │   ├── POST/
    │   │   └── backup.sql         # Database backup operation
    │   ├── DELETE/
    │   └── PUT/
    ├── schema.sql                 # CREATE TABLE statements
    └── tables/
        ├── users/
        │   ├── GET/
        │   │   ├── select.sql     # SELECT * FROM users
        │   │   ├── by_email.sql   # SELECT * FROM users WHERE email = ?
        │   │   └── active.sql     # SELECT * FROM users WHERE active = 1
        │   ├── POST/
        │   │   └── insert.sql     # INSERT INTO users (...)
        │   ├── DELETE/
        │   │   └── delete.sql     # DELETE FROM users WHERE id = ?
        │   └── PUT/
        │       └── update.sql     # UPDATE users SET ... WHERE id = ?
        ├── orders/
        │   ├── GET/
        │   │   ├── select.sql
        │   │   └── by_user.sql    # SELECT * FROM orders WHERE user_id = ?
        │   ├── POST/
        │   │   └── insert.sql
        │   ├── DELETE/
        │   │   └── delete.sql
        │   └── PUT/
        │       └── update.sql
        └── products/
            ├── GET/
            │   ├── select.sql
            │   ├── in_stock.sql   # SELECT * FROM products WHERE stock > 0
            │   └── by_category.sql
            ├── POST/
            │   └── insert.sql
            ├── DELETE/
            │   └── delete.sql
            └── PUT/
                └── update.sql

Endpoint Mapping

PyGoSQL automatically maps your directory structure to HTTP endpoints:

File Path HTTP Method Generated Endpoint Python Function
tables/users/GET/select.sql GET /api/v1/users/select client.users.select()
tables/users/GET/by_email.sql GET /api/v1/users/by_email client.users.by_email()
tables/users/POST/insert.sql POST /api/v1/users/insert client.users.insert()
tables/orders/GET/by_user.sql GET /api/v1/orders/by_user client.orders.by_user()
database/GET/health_check.sql GET /api/v1/health_check client.system.health_check()

Supports Templating via {{}}

    // Regex to find all {{variable}} patterns
    re := regexp.MustCompile(`\{\{(\w+)\}\}`)

    // Find all matches first for logging
    matches := re.FindAllString(sqlContent, -1)
    log.Printf("   - Found template variables: %v", matches)

    result := re.ReplaceAllStringFunc(sqlContent, func(match string) string {
        // Extract variable name from {{variable}}
        varName := strings.Trim(match, "{}")

        // If variable exists in params, replace it
        if value, exists := allParams[varName]; exists {
            replacement := fmt.Sprintf("%v", value)
            log.Printf("   - Replacing %s with '%s'", match, replacement)
            return replacement
        }

        // Leave unmatched templates as-is
        log.Printf("   - No replacement found for %s - leaving as-is", match)
        return match
    })

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pygosql-0.1.0.tar.gz (12.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pygosql-0.1.0-py3-none-any.whl (11.8 kB view details)

Uploaded Python 3

File details

Details for the file pygosql-0.1.0.tar.gz.

File metadata

  • Download URL: pygosql-0.1.0.tar.gz
  • Upload date:
  • Size: 12.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for pygosql-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f29ce3bb5dab9b854e7f943187771f60b1cebd9a7e3d34f972c46e883af1087e
MD5 cb4a57996c613ba73c10345411cc31b0
BLAKE2b-256 bf44d9778f3441ce41ed2346d03a10d8c2e6c0da29c4cea0b60fdb657f5b6a4d

See more details on using hashes here.

File details

Details for the file pygosql-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: pygosql-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for pygosql-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7fd253cf32c1c3c7347c25f12751c09e1f96c0cf749f2926a6c251a30cf41c2f
MD5 537b07c7f00cd9aeeb4174138a27ecb1
BLAKE2b-256 6ddfb45bf3bc1ef127f7bd7406394b350dc7a484e847a0f61a2acfd406421654

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page