Skip to main content

Add your description here

Project description

PocketBase ORM

A Python ORM (Object-Relational Mapper) for PocketBase that provides Pydantic model integration and automatic schema synchronization.

Features

  • Pydantic model integration for data validation and serialization
  • Automatic schema synchronization with PocketBase collections
  • Support for all PocketBase field types including relations and file uploads
  • Simple and intuitive API for CRUD operations
  • Type hints and documentation for better development experience
  • Built-in logging for debugging and troubleshooting

Installation

uv install pocketbase-orm

Quick Start

from pocketbase import PocketBase
from pocketbase_orm import PBModel
from pydantic import EmailStr, AnyUrl, Field
from typing import List, Union
from datetime import datetime, timezone
from pocketbase.client import FileUpload

# Define your models
class RelatedModel(PBModel):
    name: str

    class Meta:
        collection_name = "related_models"

class Example(PBModel):
    text_field: str
    number_field: int
    is_active: bool
    url_field: AnyUrl
    created_at: datetime
    options: List[str]
    email_field: EmailStr | None = None
    related_model: Union[RelatedModel, str] = Field(..., description="Related model reference")
    image: FileUpload | str = Field(default=None, description="Image file upload")

# Initialize PocketBase client and bind it to the ORM
client = PocketBase("YOUR_POCKETBASE_URL")
client.admins.auth_with_password("admin@example.com", "password")
PBModel.bind_client(client)

# Sync collection schemas
RelatedModel.sync_collection()
Example.sync_collection()

# Create and save records
related_model = RelatedModel(name="Related Model")
related_model.save()

# Create a new record with file upload
with open("image.png", "rb") as f:
    example = Example(
        text_field="Test with image",
        number_field=123,
        is_active=True,
        email_field="test@example.com",
        url_field="http://example.com",
        created_at=datetime.now(timezone.utc),
        options=["option1", "option2"],
        related_model=related_model.id,
        image=FileUpload(("image.png", f))
    )
    example.save()

# Query records
examples = Example.get_full_list()
single_example = Example.get_one("RECORD_ID")
filtered_example = Example.get_first_list_item(filter='email_field = "test@example.com"')

# Get file contents
image_bytes = example.get_file_contents("image")

Model Definition

Models inherit from PBModel and use Pydantic field types:

class MyModel(PBModel):
    name: str
    age: int
    email: EmailStr | None = None
    
    class Meta:
        collection_name = "custom_collection_name"  # Optional

The collection name will be automatically derived from the class name (pluralized) if not specified in the Meta class.

Supported Field Types

  • Text: str
  • Number: int, float
  • Boolean: bool
  • Email: EmailStr
  • URL: AnyUrl
  • DateTime: datetime
  • JSON: List, Dict
  • File: FileUpload | str
  • Relation: Union[RelatedModel, str]

API Reference

Class Methods

  • bind_client(client: PocketBase): Bind PocketBase client to the model class
  • sync_collection(): Create or update the collection schema in PocketBase
  • get_one(id: str, **kwargs) -> T: Get a single record by ID
  • get_list(*args, **kwargs) -> List[T]: Get a paginated list of records
  • get_full_list(*args, **kwargs) -> List[T]: Get all records
  • get_first_list_item(*args, **kwargs) -> T: Get the first matching record
  • delete(*args, **kwargs): Delete a record

Instance Methods

  • save() -> T: Create or update the record
  • get_file_contents(field: str) -> bytes: Get the contents of a file field

Error Handling

The library includes comprehensive error handling and logging:

try:
    record = MyModel.get_one("non_existent_id")
except Exception as e:
    logger.error(f"Error fetching record: {e}")

Logging

The library uses Python's built-in logging module. To enable debug logging:

import logging
logging.getLogger("pocketbase_orm").setLevel(logging.DEBUG)

Limitations

  • The ORM currently supports basic CRUD operations and schema synchronization
  • Complex queries should use the PocketBase client directly
  • Relationship handling is limited to single relations

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

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

pocketbase_orm-0.3.0.tar.gz (7.3 kB view details)

Uploaded Source

Built Distribution

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

pocketbase_orm-0.3.0-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pocketbase_orm-0.3.0.tar.gz
  • Upload date:
  • Size: 7.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.5.14

File hashes

Hashes for pocketbase_orm-0.3.0.tar.gz
Algorithm Hash digest
SHA256 1931cf4a3333e3666527b4777dbc793bae3ab64fde1cc6e02b91ef0b10a99c70
MD5 fad164ac5b39f3307d37f2a8453b50f3
BLAKE2b-256 f47cf6e3cdfcdd3c9a9172a2e79555ffeccf0207ac2ceb0cd9601e19601696ca

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pocketbase_orm-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9786368b3472c6c36878554770b0bea66c26e1791652a45529758cdad5c35e5a
MD5 47a43d7722985440530a7e731539474c
BLAKE2b-256 756d0ac32db875dc5c7336d2359634eb5a6080b9040697536b77e095083595b1

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