or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdauthentication.mddata-types.mddbapi-interface.mddriver-connection.mderror-handling.mdindex.mdquery-service.mdschema-operations.mdsqlalchemy-integration.mdtable-operations.mdtopic-operations.md

data-types.mddocs/

0

# Data Types and Conversion

1

2

Complete type system mapping Python types to YDB types, including primitives, optionals, containers, and advanced types like decimals and variants.

3

4

## Capabilities

5

6

### Primitive Types

7

8

Basic data types that map directly to YDB's primitive types.

9

10

```python { .api }

11

class PrimitiveType:

12

"""YDB primitive data types."""

13

14

# Boolean

15

Bool: Type

16

17

# Integer types

18

Int8: Type # Signed 8-bit integer

19

Uint8: Type # Unsigned 8-bit integer

20

Int16: Type # Signed 16-bit integer

21

Uint16: Type # Unsigned 16-bit integer

22

Int32: Type # Signed 32-bit integer

23

Uint32: Type # Unsigned 32-bit integer

24

Int64: Type # Signed 64-bit integer

25

Uint64: Type # Unsigned 64-bit integer

26

27

# Floating point

28

Float: Type # 32-bit floating point

29

Double: Type # 64-bit floating point

30

31

# String types

32

String: Type # Binary string

33

Utf8: Type # UTF-8 string

34

35

# Structured data

36

Yson: Type # YSON format

37

Json: Type # JSON string

38

JsonDocument: Type # JSON document (binary)

39

40

# UUID

41

Uuid: Type # UUID type

42

43

# Date and time

44

Date: Type # Date only

45

Datetime: Type # Date and time

46

Timestamp: Type # Timestamp with microseconds

47

Interval: Type # Time interval

48

TzDate: Type # Date with timezone

49

TzDatetime: Type # DateTime with timezone

50

TzTimestamp: Type # Timestamp with timezone

51

52

# Decimal number

53

DyNumber: Type # Dynamic number

54

```

55

56

### Optional Types

57

58

Nullable types that can contain either a value or NULL.

59

60

```python { .api }

61

def Optional(item_type: Type) -> OptionalType:

62

"""

63

Create optional (nullable) type.

64

65

Args:

66

item_type (Type): Inner type that can be null

67

68

Returns:

69

OptionalType: Optional type wrapper

70

"""

71

72

class OptionalType:

73

def __init__(self, item_type: Type):

74

"""

75

Optional type constructor.

76

77

Args:

78

item_type (Type): Type that can be null

79

"""

80

81

@property

82

def item_type(self) -> Type:

83

"""Get the inner type."""

84

```

85

86

### Container Types

87

88

Collection types for complex data structures.

89

90

```python { .api }

91

def List(item_type: Type) -> ListType:

92

"""

93

Create list type.

94

95

Args:

96

item_type (Type): Type of list elements

97

98

Returns:

99

ListType: List type

100

"""

101

102

def Tuple(*item_types: Type) -> TupleType:

103

"""

104

Create tuple type with fixed element types.

105

106

Args:

107

*item_types (Type): Types of tuple elements in order

108

109

Returns:

110

TupleType: Tuple type

111

"""

112

113

def Struct(**kwargs: Type) -> StructType:

114

"""

115

Create struct type with named fields.

116

117

Args:

118

**kwargs (Type): Field names and their types

119

120

Returns:

121

StructType: Struct type

122

"""

123

124

def Dict(key_type: Type, value_type: Type) -> DictType:

125

"""

126

Create dictionary type.

127

128

Args:

129

key_type (Type): Type of dictionary keys

130

value_type (Type): Type of dictionary values

131

132

Returns:

133

DictType: Dictionary type

134

"""

135

136

class ListType:

137

def __init__(self, item_type: Type):

138

"""List type with homogeneous elements."""

139

140

@property

141

def item_type(self) -> Type:

142

"""Get element type."""

143

144

class TupleType:

145

def __init__(self, *item_types: Type):

146

"""Tuple type with heterogeneous elements."""

147

148

@property

149

def item_types(self) -> tuple:

150

"""Get element types."""

151

152

class StructType:

153

def __init__(self, **kwargs: Type):

154

"""Struct type with named fields."""

155

156

@property

157

def fields(self) -> dict:

158

"""Get field definitions."""

159

160

class DictType:

161

def __init__(self, key_type: Type, value_type: Type):

162

"""Dictionary type with key-value pairs."""

163

164

@property

165

def key_type(self) -> Type:

166

"""Get key type."""

167

168

@property

169

def value_type(self) -> Type:

170

"""Get value type."""

171

```

172

173

### Advanced Types

174

