iceaxe 0.8.3__cp313-cp313-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of iceaxe might be problematic. Click here for more details.

Files changed (75) hide show
  1. iceaxe/__init__.py +20 -0
  2. iceaxe/__tests__/__init__.py +0 -0
  3. iceaxe/__tests__/benchmarks/__init__.py +0 -0
  4. iceaxe/__tests__/benchmarks/test_bulk_insert.py +45 -0
  5. iceaxe/__tests__/benchmarks/test_select.py +114 -0
  6. iceaxe/__tests__/conf_models.py +133 -0
  7. iceaxe/__tests__/conftest.py +204 -0
  8. iceaxe/__tests__/docker_helpers.py +208 -0
  9. iceaxe/__tests__/helpers.py +268 -0
  10. iceaxe/__tests__/migrations/__init__.py +0 -0
  11. iceaxe/__tests__/migrations/conftest.py +36 -0
  12. iceaxe/__tests__/migrations/test_action_sorter.py +237 -0
  13. iceaxe/__tests__/migrations/test_generator.py +140 -0
  14. iceaxe/__tests__/migrations/test_generics.py +91 -0
  15. iceaxe/__tests__/mountaineer/__init__.py +0 -0
  16. iceaxe/__tests__/mountaineer/dependencies/__init__.py +0 -0
  17. iceaxe/__tests__/mountaineer/dependencies/test_core.py +76 -0
  18. iceaxe/__tests__/schemas/__init__.py +0 -0
  19. iceaxe/__tests__/schemas/test_actions.py +1265 -0
  20. iceaxe/__tests__/schemas/test_cli.py +25 -0
  21. iceaxe/__tests__/schemas/test_db_memory_serializer.py +1571 -0
  22. iceaxe/__tests__/schemas/test_db_serializer.py +435 -0
  23. iceaxe/__tests__/schemas/test_db_stubs.py +190 -0
  24. iceaxe/__tests__/test_alias.py +83 -0
  25. iceaxe/__tests__/test_base.py +52 -0
  26. iceaxe/__tests__/test_comparison.py +383 -0
  27. iceaxe/__tests__/test_field.py +11 -0
  28. iceaxe/__tests__/test_helpers.py +9 -0
  29. iceaxe/__tests__/test_modifications.py +151 -0
  30. iceaxe/__tests__/test_queries.py +764 -0
  31. iceaxe/__tests__/test_queries_str.py +173 -0
  32. iceaxe/__tests__/test_session.py +1511 -0
  33. iceaxe/__tests__/test_text_search.py +287 -0
  34. iceaxe/alias_values.py +67 -0
  35. iceaxe/base.py +351 -0
  36. iceaxe/comparison.py +560 -0
  37. iceaxe/field.py +263 -0
  38. iceaxe/functions.py +1432 -0
  39. iceaxe/generics.py +140 -0
  40. iceaxe/io.py +107 -0
  41. iceaxe/logging.py +91 -0
  42. iceaxe/migrations/__init__.py +5 -0
  43. iceaxe/migrations/action_sorter.py +98 -0
  44. iceaxe/migrations/cli.py +228 -0
  45. iceaxe/migrations/client_io.py +62 -0
  46. iceaxe/migrations/generator.py +404 -0
  47. iceaxe/migrations/migration.py +86 -0
  48. iceaxe/migrations/migrator.py +101 -0
  49. iceaxe/modifications.py +176 -0
  50. iceaxe/mountaineer/__init__.py +10 -0
  51. iceaxe/mountaineer/cli.py +74 -0
  52. iceaxe/mountaineer/config.py +46 -0
  53. iceaxe/mountaineer/dependencies/__init__.py +6 -0
  54. iceaxe/mountaineer/dependencies/core.py +67 -0
  55. iceaxe/postgres.py +133 -0
  56. iceaxe/py.typed +0 -0
  57. iceaxe/queries.py +1459 -0
  58. iceaxe/queries_str.py +294 -0
  59. iceaxe/schemas/__init__.py +0 -0
  60. iceaxe/schemas/actions.py +864 -0
  61. iceaxe/schemas/cli.py +30 -0
  62. iceaxe/schemas/db_memory_serializer.py +711 -0
  63. iceaxe/schemas/db_serializer.py +347 -0
  64. iceaxe/schemas/db_stubs.py +529 -0
  65. iceaxe/session.py +860 -0
  66. iceaxe/session_optimized.c +12207 -0
  67. iceaxe/session_optimized.cpython-313-darwin.so +0 -0
  68. iceaxe/session_optimized.pyx +212 -0
  69. iceaxe/sql_types.py +149 -0
  70. iceaxe/typing.py +73 -0
  71. iceaxe-0.8.3.dist-info/METADATA +262 -0
  72. iceaxe-0.8.3.dist-info/RECORD +75 -0
  73. iceaxe-0.8.3.dist-info/WHEEL +6 -0
  74. iceaxe-0.8.3.dist-info/licenses/LICENSE +21 -0
  75. iceaxe-0.8.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,212 @@
