0
# Data Types
1
2
EdgeDB data type representations in Python, providing native Python types for EdgeDB's type system including scalar types, collections, and specialized types.
3
4
## Capabilities
5
6
### Core Collection Types
7
8
EdgeDB collection types mapped to Python equivalents with enhanced functionality.
9
10
```python { .api }
11
class Object:
12
"""
13
EdgeDB object type representation.
14
15
Provides attribute access to object properties and links,
16
allowing both dot notation and dictionary-style access.
17
"""
18
19
def __getattr__(self, name: str) -> Any:
20
"""Get object attribute by name."""
21
22
def __getitem__(self, key: str) -> Any:
23
"""Get object attribute by key."""
24
25
def __contains__(self, key: str) -> bool:
26
"""Check if object has attribute."""
27
28
# Type aliases for EdgeDB collections
29
Set = list # EdgeDB set mapped to Python list
30
Array = list # EdgeDB array mapped to Python list
31
Tuple = tuple # EdgeDB tuple mapped to Python tuple
32
33
class NamedTuple(tuple):
34
"""
35
EdgeDB named tuple representation.
36
37
Extends Python tuple with named field access.
38
"""
39
40
def __new__(cls, values, names):
41
"""Create named tuple with field names."""
42
43
def __getattr__(self, name: str) -> Any:
44
"""Access field by name."""
45
46
class Link:
47
"""
48
EdgeDB link representation.
49
50
Represents a link to another object with link properties.
51
"""
52
53
class LinkSet:
54
"""
55
EdgeDB link set representation.
56
57
Represents a set of links with associated link properties.
58
"""
59
60
class EnumValue:
61
"""
62
EdgeDB enum value representation.
63
64
Provides string-like behavior for enum values.
65
"""
66
67
def __str__(self) -> str:
68
"""String representation of enum value."""
69
70
def __eq__(self, other) -> bool:
71
"""Compare enum values."""
72
```
73
74
### Temporal Types
75
76
EdgeDB temporal and duration types with Python integration.
77
78
```python { .api }
79
class RelativeDuration:
80
"""
81
EdgeDB cal::relative_duration type.
82
83
Represents a duration with years, months, days, hours, minutes,
84
seconds, and microseconds components.
85
"""
86
87
def __init__(
88
self,
89
*,
90
years: int = 0,
91
months: int = 0,
92
days: int = 0,
93
hours: int = 0,
94
minutes: int = 0,
95
seconds: int = 0,
96
microseconds: int = 0
97
):
98
"""Create a relative duration."""
99
100
@property
101
def years(self) -> int:
102
"""Years component."""
103
104
@property
105
def months(self) -> int:
106
"""Months component."""
107
108
@property
109
def days(self) -> int:
110
"""Days component."""
111
112
@property
113
def hours(self) -> int:
114
"""Hours component."""
115
116
@property
117
def minutes(self) -> int:
118
"""Minutes component."""
119
120
@property
121
def seconds(self) -> int:
122
"""Seconds component."""
123
124
@property
125
def microseconds(self) -> int:
126
"""Microseconds component."""
127
128
def __add__(self, other) -> RelativeDuration:
129
"""Add durations."""
130
131
def __sub__(self, other) -> RelativeDuration:
132
"""Subtract durations."""
133
134
class DateDuration:
135
"""
136
EdgeDB cal::date_duration type.
137
138
Represents a date-only duration with years, months, and days.
139
"""
140
141
def __init__(
142
self,
143
*,
144
years: int = 0,
145
months: int = 0,
146
days: int = 0
147
):
148
"""Create a date duration."""
149
150
@property
151
def years(self) -> int:
152
"""Years component."""
153
154
@property
155
def months(self) -> int:
156
"""Months component."""
157
158
@property
159
def days(self) -> int:
160
"""Days component."""
161
162
def __add__(self, other) -> DateDuration:
163
"""Add date durations."""
164
165
def __sub__(self, other) -> DateDuration:
166
"""Subtract date durations."""
167
```
168
169
### Configuration Types
170
171
EdgeDB configuration-specific types.
172
173
```python { .api }
174
class ConfigMemory:
175
"""
176
EdgeDB cfg::memory type.
177
178
Represents memory size values with unit parsing.
179
"""
180
181
def __init__(self, value: Union[int, str]):
182
"""
183
Create memory configuration value.
184
185
Parameters:
186
- value: Memory value as int (bytes) or string with unit (e.g., "1GB", "512MB")
187
"""
188
189
@property
190
def bytes(self) -> int:
191
"""Memory value in bytes."""
192
193
def __str__(self) -> str:
194
"""String representation with appropriate unit."""
195
```
196
197
### Range Types
198
199
EdgeDB range and multirange types for representing value ranges.
200
201
```python { .api }
202
class Range:
203
"""
204
EdgeDB range type representation.
205
206
Represents a contiguous range of values with inclusive/exclusive bounds.
207
"""
208
209
def __init__(
210
self,
211
lower: Optional[Any] = None,
212
upper: Optional[Any] = None,
213
*,
214
inc_lower: bool = True,
215
inc_upper: bool = False,
216
empty: bool = False
217
):
218
"""
219
Create a range.
220
221
Parameters:
222
- lower: Lower bound value
223
- upper: Upper bound value
224
- inc_lower: Whether lower bound is inclusive
225
- inc_upper: Whether upper bound is inclusive
226
- empty: Whether range is empty
227
"""
228
229
@property
230
def lower(self) -> Optional[Any]:
231
"""Lower bound value."""
232
233
@property
234
def upper(self) -> Optional[Any]:
235
"""Upper bound value."""
236
237
@property
238
def inc_lower(self) -> bool:
239
"""Whether lower bound is inclusive."""
240
241
@property
242
def inc_upper(self) -> bool:
243
"""Whether upper bound is inclusive."""
244
245
@property
246
def is_empty(self) -> bool:
247
"""Whether range is empty."""
248
249
def __contains__(self, value: Any) -> bool:
250
"""Check if value is in range."""
251
252
def __eq__(self, other) -> bool:
253
"""Compare ranges."""
254
255
class MultiRange:
256
"""
257
EdgeDB multirange type representation.
258
259
Represents a collection of non-overlapping ranges.
260
"""
261
262
def __init__(self, ranges: List[Range]):
263
"""
264
Create a multirange from list of ranges.
265
266
Parameters:
267
- ranges: List of Range objects
268
"""
269
270
@property
271
def ranges(self) -> List[Range]:
272
"""List of constituent ranges."""
273
274
def __contains__(self, value: Any) -> bool:
275
"""Check if value is in any range."""
276
277
def __iter__(self):
278
"""Iterate over constituent ranges."""
279
280
def __len__(self) -> int:
281
"""Number of constituent ranges."""
282
```
283
284
## Usage Examples
285
286
### Working with Objects
287
288
```python
289
import edgedb
290
291
client = edgedb.create_client()
292
293
# Query returns Object instances
294
user = client.query_single("SELECT User { name, email, profile: { bio, avatar } }")
295
296
# Access attributes with dot notation
297
print(user.name)
298
print(user.email)
299
print(user.profile.bio)
300
301
# Access attributes with dictionary notation
302
print(user['name'])
303
print(user['profile']['avatar'])
304
305
# Check if attribute exists
306
if 'phone' in user:
307
print(user.phone)
308
```
309
310
### Working with Collections
311
312
```python
313
import edgedb
314
315
client = edgedb.create_client()
316
317
# Sets and arrays are returned as Python lists
318
articles = client.query("SELECT Article { title, tags }")
319
320
for article in articles:
321
print(f"Title: {article.title}")
322
# tags is a list (EdgeDB array/set)
323
for tag in article.tags:
324
print(f" Tag: {tag}")
325
326
# Named tuples
327
coordinates = client.query_single("SELECT (x := 10, y := 20)")
328
print(f"X: {coordinates.x}, Y: {coordinates.y}")
329
```
330
331
### Working with Enum Values
332
333
```python
334
import edgedb
335
336
client = edgedb.create_client()
337
338
user = client.query_single("SELECT User { name, status }")
339
340
# Enum values behave like strings
341
if user.status == "active":
342
print("User is active")
343
344
# String representation
345
print(f"User status: {user.status}")
346
```
347
348
### Working with Temporal Types
349
350
```python
351
import edgedb
352
from edgedb import RelativeDuration, DateDuration
353
354
client = edgedb.create_client()
355
356
# Create duration objects
357
age_duration = RelativeDuration(years=25, months=6, days=15)
358
project_duration = DateDuration(months=6, days=10)
359
360
# Use in queries
361
client.execute(
362
"UPDATE User SET { age_duration := $duration } FILTER .id = $id",
363
duration=age_duration,
364
id="123e4567-e89b-12d3-a456-426614174000"
365
)
366
367
# Query returns duration objects
368
user = client.query_single("SELECT User { name, age_duration }")
369
print(f"User age: {user.age_duration.years} years, {user.age_duration.months} months")
370
```
371
372
### Working with Ranges
373
374
```python
375
import edgedb
376
from edgedb import Range, MultiRange
377
378
client = edgedb.create_client()
379
380
# Create ranges
381
price_range = Range(100, 500, inc_lower=True, inc_upper=False) # [100, 500)
382
date_range = Range(
383
lower=datetime.date(2024, 1, 1),
384
upper=datetime.date(2024, 12, 31),
385
inc_lower=True,
386
inc_upper=True
387
) # [2024-01-01, 2024-12-31]
388
389
# Use ranges in queries
390
products = client.query(
391
"SELECT Product { name, price } FILTER .price <@ $price_range",
392
price_range=price_range
393
)
394
395
# Check if value is in range
396
if 250 in price_range:
397
print("250 is in price range")
398
399
# Work with multiranges
400
availability = MultiRange([
401
Range(9, 12, inc_lower=True, inc_upper=False), # [9, 12)
402
Range(13, 17, inc_lower=True, inc_upper=False) # [13, 17)
403
])
404
405
if 10 in availability:
406
print("10 is in available hours")
407
```
408
409
### Working with Configuration Types
410
411
```python
412
import edgedb
413
from edgedb import ConfigMemory
414
415
# Create memory configuration values
416
memory_limit = ConfigMemory("2GB")
417
cache_size = ConfigMemory("512MB")
418
buffer_size = ConfigMemory(1048576) # 1MB in bytes
419
420
print(f"Memory limit: {memory_limit.bytes} bytes")
421
print(f"Formatted: {memory_limit}") # Automatically formats with appropriate unit
422
```
423
424
### Type Checking and Conversion
425
426
```python
427
import edgedb
428
429
client = edgedb.create_client()
430
431
result = client.query_single("SELECT User { name, created_at, tags }")
432
433
# Check types
434
print(f"Name type: {type(result.name)}") # <class 'str'>
435
print(f"Created type: {type(result.created_at)}") # <class 'datetime.datetime'>
436
print(f"Tags type: {type(result.tags)}") # <class 'list'>
437
438
# EdgeDB objects are instances of Object
439
print(f"Result type: {type(result)}") # <class 'edgedb.Object'>
440
print(f"Is EdgeDB Object: {isinstance(result, edgedb.Object)}") # True
441
```
442
443
### Complex Nested Types
444
445
```python
446
import edgedb
447
448
client = edgedb.create_client()
449
450
# Query with complex nested structure
451
blog_post = client.query_single("""
452
SELECT BlogPost {
453
title,
454
content,
455
author: { name, email },
456
tags,
457
comments: {
458
content,
459
author: { name },
460
created_at,
461
replies: {
462
content,
463
author: { name },
464
created_at
465
}
466
},
467
metadata: {
468
word_count,
469
reading_time,
470
categories
471
}
472
} FILTER .id = $id
473
""", id="123e4567-e89b-12d3-a456-426614174000")
474
475
# Navigate nested structure
476
print(f"Post: {blog_post.title}")
477
print(f"Author: {blog_post.author.name}")
478
print(f"Tags: {', '.join(blog_post.tags)}")
479
print(f"Word count: {blog_post.metadata.word_count}")
480
481
for comment in blog_post.comments:
482
print(f"Comment by {comment.author.name}: {comment.content}")
483
for reply in comment.replies:
484
print(f" Reply by {reply.author.name}: {reply.content}")
485
```