Skip to main content

TypeDAL

PyPI - Version PyPI - Python Version
Code style: black License: MIT
su6 checks coverage.svg

Typing support for PyDAL. This package aims to improve the typing support for PyDAL. By using classes instead of the define_table method, type hinting the result of queries can improve the experience while developing. In the background, the queries are still generated and executed by pydal itself, this package only provides some logic to properly pass calls from class methods to the underlying db.define_table pydal Tables.

  • TypeDAL is the replacement class for DAL that manages the code on top of DAL.
  • TypedTable must be the parent class of any custom Tables you define (e.g. class SomeTable(TypedTable))
  • TypedField can be used instead of Python native types when extra settings (such as default) are required ( e.g. name = TypedField(str, default="John Doe")). It can also be used in an annotation (name: TypedField[str]) to improve editor support over only annotating with str.
  • TypedRows: can be used as the return type annotation of pydal's .select() and subscribed with the actual table class, so e.g. rows: TypedRows[SomeTable] = db(...).select(). When using the QueryBuilder, a TypedRows instance is returned by .collect().

Version 2.0 also introduces more ORM-like functionality. Most notably, a Typed Query Builder that sees your table classes as models with relationships to each other. See 3. Building Queries for more details.

Quickstart

uv pip install typedal
# alternative:
pip install typedal
from typedal import TypeDAL, TypedTable

db = TypeDAL("sqlite:memory")
# Alternatives:
# db = TypeDAL("sqlite://storage.sqlite")
# db = TypeDAL("postgres://user:password@localhost:5432/mydb")
# db = TypeDAL("mysql://user:password@localhost:3306/mydb")
# ...


@db.define()
class User(TypedTable):
    name: str
    age: int | None


User.insert(name="Alice", age=30)
adults = User.where(User.age >= 18).collect()
print(adults.column("name"))  # ['Alice']

If you are new to TypeDAL, start with:

  1. Getting Started
  2. Defining Tables
  3. Building Queries
  4. Relationships

CLI

The TypeDAL CLI provides a convenient interface for generating SQL migrations for edwh-migrate from PyDAL or TypeDAL configurations using pydal2sql. It offers various commands to streamline database management tasks.

Usage

typedal --help

Options

  • --show-config: Toggle to show configuration details. Default is no-show-config.
  • --version: Toggle to display version information. Default is no-version.
  • --install-completion: Install completion for the current shell.
  • --show-completion: Show completion for the current shell, for copying or customization.
  • --help: Display help message and exit.

Commands

  • cache.clear: Clear expired items from the cache.
  • cache.stats: Show caching statistics.
  • migrations.fake: Mark one or more migrations as completed in the database without executing the SQL code.
  • migrations.generate: Run pydal2sql based on the TypeDAL configuration.
  • migrations.run: Run edwh-migrate based on the TypeDAL configuration.
  • typescript.generate: Generate TypeScript interfaces from TypeDAL models.
  • setup: Interactively setup a [tool.typedal] entry in the local pyproject.toml.

Configuration

TypeDAL and its CLI can be configured via pyproject.toml.
See 6. Migrations for more information about configuration.

TypeDAL for PyDAL users - Quick Overview

Below you'll find a quick overview of translation from pydal to TypeDAL.
For more info, see the docs.


Translations from pydal to typedal

Description pydal typedal typedal alternative(s) ...
Setup
from pydal import DAL, Field

db = DAL(...)
from typedal import TypeDAL, TypedTable, TypedField

db = TypeDAL(...)
Table Definitions
db.define_table(
    "table_name",
    Field("fieldname", "string", required=True),
    Field("otherfield", "float"),
    Field("yet_another", "text", default="Something"),
)
@db.define
class TableName(TypedTable):
    fieldname: str
    otherfield: float | None
    yet_another = TypedField(str, type="text", default="something", required=False)
import typing


class TableName(TypedTable):
    fieldname: TypedField[str]
    otherfield: TypedField[typing.Optional[float]]
    yet_another = TextField(default="something", required=False)


