CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-edgedb

EdgeDB Python driver providing both blocking IO and asyncio implementations for connecting to and interacting with EdgeDB databases.

Pending
Overview
Eval results
Files

data-types.mddocs/

Data Types

EdgeDB data type representations in Python, providing native Python types for EdgeDB's type system including scalar types, collections, and specialized types.

Capabilities

Core Collection Types

EdgeDB collection types mapped to Python equivalents with enhanced functionality.

class Object:
    """
    EdgeDB object type representation.
    
    Provides attribute access to object properties and links,
    allowing both dot notation and dictionary-style access.
    """
    
    def __getattr__(self, name: str) -> Any:
        """Get object attribute by name."""
    
    def __getitem__(self, key: str) -> Any:
        """Get object attribute by key."""
    
    def __contains__(self, key: str) -> bool:
        """Check if object has attribute."""

# Type aliases for EdgeDB collections
Set = list  # EdgeDB set mapped to Python list
Array = list  # EdgeDB array mapped to Python list
Tuple = tuple  # EdgeDB tuple mapped to Python tuple

class NamedTuple(tuple):
    """
    EdgeDB named tuple representation.
    
    Extends Python tuple with named field access.
    """
    
    def __new__(cls, values, names):
        """Create named tuple with field names."""
    
    def __getattr__(self, name: str) -> Any:
        """Access field by name."""

class Link:
    """
    EdgeDB link representation.
    
    Represents a link to another object with link properties.
    """

class LinkSet:
    """
    EdgeDB link set representation.
    
    Represents a set of links with associated link properties.
    """

class EnumValue:
    """
    EdgeDB enum value representation.
    
    Provides string-like behavior for enum values.
    """
    
    def __str__(self) -> str:
        """String representation of enum value."""
    
    def __eq__(self, other) -> bool:
        """Compare enum values."""

Temporal Types

EdgeDB temporal and duration types with Python integration.

class RelativeDuration:
    """
    EdgeDB cal::relative_duration type.
    
    Represents a duration with years, months, days, hours, minutes,
    seconds, and microseconds components.
    """
    
    def __init__(
        self,
        *,
        years: int = 0,
        months: int = 0,
        days: int = 0,
        hours: int = 0,
        minutes: int = 0,
        seconds: int = 0,
        microseconds: int = 0
    ):
        """Create a relative duration."""
    
    @property
    def years(self) -> int:
        """Years component."""
    
    @property
    def months(self) -> int:
        """Months component."""
    
    @property
    def days(self) -> int:
        """Days component."""
    
    @property
    def hours(self) -> int:
        """Hours component."""
    
    @property
    def minutes(self) -> int:
        """Minutes component."""
    
    @property
    def seconds(self) -> int:
        """Seconds component."""
    
    @property
    def microseconds(self) -> int:
        """Microseconds component."""
    
    def __add__(self, other) -> RelativeDuration:
        """Add durations."""
    
    def __sub__(self, other) -> RelativeDuration:
        """Subtract durations."""

class DateDuration:
    """
    EdgeDB cal::date_duration type.
    
    Represents a date-only duration with years, months, and days.
    """
    
    def __init__(
        self,
        *,
        years: int = 0,
        months: int = 0,
        days: int = 0
    ):
        """Create a date duration."""
    
    @property
    def years(self) -> int:
        """Years component."""
    
    @property
    def months(self) -> int:
        """Months component."""
    
    @property
    def days(self) -> int:
        """Days component."""
    
    def __add__(self, other) -> DateDuration:
        """Add date durations."""
    
    def __sub__(self, other) -> DateDuration:
        """Subtract date durations."""

Configuration Types

EdgeDB configuration-specific types.

class ConfigMemory:
    """
    EdgeDB cfg::memory type.
    
    Represents memory size values with unit parsing.
    """
    
    def __init__(self, value: Union[int, str]):
        """
        Create memory configuration value.
        
        Parameters:
        - value: Memory value as int (bytes) or string with unit (e.g., "1GB", "512MB")
        """
    
    @property
    def bytes(self) -> int:
        """Memory value in bytes."""
    
    def __str__(self) -> str:
        """String representation with appropriate unit."""

Range Types

EdgeDB range and multirange types for representing value ranges.

class Range:
    """
    EdgeDB range type representation.
    
    Represents a contiguous range of values with inclusive/exclusive bounds.
    """
    
    def __init__(
        self,
        lower: Optional[Any] = None,
        upper: Optional[Any] = None,
        *,
        inc_lower: bool = True,
        inc_upper: bool = False,
        empty: bool = False
    ):
        """
        Create a range.
        
        Parameters:
        - lower: Lower bound value
        - upper: Upper bound value
        - inc_lower: Whether lower bound is inclusive
        - inc_upper: Whether upper bound is inclusive
        - empty: Whether range is empty
        """
    
    @property
    def lower(self) -> Optional[Any]:
        """Lower bound value."""
    
    @property
    def upper(self) -> Optional[Any]:
        """Upper bound value."""
    
    @property
    def inc_lower(self) -> bool:
        """Whether lower bound is inclusive."""
    
    @property
    def inc_upper(self) -> bool:
        """Whether upper bound is inclusive."""
    
    @property
    def is_empty(self) -> bool:
        """Whether range is empty."""
    
    def __contains__(self, value: Any) -> bool:
        """Check if value is in range."""
    
    def __eq__(self, other) -> bool:
        """Compare ranges."""