175

Specialized types for complex scenarios.

176

177

```python { .api }

178

def Decimal(precision: int, scale: int) -> DecimalType:

179

"""

180

Create decimal number type.

181

182

Args:

183

precision (int): Total number of digits

184

scale (int): Number of digits after decimal point

185

186

Returns:

187

DecimalType: Decimal type

188

"""

189

190

def Variant(struct_type: StructType = None, tuple_type: TupleType = None) -> VariantType:

191

"""

192

Create variant (union) type.

193

194

Args:

195

struct_type (StructType, optional): Struct-based variant

196

tuple_type (TupleType, optional): Tuple-based variant

197

198

Returns:

199

VariantType: Variant type

200

"""

201

202

def Tagged(tag: str, base_type: Type) -> TaggedType:

203

"""

204

Create tagged type with metadata.

205

206

Args:

207

tag (str): Type tag/label

208

base_type (Type): Underlying type

209

210

Returns:

211

TaggedType: Tagged type

212

"""

213

214

class DecimalType:

215

def __init__(self, precision: int, scale: int):

216

"""

217

Decimal number type.

218

219

Args:

220

precision (int): Total digits (1-35)

221

scale (int): Decimal places (0-precision)

222

"""

223

224

@property

225

def precision(self) -> int:

226

"""Total number of digits."""

227

228

@property

229

def scale(self) -> int:

230

"""Digits after decimal point."""

231

232

class VariantType:

233

def __init__(self, underlying_type: Type):

234

"""Variant type for union values."""

235

236

@property

237

def underlying_type(self) -> Type:

238

"""Get underlying type."""

239

240

class TaggedType:

241

def __init__(self, tag: str, base_type: Type):

242

"""Tagged type with metadata."""

243

244

@property

245

def tag(self) -> str:

246

"""Get type tag."""

247

248

@property

249

def base_type(self) -> Type:

250

"""Get base type."""

251

252

class VoidType:

253

"""Void type for functions with no return value."""

254

```

255

256

### Type Utilities

257

258

Helper functions for working with types.

259

260

```python { .api }

261

class Type:

262

"""Base class for all YDB types."""

263

264

def __str__(self) -> str:

265

"""String representation of type."""

266

267

def __eq__(self, other) -> bool:

268

"""Type equality comparison."""

269

270

def type_to_native(ydb_type: Type):

271

"""

272

Convert YDB type to native Python representation.

273

274

Args:

275

ydb_type (Type): YDB type instance

276

277

Returns:

278

Native Python representation

279

"""

280

281

def native_to_type(python_value):

282

"""

283

Infer YDB type from Python value.

284

285

Args:

286

python_value: Python value

287

288

Returns:

289

Type: Corresponding YDB type

290

"""

291

```

292

293

## Usage Examples

294

295

### Basic Type Definitions

296

297

```python

298

import ydb

299

300

# Primitive types

301

user_id_type = ydb.PrimitiveType.Uint64

302

name_type = ydb.PrimitiveType.Utf8

303

created_at_type = ydb.PrimitiveType.Timestamp

304

is_active_type = ydb.PrimitiveType.Bool

305

306

# Optional types (nullable)

307

optional_email = ydb.Optional(ydb.PrimitiveType.Utf8)

308

optional_age = ydb.Optional(ydb.PrimitiveType.Uint32)

309

```

310

311

### Container Types

312

313

```python

314

import ydb

315

316

# List of strings

317

tags_type = ydb.List(ydb.PrimitiveType.Utf8)

318

319

# Dictionary mapping strings to integers

320

scores_type = ydb.Dict(ydb.PrimitiveType.Utf8, ydb.PrimitiveType.Int32)

321

322

# Tuple with mixed types

323

coordinate_type = ydb.Tuple(ydb.PrimitiveType.Double, ydb.PrimitiveType.Double)

324

325

# Struct with named fields

326

user_type = ydb.Struct(

327

id=ydb.PrimitiveType.Uint64,

328

name=ydb.PrimitiveType.Utf8,

329

email=ydb.Optional(ydb.PrimitiveType.Utf8),

330

tags=ydb.List(ydb.PrimitiveType.Utf8)

331

)

332

```

333

334

### Advanced Types

335

336

```python

337

import ydb

338

339

# Decimal for precise monetary calculations

340

price_type = ydb.Decimal(precision=10, scale=2) # 10 digits, 2 decimal places

341

342

# Variant type for union of different types

343

status_type = ydb.Variant(ydb.Struct(

344

success=ydb.PrimitiveType.Bool,

345

error=ydb.PrimitiveType.Utf8,

346

pending=ydb.PrimitiveType.Void

347

))

348

349

# Tagged type for semantic meaning

350

user_id_tagged = ydb.Tagged("UserId", ydb.PrimitiveType.Uint64)

351

```

