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.3.0.tar.gz (33.0 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.3.0-py3-none-any.whl (37.6 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pygosql-0.3.0.tar.gz
Algorithm Hash digest
SHA256 65af049cae653dcc4e32942a80b4ca78eed6bb4562afb0769f6b2f77c445101f
MD5 30573c6b34948bb677867ead1b710ea4
BLAKE2b-256 67d14d39478508521b5fd0971fc0fa9aeb4528d3ed9a0882f128dd550d23d030

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pygosql-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 37.6 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.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 61c98bde6c96cf42b4c0af3a4043e500247adc2a9389a8c135344271c0dcd906
MD5 9a8135b5f9b4cfb705c91d0a38553377
BLAKE2b-256 ec4d12f4b0ee1f5b41ff1ede3e3aba8acd6821f889afc9d817a028b32995eb0f

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