class MultiRange:
    """
    EdgeDB multirange type representation.
    
    Represents a collection of non-overlapping ranges.
    """
    
    def __init__(self, ranges: List[Range]):
        """
        Create a multirange from list of ranges.
        
        Parameters:
        - ranges: List of Range objects
        """
    
    @property
    def ranges(self) -> List[Range]:
        """List of constituent ranges."""
    
    def __contains__(self, value: Any) -> bool:
        """Check if value is in any range."""
    
    def __iter__(self):
        """Iterate over constituent ranges."""
    
    def __len__(self) -> int:
        """Number of constituent ranges."""

Usage Examples

Working with Objects

import edgedb

client = edgedb.create_client()

# Query returns Object instances
user = client.query_single("SELECT User { name, email, profile: { bio, avatar } }")

# Access attributes with dot notation
print(user.name)
print(user.email)
print(user.profile.bio)

# Access attributes with dictionary notation
print(user['name'])
print(user['profile']['avatar'])

# Check if attribute exists
if 'phone' in user:
    print(user.phone)

Working with Collections

import edgedb

client = edgedb.create_client()

# Sets and arrays are returned as Python lists
articles = client.query("SELECT Article { title, tags }")

for article in articles:
    print(f"Title: {article.title}")
    # tags is a list (EdgeDB array/set)
    for tag in article.tags:
        print(f"  Tag: {tag}")

# Named tuples
coordinates = client.query_single("SELECT (x := 10, y := 20)")
print(f"X: {coordinates.x}, Y: {coordinates.y}")

Working with Enum Values

import edgedb

client = edgedb.create_client()

user = client.query_single("SELECT User { name, status }")

# Enum values behave like strings
if user.status == "active":
    print("User is active")

# String representation
print(f"User status: {user.status}")

Working with Temporal Types

import edgedb
from edgedb import RelativeDuration, DateDuration

client = edgedb.create_client()

# Create duration objects
age_duration = RelativeDuration(years=25, months=6, days=15)
project_duration = DateDuration(months=6, days=10)

# Use in queries
client.execute(
    "UPDATE User SET { age_duration := $duration } FILTER .id = $id",
    duration=age_duration,
    id="123e4567-e89b-12d3-a456-426614174000"
)

# Query returns duration objects
user = client.query_single("SELECT User { name, age_duration }")
print(f"User age: {user.age_duration.years} years, {user.age_duration.months} months")

Working with Ranges

import edgedb
from edgedb import Range, MultiRange

client = edgedb.create_client()

# Create ranges
price_range = Range(100, 500, inc_lower=True, inc_upper=False)  # [100, 500)
date_range = Range(
    lower=datetime.date(2024, 1, 1),
    upper=datetime.date(2024, 12, 31),
    inc_lower=True,
    inc_upper=True
)  # [2024-01-01, 2024-12-31]

# Use ranges in queries
products = client.query(
    "SELECT Product { name, price } FILTER .price <@ $price_range",
    price_range=price_range
)

# Check if value is in range
if 250 in price_range:
    print("250 is in price range")

# Work with multiranges
availability = MultiRange([
    Range(9, 12, inc_lower=True, inc_upper=False),    # [9, 12)
    Range(13, 17, inc_lower=True, inc_upper=False)    # [13, 17)
])

if 10 in availability:
    print("10 is in available hours")

Working with Configuration Types

import edgedb
from edgedb import ConfigMemory

# Create memory configuration values
memory_limit = ConfigMemory("2GB")
cache_size = ConfigMemory("512MB")
buffer_size = ConfigMemory(1048576)  # 1MB in bytes

print(f"Memory limit: {memory_limit.bytes} bytes")
print(f"Formatted: {memory_limit}")  # Automatically formats with appropriate unit

Type Checking and Conversion

import edgedb

client = edgedb.create_client()

result = client.query_single("SELECT User { name, created_at, tags }")

# Check types
print(f"Name type: {type(result.name)}")          # <class 'str'>
print(f"Created type: {type(result.created_at)}")  # <class 'datetime.datetime'>
print(f"Tags type: {type(result.tags)}")          # <class 'list'>

# EdgeDB objects are instances of Object
print(f"Result type: {type(result)}")             # <class 'edgedb.Object'>
print(f"Is EdgeDB Object: {isinstance(result, edgedb.Object)}")  # True

Complex Nested Types

import edgedb

client = edgedb.create_client()

# Query with complex nested structure
blog_post = client.query_single("""
    SELECT BlogPost {
        title,
        content,
        author: { name, email },
        tags,
        comments: {
            content,
            author: { name },
            created_at,
            replies: {
                content,
                author: { name },
                created_at
            }
        },
        metadata: {
            word_count,
            reading_time,
            categories
        }
    } FILTER .id = $id
""", id="123e4567-e89b-12d3-a456-426614174000")

# Navigate nested structure
print(f"Post: {blog_post.title}")
print(f"Author: {blog_post.author.name}")
print(f"Tags: {', '.join(blog_post.tags)}")
print(f"Word count: {blog_post.metadata.word_count}")

for comment in blog_post.comments:
    print(f"Comment by {comment.author.name}: {comment.content}")
    for reply in comment.replies:
        print(f"  Reply by {reply.author.name}: {reply.content}")

Install with Tessl CLI

npx tessl i tessl/pypi-edgedb

docs

ai-integration.md

client-management.md

configuration-options.md

data-types.md

error-handling.md

index.md

query-execution.md

schema-introspection.md

transaction-management.md

tile.json