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.2.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.2.0-py3-none-any.whl (37.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pygosql-0.2.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.2.0.tar.gz
Algorithm Hash digest
SHA256 e23fbe23893a8b7b41f78fe2b863cc42a945e6699623e8e167493fbfc9a4aca4
MD5 6a79b6edf27f7462f9f6694bd2364c8e
BLAKE2b-256 afdcafe7e924e913491c9a16bb83511c4073972d9fb48b0c7c8a9a3d00f999c6

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pygosql-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 37.4 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.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f2e1509e4d859e8d862bd4dc7a47c5649965c2245d985c7b1a9c62804e96df61
MD5 1f8a129cebccd415a29951d2c2320544
BLAKE2b-256 44702fce5988482c0cebb981cca8ab92177b9d840b1344cf66dedc21bcb420ed

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