1
+ from typing import Any, List, Tuple
2
+ from iceaxe.base import TableBase
3
+ from iceaxe.queries import FunctionMetadata
4
+ from iceaxe.alias_values import Alias
5
+ from json import loads as json_loads
6
+ from cpython.ref cimport PyObject
7
+ from cpython.object cimport PyObject_GetItem
8
+ from libc.stdlib cimport malloc, free
9
+ from libc.string cimport memcpy
10
+ from cpython.ref cimport Py_INCREF, Py_DECREF
11
+
12
+ cdef struct FieldInfo:
13
+ char* name # Field name
14
+ char* select_attribute # Corresponding attribute in the select_raw
15
+ bint is_json # Flag indicating if the field is JSON
16
+
17
+ cdef char* allocate_cstring(bytes data):
18
+ cdef Py_ssize_t length = len(data)
19
+ cdef char* c_str = <char*>malloc((length + 1) * sizeof(char))
20
+ if not c_str:
21
+ raise MemoryError("Failed to allocate memory for C string.")
22
+ memcpy(c_str, <char*>data, length) # Cast bytes to char* for memcpy
23
+ c_str[length] = 0 # Null-terminate the string
24
+ return c_str
25
+
26
+ cdef void free_fields(FieldInfo** fields, Py_ssize_t* num_fields_array, Py_ssize_t num_selects):
27
+ cdef Py_ssize_t j, k
28
+ if fields:
29
+ for j in range(num_selects):
30
+ if fields[j]:
31
+ for k in range(num_fields_array[j]):
32
+ free(fields[j][k].name)
33
+ free(fields[j][k].select_attribute)
34
+ free(fields[j])
35
+ free(fields)
36
+ if num_fields_array:
37
+ free(num_fields_array)
38
+
39
+ cdef FieldInfo** precompute_fields(list select_raws, list select_types, Py_ssize_t num_selects, Py_ssize_t* num_fields_array):
40
+ cdef FieldInfo** fields = <FieldInfo**>malloc(num_selects * sizeof(FieldInfo*))
41
+ cdef Py_ssize_t j, k, num_fields
42
+ cdef dict field_dict
43
+ cdef bytes select_bytes, field_bytes
44
+ cdef char* c_select
45
+ cdef char* c_field
46
+ cdef object select_raw
47
+ cdef bint raw_is_table, raw_is_column, raw_is_function_metadata
48
+
49
+ if not fields:
50
+ raise MemoryError("Failed to allocate memory for fields.")
51
+
52
+ for j in range(num_selects):
53
+ select_raw = select_raws[j]
54
+ raw_is_table, raw_is_column, raw_is_function_metadata = select_types[j]
55
+
56
+ if raw_is_table:
57
+ field_dict = {field: info.is_json for field, info in select_raw.get_client_fields().items() if not info.exclude}
58
+ num_fields = len(field_dict)
59
+ num_fields_array[j] = num_fields
60
+ fields[j] = <FieldInfo*>malloc(num_fields * sizeof(FieldInfo))
61
+ if not fields[j]:
62
+ raise MemoryError("Failed to allocate memory for FieldInfo.")
63
+
64
+ for k, (field, is_json) in enumerate(field_dict.items()):
65
+ select_bytes = f"{select_raw.get_table_name()}_{field}".encode('utf-8')
66
+ c_select = allocate_cstring(select_bytes)
67
+
68
+ field_bytes = field.encode('utf-8')
69
+ c_field = allocate_cstring(field_bytes)
70
+
71
+ fields[j][k].select_attribute = c_select
72
+ fields[j][k].name = c_field
73
+ fields[j][k].is_json = is_json
74
+ else:
75
+ num_fields_array[j] = 0
76
+ fields[j] = NULL
77
+
78
+ return fields
79
+
80
+ cdef list process_values(
81
+ list values,
82
+ FieldInfo** fields,
83
+ Py_ssize_t* num_fields_array,
84
+ list select_raws,
85
+ list select_types,
86
+ Py_ssize_t num_selects
87
+ ):
88
+ cdef Py_ssize_t num_values = len(values)
89
+ cdef list result_all = [None] * num_values
90
+ cdef Py_ssize_t i, j, k, num_fields
91
+ cdef PyObject** result_value
92
+ cdef object value, obj, item
93
+ cdef dict obj_dict
94
+ cdef bint raw_is_table, raw_is_column, raw_is_function_metadata, raw_is_alias
95
+ cdef char* field_name_c
96
+ cdef char* select_name_c
97
+ cdef str field_name
98
+ cdef str select_name
99
+ cdef object field_value
100
+ cdef object select_raw
101
+ cdef PyObject* temp_obj
102
+ cdef bint all_none
103
+
104
+ for i in range(num_values):
105
+ value = values[i]
106
+ result_value = <PyObject**>malloc(num_selects * sizeof(PyObject*))
107
+ if not result_value:
108
+ raise MemoryError("Failed to allocate memory for result_value.")
109
+ try:
110
+ for j in range(num_selects):
111
+ select_raw = select_raws[j]
112
+ raw_is_table, raw_is_column, raw_is_function_metadata = select_types[j]
113
+ raw_is_alias = isinstance(select_raw, Alias)
114
+
115
+ if raw_is_table:
116
+ obj_dict = {}
117
+ num_fields = num_fields_array[j]
118
+ all_none = True
119
+
120
+ # First pass: collect all fields and check if they're all None
121
+ for k in range(num_fields):
122
+ field_name_c = fields[j][k].name
123
+ select_name_c = fields[j][k].select_attribute
124
+ field_name = field_name_c.decode('utf-8')
125
+ select_name = select_name_c.decode('utf-8')
126
+
127
+ try:
128
+ field_value = value[select_name]
129
+ except KeyError:
130
+ raise KeyError(f"Key '{select_name}' not found in value.")
131
+
132
+ if field_value is not None:
133
+ all_none = False
134
+ if fields[j][k].is_json:
135
+ field_value = json_loads(field_value)
136
+
137
+ obj_dict[field_name] = field_value
138
+
139
+ # If all fields are None, store None instead of creating the table object
140
+ if all_none:
141
+ result_value[j] = <PyObject*>None
142
+ Py_INCREF(None)
143
+ else:
144
+ obj = select_raw(**obj_dict)
145
+ result_value[j] = <PyObject*>obj
146
+ Py_INCREF(obj)
147
+
148
+ elif raw_is_column:
149
+ try:
150
+ # Use the table-qualified column name
151
+ table_name = select_raw.root_model.get_table_name()
152
+ column_name = select_raw.key
153
+ item = value[f"{table_name}_{column_name}"]
154
+ except KeyError:
155
+ raise KeyError(f"Key '{table_name}_{column_name}' not found in value.")
156
+ result_value[j] = <PyObject*>item
157
+ Py_INCREF(item)
158
+
159
+ elif raw_is_function_metadata:
160
+ try:
161
+ item = value[select_raw.local_name]
162
+ except KeyError:
163
+ raise KeyError(f"Key '{select_raw.local_name}' not found in value.")
164
+ result_value[j] = <PyObject*>item
165
+ Py_INCREF(item)
166
+
167
+ elif raw_is_alias:
168
+ try:
169
+ item = value[select_raw.name]
170
+ except KeyError:
171
+ raise KeyError(f"Key '{select_raw.name}' not found in value.")
172
+ result_value[j] = <PyObject*>item
173
+ Py_INCREF(item)
174
+
175
+ # Assemble the result
176
+ if num_selects == 1:
177
+ result_all[i] = <object>result_value[0]
178
+ Py_DECREF(<object>result_value[0])
179
+ else:
180
+ result_tuple = tuple([<object>result_value[j] for j in range(num_selects)])
181
+ for j in range(num_selects):
182
+ Py_DECREF(<object>result_value[j])
183
+ result_all[i] = result_tuple
184
+
185
+ finally:
186
+ free(result_value)
187
+
188
+ return result_all
189
+
190
+ cdef list optimize_casting(list values, list select_raws, list select_types):
191
+ cdef Py_ssize_t num_selects = len(select_raws)
192
+ cdef Py_ssize_t* num_fields_array = <Py_ssize_t*>malloc(num_selects * sizeof(Py_ssize_t))
193
+ cdef FieldInfo** fields
194
+ cdef list result_all
195
+
196
+ if not num_fields_array:
197
+ raise MemoryError("Failed to allocate memory for num_fields_array.")
198
+
199
+ try:
200
+ fields = precompute_fields(select_raws, select_types, num_selects, num_fields_array)
201
+ result_all = process_values(values, fields, num_fields_array, select_raws, select_types, num_selects)
202
+ finally:
203
+ free_fields(fields, num_fields_array, num_selects)
204
+
205
+ return result_all
206
+
207
+ def optimize_exec_casting(
208
+ values: List[Any],
209
+ select_raws: List[Any],
210
+ select_types: List[Tuple[bool, bool, bool]]
211
+ ) -> List[Any]:
212
+ return optimize_casting(values, select_raws, select_types)
iceaxe/sql_types.py ADDED
@@ -0,0 +1,149 @@
1
+ from datetime import date, datetime, time, timedelta
2
+ from enum import Enum, StrEnum
3
+ from uuid import UUID
4
+
5
+
6
+ class ColumnType(StrEnum):
7
+ # The values of the enum are the actual SQL types. When constructing
8
+ # the column they can be case-insensitive, but when we're casting from
9
+ # the database to memory they must align with the on-disk representation
10
+ # which is lowercase.
11
+ #
12
+ # Note: The SQL standard requires that writing just "timestamp" be equivalent
13
+ # to "timestamp without time zone", and PostgreSQL honors that behavior.
14
+ # Similarly, "time" is equivalent to "time without time zone".
15
+
16
+ # Numeric Types
17
+ SMALLINT = "smallint"
18
+ INTEGER = "integer"
19
+ BIGINT = "bigint"
20
+ DECIMAL = "decimal"
21
+ NUMERIC = "numeric"
22
+ REAL = "real"
23
+ DOUBLE_PRECISION = "double precision"
24
+ SERIAL = "serial"
25
+ BIGSERIAL = "bigserial"
26
+ SMALLSERIAL = "smallserial"
27
+
28
+ # Monetary Type
29
+ MONEY = "money"
30
+
31
+ # Character Types
32
+ CHAR = "char"
33
+ VARCHAR = "character varying"
34
+ TEXT = "text"
35
+
36
+ # Binary Data Types
37
+ BYTEA = "bytea"
38
+
39
+ # Date/Time Types
40
+ DATE = "date"
41
+ TIME_WITHOUT_TIME_ZONE = "time without time zone"
42
+ TIME_WITH_TIME_ZONE = "time with time zone"
43
+ TIMESTAMP_WITHOUT_TIME_ZONE = "timestamp without time zone"
44
+ TIMESTAMP_WITH_TIME_ZONE = "timestamp with time zone"
45
+ INTERVAL = "interval"
46
+
47
+ # Boolean Type
48
+ BOOLEAN = "boolean"
49
+
50
+ # Geometric Types
51
+ POINT = "point"
52
+ LINE = "line"
53
+ LSEG = "lseg"
54
+ BOX = "box"
55
+ PATH = "path"
56
+ POLYGON = "polygon"
57
+ CIRCLE = "circle"
58
+
59
+ # Network Address Types
60
+ CIDR = "cidr"
61
+ INET = "inet"
62
+ MACADDR = "macaddr"
63
+ MACADDR8 = "macaddr8"
64
+
65
+ # Bit String Types
66
+ BIT = "bit"
67
+ BIT_VARYING = "bit varying"
68
+
69
+ # Text Search Types
70
+ TSVECTOR = "tsvector"
71
+ TSQUERY = "tsquery"
72
+
73
+ # UUID Type
74
+ UUID = "uuid"
75
+
76
+ # XML Type
77
+ XML = "xml"
78
+
79
+ # JSON Types
80
+ JSON = "json"
81
+ JSONB = "jsonb"
82
+
83
+ # Range Types
84
+ INT4RANGE = "int4range"
85
+ NUMRANGE = "numrange"
86
+ TSRANGE = "tsrange"
87
+ TSTZRANGE = "tstzrange"
88
+ DATERANGE = "daterange"
89
+
90
+ # Object Identifier Type
91
+ OID = "oid"
92
+
93
+ @classmethod
94
+ def _missing_(cls, value: object):
95
+ """
96
+ Handle SQL standard aliases when the exact enum value is not found.
97
+
98
+ The SQL standard requires that "timestamp" be equivalent to "timestamp without time zone"
99
+ and "time" be equivalent to "time without time zone".
100
+ """
101
+ # Only handle string values for SQL type aliases
102
+ if not isinstance(value, str):
103
+ return None
104
+
105
+ aliases = {
106
+ "timestamp": "timestamp without time zone",
107
+ "time": "time without time zone",
108
+ }
109
+
110
+ # Check if this is an alias we can resolve
111
+ if value in aliases:
112
+ # Return the actual enum member for the aliased value
113
+ return cls(aliases[value])
114
+
115
+ # If not an alias, let the default enum behavior handle it
116
+ return None
117
+
118
+
119
+ class ConstraintType(StrEnum):
120
+ PRIMARY_KEY = "PRIMARY KEY"
121
+ FOREIGN_KEY = "FOREIGN KEY"
122
+ UNIQUE = "UNIQUE"
123
+ CHECK = "CHECK"
124
+ INDEX = "INDEX"
125
+
126
+
127
+ def get_python_to_sql_mapping():
128
+ """
129
+ Returns a mapping of Python types to their corresponding SQL types.
130
+ """
131
+ return {
132
+ int: ColumnType.INTEGER,
133
+ float: ColumnType.DOUBLE_PRECISION,
134
+ str: ColumnType.VARCHAR,
135
+ bool: ColumnType.BOOLEAN,
136
+ bytes: ColumnType.BYTEA,
137
+ UUID: ColumnType.UUID,
138
+ datetime: ColumnType.TIMESTAMP_WITHOUT_TIME_ZONE,
139
+ date: ColumnType.DATE,
140
+ time: ColumnType.TIME_WITHOUT_TIME_ZONE,
141
+ timedelta: ColumnType.INTERVAL,
142
+ }
143
+
144
+
145
+ def enum_to_name(enum: Enum) -> str:
146
+ """
147
+ Returns the name of the enum as a string.
148
+ """
149
+ return enum.__name__.lower()
iceaxe/typing.py ADDED
@@ -0,0 +1,73 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import date, datetime, time, timedelta
4
+ from enum import Enum, IntEnum, StrEnum
5
+ from inspect import isclass
6
+ from typing import (
7
+ TYPE_CHECKING,
8
+ Any,
9
+ Type,
10
+ TypeGuard,
11
+ TypeVar,
12
+ )
13
+ from uuid import UUID
14
+
15
+ if TYPE_CHECKING:
16
+ from iceaxe.alias_values import Alias
17
+ from iceaxe.base import (
18
+ DBFieldClassDefinition,
19
+ TableBase,
20
+ )
21
+ from iceaxe.comparison import FieldComparison, FieldComparisonGroup
22
+ from iceaxe.functions import FunctionMetadata
23
+
24
+
25
+ ALL_ENUM_TYPES = Type[Enum | StrEnum | IntEnum]
26
+ PRIMITIVE_TYPES = int | float | str | bool | bytes | UUID
27
+ PRIMITIVE_WRAPPER_TYPES = list[PRIMITIVE_TYPES] | PRIMITIVE_TYPES
28
+ DATE_TYPES = datetime | date | time | timedelta
29
+ JSON_WRAPPER_FALLBACK = list[Any] | dict[Any, Any]
30
+
31
+ T = TypeVar("T")
32
+
33
+
34
+ def is_base_table(obj: Any) -> TypeGuard[type[TableBase]]:
35
+ from iceaxe.base import TableBase
36
+
37
+ return isclass(obj) and issubclass(obj, TableBase)
38
+
39
+
40
+ def is_column(obj: T) -> TypeGuard[DBFieldClassDefinition[T]]:
41
+ from iceaxe.base import DBFieldClassDefinition
42
+
43
+ return isinstance(obj, DBFieldClassDefinition)
44
+
45
+
46
+ def is_comparison(obj: Any) -> TypeGuard[FieldComparison]:
47
+ from iceaxe.comparison import FieldComparison
48
+
49
+ return isinstance(obj, FieldComparison)
50
+
51
+
52
+ def is_comparison_group(obj: Any) -> TypeGuard[FieldComparisonGroup]:
53
+ from iceaxe.comparison import FieldComparisonGroup
54
+
55
+ return isinstance(obj, FieldComparisonGroup)
56
+
57
+
58
+ def is_function_metadata(obj: Any) -> TypeGuard[FunctionMetadata]:
59
+ from iceaxe.functions import FunctionMetadata
60
+
61
+ return isinstance(obj, FunctionMetadata)
62
+
63
+
64
+ def is_alias(obj: Any) -> TypeGuard[Alias]:
65
+ from iceaxe.alias_values import Alias
66
+
67
+ return isinstance(obj, Alias)
68
+
69
+
70
+ def column(obj: T) -> DBFieldClassDefinition[T]:
71
+ if not is_column(obj):
72
+ raise ValueError(f"Invalid column: {obj}")
73
+ return obj
@@ -0,0 +1,262 @@
1
+ Metadata-Version: 2.4
2
+ Name: iceaxe
3
+ Version: 0.8.3
4
+ Summary: A modern, fast ORM for Python.
5
+ Author-email: Pierce Freeman <pierce@freeman.vc>
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: asyncpg<1,>=0.30
10
+ Requires-Dist: click>=8
11
+ Requires-Dist: pydantic<3,>=2
12
+ Requires-Dist: rich>=13
13
+ Dynamic: license-file
14
+
15
+ # iceaxe
16
+
17
+ ![Iceaxe Logo](https://raw.githubusercontent.com/piercefreeman/iceaxe/main/media/header.png)
18
+
19
+ ![Python Version](https://img.shields.io/python/required-version-toml?tomlFilePath=https%3A%2F%2Fraw.githubusercontent.com%2Fpiercefreeman%2Ficeaxe%2Frefs%2Fheads%2Fmain%2Fpyproject.toml) [![Test status](https://github.com/piercefreeman/iceaxe/actions/workflows/test.yml/badge.svg)](https://github.com/piercefreeman/iceaxe/actions)
20
+
21
+ A modern, fast ORM for Python. We have the following goals:
22
+
23
+ - 🏎️ **Performance**: We want to exceed or match the fastest ORMs in Python. We want our ORM
24
+ to be as close as possible to raw-[asyncpg](https://github.com/MagicStack/asyncpg) speeds. See the "Benchmarks" section for more.
25
+ - 📝 **Typehinting**: Everything should be typehinted with expected types. Declare your data as you
26
+ expect in Python and it should bidirectionally sync to the database.
27
+ - 🐘 **Postgres only**: Leverage native Postgres features and simplify the implementation.
28
+ - ⚡ **Common things are easy, rare things are possible**: 99% of the SQL queries we write are
29
+ vanilla SELECT/INSERT/UPDATEs. These should be natively supported by your ORM. If you're writing _really_
30
+ complex queries, these are better done by hand so you can see exactly what SQL will be run.
31
+
32
+ Iceaxe is used in production at several companies. It's also an independent project. It's compatible with the [Mountaineer](https://github.com/piercefreeman/mountaineer) ecosystem, but you can use it in whatever
33
+ project and web framework you're using.
34
+
35
+ For comprehensive documentation, visit [https://iceaxe.sh](https://iceaxe.sh).
36
+
37
+ To auto-optimize your self hosted Postgres install, check out our new [autopg](https://github.com/piercefreeman/autopg) project.
38
+
39
+ ## Installation
40
+
41
+ If you're using poetry to manage your dependencies:
42
+
43
+ ```bash
44
+ uv add iceaxe
45
+ ```
46
+
47
+ Otherwise install with pip:
48
+
49
+ ```bash
50
+ pip install iceaxe
51
+ ```
52
+
53
+ ## Usage
54
+
55
+ Define your models as a `TableBase` subclass:
56
+
57
+ ```python
58
+ from iceaxe import TableBase
59
+
60
+ class Person(TableBase):
61
+ id: int
62
+ name: str
63
+ age: int
64
+ ```
65
+
66
+ TableBase is a subclass of Pydantic's `BaseModel`, so you get all of the validation and Field customization
67
+ out of the box. We provide our own `Field` constructor that adds database-specific configuration. For instance, to make the
68
+ `id` field a primary key / auto-incrementing you can do:
69
+
70
+ ```python
71
+ from iceaxe import Field
72
+
73
+ class Person(TableBase):
74
+ id: int = Field(primary_key=True)
75
+ name: str
76
+ age: int
77
+ ```
78
+
79
+ Okay now you have a model. How do you interact with it?
80
+
81
+ Databases are based on a few core primitives to insert data, update it, and fetch it out again.
82
+ To do so you'll need a _database connection_, which is a connection over the network from your code
83
+ to your Postgres database. The `DBConnection` is the core class for all ORM actions against the database.
84
+
85
+ ```python
86
+ from iceaxe import DBConnection
87
+ import asyncpg
88
+
89
+ conn = DBConnection(
90
+ await asyncpg.connect(
91
+ host="localhost",
92
+ port=5432,
93
+ user="db_user",
94
+ password="yoursecretpassword",
95
+ database="your_db",
96
+ )
97
+ )
98
+ ```
99
+
100
+ The Person class currently just lives in memory. To back it with a full
101
+ database table, we can run raw SQL or run a migration to add it:
102
+
103
+ ```python
104
+ await conn.conn.execute(
105
+ """
106
+ CREATE TABLE IF NOT EXISTS person (
107
+ id SERIAL PRIMARY KEY,
108
+ name TEXT NOT NULL,
109
+ age INT NOT NULL
110
+ )
111
+ """
112
+ )
113
+ ```
114
+
115
+ ### Inserting Data
116
+
117
+ Instantiate object classes as you normally do:
118
+
119
+ ```python
120
+ people = [
121
+ Person(name="Alice", age=30),
122
+ Person(name="Bob", age=40),
123
+ Person(name="Charlie", age=50),
124
+ ]
125
+ await conn.insert(people)
126
+
127
+ print(people[0].id) # 1
128
+ print(people[1].id) # 2
129
+ ```
130
+
131
+ Because we're using an auto-incrementing primary key, the `id` field will be populated after the insert.
132
+ Iceaxe will automatically update the object in place with the newly assigned value.
133
+
134
+ ### Updating data
135
+
136
+ Now that we have these lovely people, let's modify them.
137
+
138
+ ```python
139
+ person = people[0]
140
+ person.name = "Blice"
141
+ ```
142
+
143
+ Right now, we have a Python object that's out of state with the database. But that's often okay. We can inspect it
144
+ and further write logic - it's fully decoupled from the database.
145
+
146
+ ```python
147
+ def ensure_b_letter(person: Person):
148
+ if person.name[0].lower() != "b":
149
+ raise ValueError("Name must start with 'B'")
150
+
151
+ ensure_b_letter(person)
152
+ ```
153
+
154
+ To sync the values back to the database, we can call `update`:
155
+
156
+ ```python
157
+ await conn.update([person])
158
+ ```
159
+
160
+ If we were to query the database directly, we see that the name has been updated:
161
+
162
+ ```
163
+ id | name | age
164
+ ----+-------+-----
165
+ 1 | Blice | 31
166
+ 2 | Bob | 40
167
+ 3 | Charlie | 50
168
+ ```
169
+
170
+ But no other fields have been touched. This lets a potentially concurrent process
171
+ modify `Alice`'s record - say, updating the age to 31. By the time we update the data, we'll
172
+ change the name but nothing else. Under the hood we do this by tracking the fields that
173
+ have been modified in-memory and creating a targeted UPDATE to modify only those values.
174
+
175
+ ### Selecting data
176
+
177
+ To select data, we can use a `QueryBuilder`. For a shortcut to `select` query functions,
178
+ you can also just import select directly. This method takes the desired value parameters
179
+ and returns a list of the desired objects.
180
+
181
+ ```python
182
+ from iceaxe import select
183
+
184
+ query = select(Person).where(Person.name == "Blice", Person.age > 25)
185
+ results = await conn.exec(query)
186
+ ```
187
+
188
+ If we inspect the typing of `results`, we see that it's a `list[Person]` objects. This matches
189
+ the typehint of the `select` function. You can also target columns directly:
190
+
191
+ ```python
192
+ query = select((Person.id, Person.name)).where(Person.age > 25)
193
+ results = await conn.exec(query)
194
+ ```
195
+
196
+ This will return a list of tuples, where each tuple is the id and name of the person: `list[tuple[int, str]]`.
197
+
198
+ We support most of the common SQL operations. Just like the results, these are typehinted
199
+ to their proper types as well. Static typecheckers and your IDE will throw an error if you try to compare
200
+ a string column to an integer, for instance. A more complex example of a query:
201
+
202
+ ```python
203
+ query = select((
204
+ Person.id,
205
+ FavoriteColor,
206
+ )).join(
207
+ FavoriteColor,
208
+ Person.id == FavoriteColor.person_id,
209
+ ).where(
210
+ Person.age > 25,
211
+ Person.name == "Blice",
212
+ ).order_by(
213
+ Person.age.desc(),
214
+ ).limit(10)
215
+ results = await conn.exec(query)
216
+ ```
217
+
218
+ As expected this will deliver results - and typehint - as a `list[tuple[int, FavoriteColor]]`
219
+
220
+ ## Production
221
+
222
+ > [!IMPORTANT]
223
+ > Iceaxe is in early alpha. We're using it internally and showly rolling out to our production
224
+ applications, but we're not yet ready to recommend it for general use. The API and larger
225
+ stability is subject to change.
226
+
227
+ Note that underlying Postgres connection wrapped by `conn` will be alive for as long as your object is in memory. This uses up one
228
+ of the allowable connections to your database. Your overall limit depends on your Postgres configuration
229
+ or hosting provider, but most managed solutions top out around 150-300. If you need more concurrent clients
230
+ connected (and even if you don't - connection creation at the Postgres level is expensive), you can adopt
231
+ a load balancer like `pgbouncer` to better scale to traffic. More deployment notes to come.
232
+
233
+ It's also worth noting the absence of request pooling in this initialization. This is a feature of many ORMs that lets you limit
234
+ the overall connections you make to Postgres, and re-use these over time. We specifically don't offer request
235
+ pooling as part of Iceaxe, despite being supported by our underlying engine `asyncpg`. This is a bit more
236
+ aligned to how things should be structured in production. Python apps are always bound to one process thanks to
237
+ the GIL. So no matter what your connection pool will always be tied to the current Python process / runtime. When you're deploying onto a server with multiple cores, the pool will be duplicated across CPUs and largely defeats the purpose of capping
238
+ network connections in the first place.
239
+
240
+ ## Benchmarking
241
+
242
+ We have basic benchmarking tests in the `__tests__/benchmarks` directory. To run them, you'll need to execute the pytest suite:
243
+
244
+ ```bash
245
+ uv run pytest -m integration_tests
246
+ ```
247
+
248
+ Current benchmarking as of October 11 2024 is:
249
+
250
+ | | raw asyncpg | iceaxe | external overhead | |
251
+ |-------------------|-------------|--------|-----------------------------------------------|---|
252
+ | TableBase columns | 0.098s | 0.093s | | |
253
+ | TableBase full | 0.164s | 1.345s | 10%: dict construction | 90%: pydantic overhead | |
254
+
255
+ ## Development
256
+
257
+ If you update your Cython implementation during development, you'll need to re-compile the Cython code. This can be done with
258
+ a simple uv sync.
259
+
260
+ ```bash
261
+ uv sync
262
+ ```