db.define(TableName)
Insert
db.table_name.insert(fieldname="value")
TableName.insert(fieldname="value")
# the old syntax is also still supported:
db.table_name.insert(fieldname="value")
(quick) Select
# all:
all_rows = db(db.table_name).select()  # -> Any (Rows)
# some:
rows = db((db.table_name.id > 5) & (db.table_name.id < 50)).select(db.table_name.id)
# one:
row = db.table_name(id=1)  # -> Any (Row)
# all:
all_rows = TableName.collect()  # or .all()
# some:
# order of select and where is interchangeable here
rows = TableName.select(Tablename.id).where(TableName.id > 5).where(TableName.id < 50).collect()
# one:
row = TableName(id=1)  # or .where(...).first()
# you can also still use the old syntax and type hint on top of it;
# all:
all_rows: TypedRows[TableName] = db(db.table_name).select()
# some:
rows: TypedRows[TableName] = db((db.table_name.id > 5) & (db.table_name.id < 50)).select(db.table_name.id)
# one:
row: TableName = db.table_name(id=1)

All Types

See 2. Defining Tables

Helpers

TypeDAL provides some utility functions to interact with the underlying pyDAL objects:

  • get_db(TableName):
    Retrieve the DAL instance associated with a given TypedTable or pyDAL Table.

  • get_table(TableName):
    Access the original PyDAL Table from a TypedTable instance (db.table_name).

  • get_field(TableName.fieldname):
    Get the pyDAL Field from a TypedField. This ensures compatibility when interacting directly with PyDAL.

These helpers are useful for scenarios where direct access to the PyDAL objects is needed while still using TypeDAL. An example of this is when you need to do a db.commit() but you can't import db directly:

from typedal.helpers import get_db  # , get_table, get_field

MyTable.insert(...)
db = get_db(MyTable)
db.commit()  # this is usually done automatically but sometimes you want to manually commit.

Caveats

  • Some editors (notably PyCharm) cannot always distinguish class-level and instance-level access on the same symbol. For example, Model.somefield is a field descriptor (query operations like .belongs()), while model.somefield is the runtime value (for example list[str]).
  • TypedField limitations; Since pydal implements some magic methods to perform queries, some features of typing will not work on a typed field: typing.Optional or a union (Field() | None) will result in errors. The only way to make a typedfield optional right now, would be to set required=False as an argument yourself. This is also a reason why typing.get_type_hints is not a complete solution.

Download files

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

Source Distribution

typedal-5.0.0.tar.gz (348.0 kB view details)

Uploaded Source

Built Distribution

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

typedal-5.0.0-py3-none-any.whl (100.6 kB view details)

Uploaded Python 3

File details

Details for the file typedal-5.0.0.tar.gz.

File metadata

  • Download URL: typedal-5.0.0.tar.gz
  • Upload date:
  • Size: 348.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"PikaOS","version":"4","id":"nest","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for typedal-5.0.0.tar.gz
Algorithm Hash digest
SHA256 1c4851cd9a52fd207b01fb9e00a8f95c72281b0fc7b83873038580623db7575f
MD5 3d4ac567bd00f3119c2148392f80c426
BLAKE2b-256 6eea468d3fc870f5d91755da12ce78a3b2a88d4648ac4b3951d7f97895780fa6

See more details on using hashes here.

File details

Details for the file typedal-5.0.0-py3-none-any.whl.

File metadata

  • Download URL: typedal-5.0.0-py3-none-any.whl
  • Upload date:
  • Size: 100.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.12.5 {"installer":{"name":"uv","version":"0.12.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"PikaOS","version":"4","id":"nest","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for typedal-5.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fb8a13e54bc25b09535b47962eecc74a1086d25116a569e5c7895a5b08aa8dc2
MD5 47408a38e21f07b90c4b6eb85841b2a3
BLAKE2b-256 0a2841a004330072c7d2426ee733926418fc61fc8c3f2264ebce5b6fc69941f2

See more details on using hashes here.

Release history Release notifications | RSS feed

Supported by

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