or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aggregations-helpers.mdattributes-relationships.mddata-types.mddatabase-entities.mddebugging-utilities.mdexception-handling.mdframework-integrations.mdindex.mdquery-operations.mdsecurity-permissions.mdsession-management.md

index.mddocs/

0

# Pony ORM

1

2

Pony ORM is an advanced Object-Relational Mapper for Python that allows developers to write database queries using Python generator expressions and lambda functions. These expressions are automatically analyzed and translated into optimized SQL queries, providing an intuitive and Pythonic way to work with databases.

3

4

## Package Information

5

6

- **Package Name**: pony

7

- **Language**: Python

8

- **Installation**: `pip install pony`

9

- **Documentation**: https://docs.ponyorm.org

10

- **License**: Apache 2.0

11

12

## Core Imports

13

14

```python

15

from pony.orm import *

16

```

17

18

Selective imports for common functionality:

19

20

```python

21

from pony.orm import Database, Required, Optional, Set, PrimaryKey

22

from pony.orm import db_session, commit, rollback, select, get

23

from pony.orm import LongStr, Json, count, sum, min, max, avg

24

```

25

26

Flask integration:

27

28

```python

29

from pony.flask import Pony

30

```

31

32

## Basic Usage

33

34

```python

35

from pony.orm import *

36

37

# Define the database and entities

38

db = Database()

39

40

class Person(db.Entity):

41

name = Required(str)

42

age = Optional(int)

43

orders = Set('Order')

44

45

class Order(db.Entity):

46

date = Required(datetime)

47

person = Required(Person)

48

total = Required(float)

49

50

db.generate_mapping(create_tables=True)

51

52

# Use database session for queries and operations

53

with db_session:

54

# Create entities

55

person = Person(name="John", age=30)

56

order = Order(date=datetime.now(), person=person, total=99.99)

57

58

# Query using generator expressions

59

adults = select(p for p in Person if p.age >= 18)

60

61

# Query with joins and aggregations

62

big_spenders = select(p for p in Person

63

if sum(p.orders.total) > 1000)

64

65

# Get single entity

66

john = Person.get(name="John")

67

68

# Commit changes

69

commit()

70

```

71

72

## Architecture

73

74

Pony ORM follows a distinctive architecture centered on generator expression translation:

75

76

- **Database**: Central registry that manages entity definitions and database connections

77

- **Entity**: Base metaclass for defining database-mapped classes with attributes and relationships

78

- **Attribute Types**: Required, Optional, Set, PrimaryKey define column types and relationships

79

- **Query Translation**: Python generator expressions are parsed and translated to optimized SQL

80

- **Session Management**: db_session decorator manages transactions and database connections

81

- **Identity Map**: Ensures object identity and manages entity lifecycle within sessions

82

83

This design enables writing database queries in pure Python while automatically generating efficient SQL, making database operations feel native to the language.

84

85

## Capabilities

86

87

### Database and Entity Management

88

89

Core classes for defining database schemas and entity relationships. The Database class serves as the central registry, while Entity provides the base for all ORM-mapped classes.

90

91

```python { .api }

92

class Database:

93

def __init__(self, provider=None, **kwargs): ...

94

def bind(self, provider, **kwargs): ...

95

def generate_mapping(self, check_tables=True, create_tables=False): ...

96

def create_tables(self): ...

97

def drop_all_tables(self, with_all_data=False): ...

98

99

class Entity:

100

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

101

def delete(self): ...

102

def flush(self): ...

103

def get_pk(self): ...

104

def set(**kwargs): ...

105

```

106

107

[Database and Entities](./database-entities.md)

108

109

### Entity Attributes and Relationships

110

111

Attribute types for defining entity properties, primary keys, and relationships between entities. These classes define the schema structure and constraints.

112

113

```python { .api }

114

class Required:

115

def __init__(self, py_type, **kwargs): ...

116

117

class Optional:

118

def __init__(self, py_type, **kwargs): ...

119

120

class PrimaryKey:

121

def __init__(self, py_type, **kwargs): ...

122

123

class Set:

124

def __init__(self, py_type, **kwargs): ...

125

126

def composite_key(*attrs): ...

127

def composite_index(*attrs): ...

128

```