352

353

### Table Column Definitions

354

355

```python

356

import ydb

357

358

# Define table with various column types

359

table_desc = ydb.TableDescription() \

360

.with_column(ydb.TableColumn(

361

'id',

362

ydb.PrimitiveType.Uint64

363

)) \

364

.with_column(ydb.TableColumn(

365

'profile',

366

ydb.Struct(

367

name=ydb.PrimitiveType.Utf8,

368

age=ydb.Optional(ydb.PrimitiveType.Uint32),

369

emails=ydb.List(ydb.PrimitiveType.Utf8)

370

)

371

)) \

372

.with_column(ydb.TableColumn(

373

'metadata',

374

ydb.Dict(ydb.PrimitiveType.Utf8, ydb.PrimitiveType.Utf8)

375

)) \

376

.with_primary_key('id')

377

```

378

379

### Type Conversion Examples

380

381

```python

382

import ydb

383

from decimal import Decimal

384

from datetime import datetime, date

385

386

# Python to YDB type inference

387

python_values = {

388

42: ydb.PrimitiveType.Int32,

389

"hello": ydb.PrimitiveType.Utf8,

390

True: ydb.PrimitiveType.Bool,

391

3.14: ydb.PrimitiveType.Double,

392

datetime.now(): ydb.PrimitiveType.Timestamp,

393

date.today(): ydb.PrimitiveType.Date,

394

[1, 2, 3]: ydb.List(ydb.PrimitiveType.Int32),

395

{"key": "value"}: ydb.Dict(ydb.PrimitiveType.Utf8, ydb.PrimitiveType.Utf8)

396

}

397

398

# Working with optional values

399

def process_optional_field(value):

400

if value is None:

401

return None # NULL value

402

return value # Actual value

403

```

404

405

### Parameter Binding with Types

406

407

```python

408

import ydb

409

410

def typed_query_example(session):

411

# Use typed parameters in queries

412

result_sets = session.transaction().execute(

413

"""

414

DECLARE $user_id AS Uint64;

415

DECLARE $profile AS Struct<

416

name: Utf8,

417

age: Uint32?,

418

emails: List<Utf8>

419

>;

420

421

INSERT INTO users (id, profile)

422

VALUES ($user_id, $profile);

423

""",

424

parameters={

425

'$user_id': 123,

426

'$profile': {

427

'name': 'Alice',

428

'age': 30,

429

'emails': ['alice@example.com', 'alice.work@company.com']

430

}

431

},

432

commit_tx=True

433

)

434

```

435

436

### Complex Nested Types

437

438

```python

439

import ydb

440

441

# Define complex nested structure

442

order_type = ydb.Struct(

443

order_id=ydb.PrimitiveType.Uint64,

444

customer=ydb.Struct(

445

id=ydb.PrimitiveType.Uint64,

446

name=ydb.PrimitiveType.Utf8,

447

email=ydb.Optional(ydb.PrimitiveType.Utf8)

448

),

449

items=ydb.List(ydb.Struct(

450

product_id=ydb.PrimitiveType.Uint64,

451

quantity=ydb.PrimitiveType.Uint32,

452

price=ydb.Decimal(precision=10, scale=2)

453

)),

454

status=ydb.Variant(ydb.Struct(

455

pending=ydb.PrimitiveType.Void,

456

shipped=ydb.PrimitiveType.Timestamp,

457

delivered=ydb.PrimitiveType.Timestamp,

458

cancelled=ydb.PrimitiveType.Utf8 # cancellation reason

459

)),

460

metadata=ydb.Optional(ydb.Dict(

461

ydb.PrimitiveType.Utf8,

462

ydb.PrimitiveType.Utf8

463

))

464

)

465

466

# Use in table definition

467

orders_table = ydb.TableDescription() \

468

.with_column(ydb.TableColumn('order', order_type)) \

469

.with_primary_key('order.order_id')

470

```

471

472

## Types

473

474

```python { .api }

475

from typing import Union, Any, Dict, List as PyList

476

from decimal import Decimal

477

from datetime import datetime, date, timedelta

478

479

# Type mapping helpers

480

PythonValue = Union[None, bool, int, float, str, bytes, datetime, date, timedelta, Decimal, PyList, Dict[str, Any]]

481

YdbValue = Any

482

483

# Time units for intervals

484

class Unit:

485

SECONDS: Unit

486

MILLISECONDS: Unit

487

MICROSECONDS: Unit

488

NANOSECONDS: Unit

489

```