129

130

[Attributes and Relationships](./attributes-relationships.md)

131

132

### Data Types and Custom Types

133

134

Specialized data types for storing large text, JSON data, and array types. These extend Python's basic types for database-specific storage needs.

135

136

```python { .api }

137

class LongStr(str): ...

138

class Json: ...

139

class IntArray: ...

140

class StrArray: ...

141

class FloatArray: ...

142

```

143

144

[Data Types](./data-types.md)

145

146

### Query Operations

147

148

Functions for querying the database using Pony's signature generator expression syntax. These provide the main interface for data retrieval and manipulation.

149

150

```python { .api }

151

def select(gen): ...

152

def get(gen): ...

153

def exists(gen): ...

154

def delete(gen): ...

155

def left_join(gen): ...

156

```

157

158

[Query Operations](./query-operations.md)

159

160

### Aggregation and Query Helpers

161

162

Aggregation functions and helper utilities for complex queries including mathematical operations, sorting, and SQL function access.

163

164

```python { .api }

165

def count(gen=None): ...

166

def sum(gen): ...

167

def min(gen): ...

168

def max(gen): ...

169

def avg(gen): ...

170

def group_concat(gen, sep=','): ...

171

def distinct(gen): ...

172

def desc(attr): ...

173

def between(x, a, b): ...

174

def concat(*args): ...

175

def coalesce(*args): ...

176

```

177

178

[Aggregations and Helpers](./aggregations-helpers.md)

179

180

### Session Management

181

182

Database session and transaction management functions. These control the lifecycle of database operations and ensure data consistency.

183

184

```python { .api }

185

@db_session

186

def your_function(): ...

187

188

def flush(): ...

189

def commit(): ...

190

def rollback(): ...

191

def make_proxy(entity_instance): ...

192

```

193

194

[Session Management](./session-management.md)

195

196

### Debugging and Utilities

197

198

Tools for debugging SQL queries, inspecting schemas, and configuring runtime behavior. Essential for development and troubleshooting.

199

200

```python { .api }

201

def set_sql_debug(debug=True, show_values=None): ...

202

def show(entity_or_query): ...

203

```

204

205

[Debugging and Utilities](./debugging-utilities.md)

206

207

### Exception Handling

208

209

Comprehensive exception hierarchy covering database errors, ORM-specific errors, query errors, and transaction errors. Proper exception handling is crucial for robust applications.

210

211

```python { .api }

212

class OrmError(Exception): ...

213

class ObjectNotFound(OrmError): ...

214

class MultipleObjectsFoundError(OrmError): ...

215

class TransactionError(OrmError): ...

216

class DatabaseError(Exception): ...

217

class IntegrityError(DatabaseError): ...

218

```

219

220

[Exception Handling](./exception-handling.md)

221

222

### Security and Permissions

223

224

Optional security framework for implementing row-level security and user-based access control in database operations.

225

226

```python { .api }

227

def set_current_user(user): ...

228

def get_current_user(): ...

229

def has_perm(entity, permission): ...

230

def perm(permission_name): ...

231

```

232

233

[Security and Permissions](./security-permissions.md)

234

235

### Framework Integrations

236

237

Integrations with popular Python web frameworks for automatic session management and simplified database operations in web applications.

238

239

```python { .api }

240

class Pony:

241

def __init__(self, app=None): ...

242

def init_app(self, app): ...

243

```

244

245

[Framework Integrations](./framework-integrations.md)

246

247

## Types

248

249

```python { .api }

250

from typing import Any, Optional, Union, List, Dict

251

from datetime import datetime, date, time, timedelta

252

from decimal import Decimal

253

254

# Core types used across the API

255

EntityType = type # Entity class type

256

AttributeType = Union[Required, Optional, PrimaryKey, Set]

257

QueryType = Any # Generator expression or Query object

258

DatabaseProvider = str # 'sqlite', 'mysql', 'postgresql', 'oracle', 'cockroach'

259

```