tai-sql 0.6.2__tar.gz → 0.6.4__tar.gz

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.
Files changed (99) hide show
  1. {tai_sql-0.6.2 → tai_sql-0.6.4}/PKG-INFO +108 -1
  2. {tai_sql-0.6.2 → tai_sql-0.6.4}/README.md +107 -0
  3. {tai_sql-0.6.2 → tai_sql-0.6.4}/pyproject.toml +1 -1
  4. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/__init__.py +3 -1
  5. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/__init__.py +13 -0
  6. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/domain/dao.py.jinja2 +4 -4
  7. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/domain/dtos.py.jinja2 +7 -7
  8. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/domain/model.py.jinja2 +78 -16
  9. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/macros/triggers.jinja2 +6 -6
  10. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/macros/write.jinja2 +1 -1
  11. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/shared/__init__.py.jinja2 +2 -10
  12. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/shared/utils/__init__.py.jinja2 +1 -9
  13. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/shared/utils/funcs.py.jinja2 +0 -21
  14. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/__init__.py +2 -0
  15. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/base.py +32 -1
  16. tai_sql-0.6.4/tai_sql/orm/calculated.py +363 -0
  17. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/columns.py +15 -7
  18. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/table.py +9 -1
  19. {tai_sql-0.6.2 → tai_sql-0.6.4}/LICENSE +0 -0
  20. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/__init__.py +0 -0
  21. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_backup/__init__.py +0 -0
  22. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_backup/main.py +0 -0
  23. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_deploy/__init__.py +0 -0
  24. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_deploy/config.py +0 -0
  25. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_deploy/local.py +0 -0
  26. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_deploy/main.py +0 -0
  27. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_deploy/workflow.py +0 -0
  28. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_feed/__init__.py +0 -0
  29. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_feed/main.py +0 -0
  30. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_generate/__init__.py +0 -0
  31. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_generate/funcs.py +0 -0
  32. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_generate/main.py +0 -0
  33. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_info/__init__.py +0 -0
  34. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_info/main.py +0 -0
  35. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_info/status.py +0 -0
  36. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_init/__init__.py +0 -0
  37. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_init/main.py +0 -0
  38. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_init/model.py +0 -0
  39. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_install/__init__.py +0 -0
  40. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_install/main.py +0 -0
  41. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_ping/__init__.py +0 -0
  42. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_ping/main.py +0 -0
  43. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_restore/__init__.py +0 -0
  44. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_restore/main.py +0 -0
  45. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_roles/__init__.py +0 -0
  46. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_roles/main.py +0 -0
  47. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_schema/__init__.py +0 -0
  48. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_schema/model.py +0 -0
  49. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_schema/new.py +0 -0
  50. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/cmd_schema/set_default.py +0 -0
  51. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/utils/__init__.py +0 -0
  52. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/utils/connectivity.py +0 -0
  53. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/utils/create.py +0 -0
  54. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/utils/github/__init__.py +0 -0
  55. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/utils/github/auth.py +0 -0
  56. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/utils/github/client.py +0 -0
  57. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/commands/utils/github/models.py +0 -0
  58. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/main.py +0 -0
  59. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/services/__init__.py +0 -0
  60. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/services/backup.py +0 -0
  61. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/services/ddl.py +0 -0
  62. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/services/drift.py +0 -0
  63. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/services/feed.py +0 -0
  64. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/services/keycloak.py +0 -0
  65. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/cli/services/safety.py +0 -0
  66. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/core/__init__.py +0 -0
  67. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/core/funcs.py +0 -0
  68. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/core/provider.py +0 -0
  69. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/drivers/__init__.py +0 -0
  70. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/drivers/base.py +0 -0
  71. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/drivers/mysql.py +0 -0
  72. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/drivers/postgresql.py +0 -0
  73. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/drivers/sqlserver.py +0 -0
  74. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/__init__.py +0 -0
  75. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/base.py +0 -0
  76. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/diagram/__init__.py +0 -0
  77. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/base.py.jinja2 +0 -0
  78. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/domain/__init__.py.jinja2 +0 -0
  79. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/facade.py.jinja2 +0 -0
  80. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/macros/aggregation.jinja2 +0 -0
  81. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/macros/dataframe.jinja2 +0 -0
  82. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/macros/filters.jinja2 +0 -0
  83. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/macros/read.jinja2 +0 -0
  84. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/macros/upsert.jinja2 +0 -0
  85. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/macros/vector.jinja2 +0 -0
  86. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/session.py.jinja2 +0 -0
  87. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/shared/aggregation.py.jinja2 +0 -0
  88. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/shared/utils/encoders.py.jinja2 +0 -0
  89. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/generators/python_client/templates/shared/utils/rls.py.jinja2 +0 -0
  90. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/annotations.py +0 -0
  91. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/descriptors.py +0 -0
  92. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/encoders.py +0 -0
  93. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/enumerations.py +0 -0
  94. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/relations.py +0 -0
  95. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/triggers.py +0 -0
  96. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/types.py +0 -0
  97. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/orm/view.py +0 -0
  98. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/project.py +0 -0
  99. {tai_sql-0.6.2 → tai_sql-0.6.4}/tai_sql/schema.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tai-sql
3
- Version: 0.6.2
3
+ Version: 0.6.4
4
4
  Summary: SQL database management and code generation tool
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -133,6 +133,7 @@ users = public_sync_api.usuario.find_many(limit=10)
133
133
  - [Función `relation()`](#-función-relation---definición-de-relaciones)
134
134
  - [Encriptación de Columnas](#-encriptación-de-columnas)
135
135
  - [Columnas Vector](#-columnas-vector-pgvector)
136
+ - [Columnas Calculadas](#-columnas-calculadas-calculated_column)
136
137
  - [`View` — Definición de Vistas](#️-view---definición-de-vistas)
137
138
  - [`Enum` — Definición de Enumeraciones](#-enum---definición-de-enumeraciones)
138
139
  - [Triggers — Lógica de Negocio en Modelos](#-triggers---lógica-de-negocio-en-modelos)
@@ -757,6 +758,112 @@ embedding: vector = vector_column(
757
758
  - ✅ Si se omite `dimensions` y el encoder es conocido → se resuelve automáticamente
758
759
 
759
760
 
761
+ #### 🧮 Columnas Calculadas (`calculated_column`)
762
+
763
+ Las **columnas calculadas** son columnas físicas en la base de datos cuyo valor se computa automáticamente a partir de otras columnas. Se definen con el decorador `@calculated_column` directamente en el modelo y se recomputan en cada INSERT y UPDATE mediante event listeners de SQLAlchemy.
764
+
765
+ **Definición básica:**
766
+
767
+ ```python
768
+ from tai_sql import Table, column, calculated_column
769
+
770
+ class Usuario(Table):
771
+ __tablename__ = "usuario"
772
+
773
+ id: int = column(primary_key=True, autoincrement=True)
774
+ first_name: str
775
+ last_name: str
776
+
777
+ @calculated_column
778
+ def full_name(self) -> str:
779
+ """Nombre completo del usuario"""
780
+ return f"{self.first_name} {self.last_name}"
781
+ ```
782
+
783
+ Esto genera una columna física `full_name` de tipo `str` en la base de datos. El valor se calcula automáticamente al crear o actualizar el registro.
784
+
785
+ **Cuerpo multi-statement con imports externos:**
786
+
787
+ El cuerpo del método puede contener múltiples sentencias y usar imports del módulo donde se define el schema:
788
+
789
+ ```python
790
+ from unidecode import unidecode
791
+
792
+ class Producto(Table):
793
+ __tablename__ = "producto"
794
+
795
+ id: int = column(primary_key=True, autoincrement=True)
796
+ nombre: str
797
+ categoria: str
798
+
799
+ @calculated_column
800
+ def slug(self) -> str:
801
+ """Genera un slug SEO-friendly a partir del nombre y categoría"""
802
+ base = f"{self.nombre}-{self.categoria}"
803
+ normalized = unidecode(base).lower()
804
+ return normalized.replace(" ", "-")
805
+ ```
806
+
807
+ TAI-SQL extrae automáticamente los imports necesarios (en este caso `from unidecode import unidecode`) y los incluye en el modelo generado.
808
+
809
+ **Reglas:**
810
+
811
+ - El método debe tener anotación de tipo de retorno (`-> str`, `-> int`, `-> float`, etc.)
812
+ - El decorador `@calculated_column` debe ser el único decorador del método
813
+ - Las dependencias (`self.campo`) se detectan automáticamente vía AST
814
+ - Soporta tipos opcionales: `-> Optional[str]` genera una columna nullable
815
+
816
+ **Cómo funciona internamente:**
817
+
818
+ El modelo SQLAlchemy generado usa el mismo patrón que las columnas encriptadas:
819
+
820
+ 1. **Columna física** `_full_name` (con prefijo `_`) almacena el valor en la BD
821
+ 2. **`hybrid_property`** `full_name` expone lectura/escritura transparente
822
+ 3. **Event listeners** `before_insert` y `before_update` recomputan el valor automáticamente
823
+
824
+ ```python
825
+ # Código generado (simplificado)
826
+ class Usuario(Base):
827
+ _full_name = Column('full_name', String, nullable=False)
828
+
829
+ @hybrid_property
830
+ def full_name(self):
831
+ return self._full_name
832
+
833
+ @full_name.setter
834
+ def full_name(self, value):
835
+ self._full_name = value
836
+
837
+ def _recompute_full_name(self):
838
+ self._full_name = f"{self.first_name} {self.last_name}"
839
+
840
+ @event.listens_for(Usuario, 'before_insert')
841
+ def _usuario_before_insert(mapper, connection, target):
842
+ target._recompute_full_name()
843
+
844
+ @event.listens_for(Usuario, 'before_update')
845
+ def _usuario_before_update(mapper, connection, target):
846
+ target._recompute_full_name()
847
+ ```
848
+
849
+ **Comportamiento en DTOs generados:**
850
+
851
+ | DTO | Incluye columna calculada | Motivo |
852
+ |-----|--------------------------|--------|
853
+ | `Create` | ❌ No | Se computa automáticamente |
854
+ | `UpdateValues` | ❌ No | Se recomputa en cada update |
855
+ | `Read` | ✅ Sí | El valor almacenado es legible |
856
+ | `Filter` | ✅ Sí | Se puede filtrar por el valor almacenado |
857
+
858
+ **Características:**
859
+
860
+ - ✅ **Columna física**: El valor se almacena en la BD, indexable y filtrable
861
+ - ✅ **Recompute automático**: Se recalcula en cada INSERT y UPDATE via event listeners
862
+ - ✅ **Multi-statement**: Soporta cuerpos con múltiples sentencias
863
+ - ✅ **Import extraction**: Detecta y extrae imports externos usados en el cuerpo
864
+ - ✅ **Detección de dependencias**: Identifica qué columnas usa (`self.X`) vía análisis AST
865
+ - ✅ **Transparente**: El CRUD generado maneja todo automáticamente — el usuario no necesita calcular nada
866
+
760
867
  ### 👁️ `View` - Definición de Vistas
761
868
 
762
869
  Las vistas permiten crear consultas complejas reutilizables:
@@ -82,6 +82,7 @@ users = public_sync_api.usuario.find_many(limit=10)
82
82
  - [Función `relation()`](#-función-relation---definición-de-relaciones)
83
83
  - [Encriptación de Columnas](#-encriptación-de-columnas)
84
84
  - [Columnas Vector](#-columnas-vector-pgvector)
85
+ - [Columnas Calculadas](#-columnas-calculadas-calculated_column)
85
86
  - [`View` — Definición de Vistas](#️-view---definición-de-vistas)
86
87
  - [`Enum` — Definición de Enumeraciones](#-enum---definición-de-enumeraciones)
87
88
  - [Triggers — Lógica de Negocio en Modelos](#-triggers---lógica-de-negocio-en-modelos)
@@ -706,6 +707,112 @@ embedding: vector = vector_column(
706
707
  - ✅ Si se omite `dimensions` y el encoder es conocido → se resuelve automáticamente
707
708
 
708
709
 
710
+ #### 🧮 Columnas Calculadas (`calculated_column`)
711
+
712
+ Las **columnas calculadas** son columnas físicas en la base de datos cuyo valor se computa automáticamente a partir de otras columnas. Se definen con el decorador `@calculated_column` directamente en el modelo y se recomputan en cada INSERT y UPDATE mediante event listeners de SQLAlchemy.
713
+
714
+ **Definición básica:**
715
+
716
+ ```python
717
+ from tai_sql import Table, column, calculated_column
718
+
719
+ class Usuario(Table):
720
+ __tablename__ = "usuario"
721
+
722
+ id: int = column(primary_key=True, autoincrement=True)
723
+ first_name: str
724
+ last_name: str
725
+
726
+ @calculated_column
727
+ def full_name(self) -> str:
728
+ """Nombre completo del usuario"""
729
+ return f"{self.first_name} {self.last_name}"
730
+ ```
731
+
732
+ Esto genera una columna física `full_name` de tipo `str` en la base de datos. El valor se calcula automáticamente al crear o actualizar el registro.
733
+
734
+ **Cuerpo multi-statement con imports externos:**
735
+
736
+ El cuerpo del método puede contener múltiples sentencias y usar imports del módulo donde se define el schema:
737
+
738
+ ```python
739
+ from unidecode import unidecode
740
+
741
+ class Producto(Table):
742
+ __tablename__ = "producto"
743
+
744
+ id: int = column(primary_key=True, autoincrement=True)
745
+ nombre: str
746
+ categoria: str
747
+
748
+ @calculated_column
749
+ def slug(self) -> str:
750
+ """Genera un slug SEO-friendly a partir del nombre y categoría"""
751
+ base = f"{self.nombre}-{self.categoria}"
752
+ normalized = unidecode(base).lower()
753
+ return normalized.replace(" ", "-")
754
+ ```
755
+
756
+ TAI-SQL extrae automáticamente los imports necesarios (en este caso `from unidecode import unidecode`) y los incluye en el modelo generado.
757
+
758
+ **Reglas:**
759
+
760
+ - El método debe tener anotación de tipo de retorno (`-> str`, `-> int`, `-> float`, etc.)
761
+ - El decorador `@calculated_column` debe ser el único decorador del método
762
+ - Las dependencias (`self.campo`) se detectan automáticamente vía AST
763
+ - Soporta tipos opcionales: `-> Optional[str]` genera una columna nullable
764
+
765
+ **Cómo funciona internamente:**
766
+
767
+ El modelo SQLAlchemy generado usa el mismo patrón que las columnas encriptadas:
768
+
769
+ 1. **Columna física** `_full_name` (con prefijo `_`) almacena el valor en la BD
770
+ 2. **`hybrid_property`** `full_name` expone lectura/escritura transparente
771
+ 3. **Event listeners** `before_insert` y `before_update` recomputan el valor automáticamente
772
+
773
+ ```python
774
+ # Código generado (simplificado)
775
+ class Usuario(Base):
776
+ _full_name = Column('full_name', String, nullable=False)
777
+
778
+ @hybrid_property
779
+ def full_name(self):
780
+ return self._full_name
781
+
782
+ @full_name.setter
783
+ def full_name(self, value):
784
+ self._full_name = value
785
+
786
+ def _recompute_full_name(self):
787
+ self._full_name = f"{self.first_name} {self.last_name}"
788
+
789
+ @event.listens_for(Usuario, 'before_insert')
790
+ def _usuario_before_insert(mapper, connection, target):
791
+ target._recompute_full_name()
792
+
793
+ @event.listens_for(Usuario, 'before_update')
794
+ def _usuario_before_update(mapper, connection, target):
795
+ target._recompute_full_name()
796
+ ```
797
+
798
+ **Comportamiento en DTOs generados:**
799
+
800
+ | DTO | Incluye columna calculada | Motivo |
801
+ |-----|--------------------------|--------|
802
+ | `Create` | ❌ No | Se computa automáticamente |
803
+ | `UpdateValues` | ❌ No | Se recomputa en cada update |
804
+ | `Read` | ✅ Sí | El valor almacenado es legible |
805
+ | `Filter` | ✅ Sí | Se puede filtrar por el valor almacenado |
806
+
807
+ **Características:**
808
+
809
+ - ✅ **Columna física**: El valor se almacena en la BD, indexable y filtrable
810
+ - ✅ **Recompute automático**: Se recalcula en cada INSERT y UPDATE via event listeners
811
+ - ✅ **Multi-statement**: Soporta cuerpos con múltiples sentencias
812
+ - ✅ **Import extraction**: Detecta y extrae imports externos usados en el cuerpo
813
+ - ✅ **Detección de dependencias**: Identifica qué columnas usa (`self.X`) vía análisis AST
814
+ - ✅ **Transparente**: El CRUD generado maneja todo automáticamente — el usuario no necesita calcular nada
815
+
709
816
  ### 👁️ `View` - Definición de Vistas
710
817
 
711
818
  Las vistas permiten crear consultas complejas reutilizables:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "tai-sql"
3
- version = "0.6.2"
3
+ version = "0.6.4"
4
4
  description = "SQL database management and code generation tool"
5
5
  license = {text = "MIT"}
6
6
  authors = [
@@ -21,7 +21,8 @@ from .orm import (
21
21
  Table, View, Enum, column, vector, vector_column, VectorColumn,
22
22
  relation, TriggerAPI, on_create, on_update, on_delete,
23
23
  trigger_api, col, onetomany, manytoone, onetoone, get_type_registry,
24
- register_type, TypeDescriptor, BaseEncoder, SentenceTransformerEncoder
24
+ register_type, TypeDescriptor, BaseEncoder, SentenceTransformerEncoder,
25
+ calculated_column,
25
26
  )
26
27
 
27
28
  from .drivers import postgresql, mysql, sqlserver
@@ -50,6 +51,7 @@ __all__ = [
50
51
  'on_update',
51
52
  'on_delete',
52
53
  'trigger_api',
54
+ 'calculated_column',
53
55
  'query',
54
56
  'View',
55
57
  'Enum',
@@ -32,10 +32,12 @@ class PythonClientGenerator(BaseGenerator):
32
32
  pool_recycle: Optional[int] = None,
33
33
  ssl: Optional[bool] = None,
34
34
  sqlalchemy_logs: Optional[bool] = None,
35
+ import_prefix: str = '..',
35
36
  ):
36
37
  super().__init__(output_dir)
37
38
  self.max_depth = max_depth
38
39
  self.logger_name = logger_name
40
+ self.import_prefix = import_prefix
39
41
  self._pool_size = pool_size
40
42
  self._max_overflow = max_overflow
41
43
  self._pool_timeout = pool_timeout
@@ -142,6 +144,12 @@ class PythonClientGenerator(BaseGenerator):
142
144
  for col in model.columns.values()
143
145
  )
144
146
 
147
+ def _model_has_calculated(self, model: Table | View) -> bool:
148
+ return any(
149
+ hasattr(col, 'is_calculated') and col.is_calculated
150
+ for col in model.columns.values()
151
+ )
152
+
145
153
  def _all_models_data(self, mode: str = 'sync') -> List[Dict[str, Any]]:
146
154
  return [model.info(mode) for model in self.models]
147
155
 
@@ -258,6 +266,7 @@ class PythonClientGenerator(BaseGenerator):
258
266
  schema_name=pm.db.schema_name,
259
267
  models=all_models_data,
260
268
  model_imports=model_imports,
269
+ shared_import_prefix='.' + self.import_prefix,
261
270
  )
262
271
  (utils_dir / 'funcs.py').write_text(funcs_code, encoding='utf-8')
263
272
 
@@ -293,6 +302,8 @@ class PythonClientGenerator(BaseGenerator):
293
302
  is_postgres=pm.db.provider.drivername == 'postgresql',
294
303
  schema_name=pm.db.schema_name,
295
304
  encrypt=self._model_has_encrypt(model),
305
+ has_calculated=self._model_has_calculated(model),
306
+ import_prefix=self.import_prefix,
296
307
  )
297
308
  (domain / 'model.py').write_text(code, encoding='utf-8')
298
309
 
@@ -305,6 +316,7 @@ class PythonClientGenerator(BaseGenerator):
305
316
  models=all_models,
306
317
  schema_name=pm.db.schema_name,
307
318
  max_depth=self.max_depth,
319
+ import_prefix=self.import_prefix,
308
320
  )
309
321
  (domain / 'dtos.py').write_text(code, encoding='utf-8')
310
322
 
@@ -332,6 +344,7 @@ class PythonClientGenerator(BaseGenerator):
332
344
  await_keyword='await ' if is_async else '',
333
345
  with_keyword='async with' if is_async else 'with',
334
346
  error_handler_name='async_error_handler' if is_async else 'sync_error_handler',
347
+ import_prefix=self.import_prefix,
335
348
  )
336
349
  filename = 'dao_async.py' if is_async else 'dao_sync.py'
337
350
  (domain / filename).write_text(code, encoding='utf-8')
@@ -48,7 +48,7 @@ from sqlalchemy.orm import defer
48
48
  {% endif %}
49
49
  from .model import {{ model.name }}
50
50
  from .dtos import *
51
- from .._shared import (
51
+ from {{ import_prefix }}_shared import (
52
52
  {{ error_handler_name }},
53
53
  get_loading_options,
54
54
  get_included_relations,
@@ -67,7 +67,7 @@ from .._shared import (
67
67
  AggField,
68
68
  GroupByField
69
69
  )
70
- from .._session import {{ session_manager_var }}
70
+ from {{ import_prefix }}_session import {{ session_manager_var }}
71
71
  {# ── Collect cross-DAO targets (relations + trigger cross-table ops) ── #}
72
72
  {% set _cross_dao_targets = [] %}
73
73
  {% for rel in model.relations | default([]) %}
@@ -84,7 +84,7 @@ from .._session import {{ session_manager_var }}
84
84
  {% set _ = _cross_dao_targets.append({'name': target_name, 'tablename': target_tablename}) %}
85
85
  {% endif %}
86
86
  {# DTO imports for cross-table trigger operations #}
87
- from ..{{ target_tablename }}.dtos import * # trigger cross-table: {{ target_name }}
87
+ from {{ import_prefix }}{{ target_tablename }}.dtos import * # trigger cross-table: {{ target_name }}
88
88
  {% endif %}
89
89
  {% endif %}
90
90
  {% endfor %}
@@ -101,7 +101,7 @@ logger = Alphi.get_logger_by_name("{{ logger_name }}")
101
101
  # ── Vector encoders ──────────────────────────────────────────────────────
102
102
  {% for vcol in vector_cols_with_encoder %}
103
103
  {% if vcol.encoder_config %}
104
- from .._shared.utils.encoders import {{ model.tablename }}_{{ vcol.name }}_encoder as _{{ vcol.name }}_encoder
104
+ from {{ import_prefix }}_shared.utils.encoders import {{ model.tablename }}_{{ vcol.name }}_encoder as _{{ vcol.name }}_encoder
105
105
  {% endif %}
106
106
  {% endfor %}
107
107
  {% if is_async %}
@@ -49,7 +49,7 @@ from pydantic import (
49
49
  )
50
50
 
51
51
  from .model import {{ model.name }}
52
- from .._shared import (
52
+ from {{ import_prefix }}_shared import (
53
53
  PrettyModel,
54
54
  should_include_relation,
55
55
  get_nested_includes
@@ -63,7 +63,7 @@ if TYPE_CHECKING:
63
63
  # ── Vector encoders ──────────────────────────────────────────────────────
64
64
  {% for vcol in _dto_encoder_cols %}
65
65
  {% if vcol.encoder_config %}
66
- from .._shared.utils.encoders import {{ model.tablename }}_{{ vcol.name }}_encoder as _{{ vcol.name }}_encoder
66
+ from {{ import_prefix }}_shared.utils.encoders import {{ model.tablename }}_{{ vcol.name }}_encoder as _{{ vcol.name }}_encoder
67
67
  {% endif %}
68
68
  {% endfor %}
69
69
  {% endif %}
@@ -214,12 +214,12 @@ class {{ model.name }}Read(PrettyModel):
214
214
  class {{ model.name }}Create(PrettyModel):
215
215
  """DTO de escritura para {{ model.name }}."""
216
216
  {% for column in model.columns -%}
217
- {% if not column.constraints.get('autoincrement', False) and column.default is none and not column.nullable and not column.is_foreign_key and not column.is_operative and not column.has_encoder|default(false) %}
217
+ {% if not column.constraints.get('autoincrement', False) and column.default is none and not column.nullable and not column.is_foreign_key and not column.is_operative and not column.has_encoder|default(false) and not column.is_calculated %}
218
218
  {{ column.name }}: {{ column.pydantic_type }}
219
219
  {% endif %}
220
220
  {% endfor %}
221
221
  {% for column in model.columns -%}
222
- {% if not column.is_operative %}
222
+ {% if not column.is_operative and not column.is_calculated %}
223
223
  {% if column.has_encoder|default(false) %}
224
224
  {{ column.name }}: Optional[{{ column.pydantic_type }}] = None
225
225
  {% elif column.is_foreign_key %}
@@ -261,7 +261,7 @@ class {{ model.name }}Create(PrettyModel):
261
261
  def to_instance(self) -> {{ model.name }}:
262
262
  model = {{ model.name }}(
263
263
  {% for column in model.columns %}
264
- {% if not column.constraints.get('autoincrement', False) and not column.is_operative %}
264
+ {% if not column.constraints.get('autoincrement', False) and not column.is_operative and not column.is_calculated %}
265
265
  {{ column.name }}=self.{{ column.name }},
266
266
  {% endif %}
267
267
  {% endfor %}
@@ -373,7 +373,7 @@ class {{ model.name }}UpdateNested(PrettyModel):
373
373
  class {{ model.name }}UpdateValues(PrettyModel):
374
374
  """DTO de actualización para {{ model.name }}."""
375
375
  {% for column in model.columns -%}
376
- {% if not column.constraints.get('autoincrement', False) and not column.is_operative %}
376
+ {% if not column.constraints.get('autoincrement', False) and not column.is_operative and not column.is_calculated %}
377
377
  {% if not column.nullable %}
378
378
  {{ column.name }}: {{ column.pydantic_type }} = None
379
379
  {% else %}
@@ -426,7 +426,7 @@ class {{ model.name }}Update(PrettyModel):
426
426
  {% set target_info = models | selectattr('name', 'equalto', rel.target) | first %}
427
427
  {% if target_info and rel.target != model.name and rel.target not in related_targets %}
428
428
  {% set _ = related_targets.append(rel.target) %}
429
- from ..{{ target_info.tablename }}.dtos import (
429
+ from {{ import_prefix }}{{ target_info.tablename }}.dtos import (
430
430
  {{ rel.target }}Read,
431
431
  {% if not model.is_view %}
432
432
  {{ rel.target }}Create,
@@ -10,16 +10,20 @@
10
10
  is_postgres bool — True if the target database is PostgreSQL
11
11
  schema_name str — Database schema name (e.g. 'public')
12
12
  encrypt bool — True if the model has encrypted columns
13
+ has_calculated bool — True if the model has calculated columns
14
+ import_prefix str — Relative import prefix to reach schema root (default '..')
13
15
 
14
16
  Template sections:
15
17
  1. Imports — stdlib, typing, SQLAlchemy, cross-domain models
16
18
  2. Class header — __tablename__, is_view flag
17
- 3. Encrypted init Custom __init__ for encrypted column interception
19
+ 3. Custom init — __init__ for encrypted/calculated column interception
18
20
  4. Columns — Mapped[] declarations with mapped_column() args
19
21
  5. Encrypted props — hybrid_property get/set for encrypted columns
20
- 6. Relationships SQLAlchemy relationship() declarations
21
- 7. Table args ForeignKeyConstraint + schema config
22
- 8. Mapper args primary_key override for views
22
+ 6. Calculated propshybrid_property + recompute for calculated columns
23
+ 7. Relationships SQLAlchemy relationship() declarations
24
+ 8. Table args ForeignKeyConstraint + schema config
25
+ 9. Mapper args — primary_key override for views
26
+ 10. Event listeners — before_insert/before_update for calculated columns
23
27
  ───────────────────────────────────────────────────────────────────────── #}
24
28
  # Este archivo ha sido generado automáticamente por tai-sql
25
29
  # No modifiques este archivo directamente
@@ -30,9 +34,9 @@ from __future__ import annotations
30
34
  from typing import Optional{% if is_postgres %}, List{% endif %}{% if model.relations | default([]) | list %}, TYPE_CHECKING{% endif %}
31
35
 
32
36
  {% if is_view %}
33
- from .._base import Base
37
+ from {{ import_prefix }}_base import Base
34
38
  {% else %}
35
- from .._base import Base{% if encrypt %}, encrypt_value, decrypt_value{% endif %}
39
+ from {{ import_prefix }}_base import Base{% if encrypt %}, encrypt_value, decrypt_value{% endif %}
36
40
 
37
41
  {% endif %}
38
42
  from sqlalchemy.orm import Mapped, mapped_column{% if model.relations | default([]) | list %}, relationship{% endif %}
@@ -71,16 +75,26 @@ from pgvector.sqlalchemy import Vector
71
75
  {% if sa_imports %}
72
76
  from sqlalchemy import {{ sa_imports | sort | join(', ') }}
73
77
  {% endif %}
74
- {% if encrypt %}
78
+ {% if encrypt or has_calculated %}
75
79
  from sqlalchemy.ext.hybrid import hybrid_property
76
80
  {% endif %}
81
+ {% if has_calculated %}
82
+ from sqlalchemy import event
83
+ {% endif %}
84
+
85
+ {# Imports required by calculated column computations #}
86
+ {% for calc_col in model.calculated_columns | default([]) %}
87
+ {% for imp in calc_col.imports | default([]) %}
88
+ {{ imp }}
89
+ {% endfor %}
90
+ {% endfor %}
77
91
 
78
92
  {# Cross-domain model imports — TYPE_CHECKING only (annotations are lazy via __future__) #}
79
93
  {% if model.relations | default([]) | selectattr('target', 'ne', model.name) | list %}
80
94
  if TYPE_CHECKING:
81
95
  {% for rel in model.relations | default([]) %}
82
96
  {% if rel.target != model.name %}
83
- from ..{{ rel.target_tablename }}.model import {{ rel.target }}
97
+ from {{ import_prefix }}{{ rel.target_tablename }}.model import {{ rel.target }}
84
98
  {% endif %}
85
99
  {% endfor %}
86
100
  {% endif %}
@@ -96,18 +110,26 @@ class {{ model.name }}(Base):
96
110
  is_view = True
97
111
  {% endif %}
98
112
 
99
- {# ── 3. Encrypted __init__ ───────────────────────────────────────────── #}
113
+ {# ── 3. Custom __init__ ───────────────────────────────────────────────── #}
100
114
  {# Intercepts encrypted column values before SQLAlchemy sets the raw column,
101
- routing them through the hybrid_property setter that encrypts on write. #}
115
+ routing them through the hybrid_property setter that encrypts on write.
116
+ Also pops calculated column kwargs (they are auto-computed). #}
102
117
  {% set encrypted_columns = model.columns | selectattr('encrypt') | list %}
103
- {% if encrypted_columns %}
118
+ {% set calculated_columns = model.calculated_columns | default([]) %}
119
+ {% if encrypted_columns or calculated_columns %}
104
120
  def __init__(self, **kwargs):
105
121
  {% for column in encrypted_columns %}
106
122
  if '{{ column.name }}' in kwargs:
107
123
  {{ column.name }}_value = kwargs.pop('{{ column.name }}')
108
124
  self.{{ column.name }} = {{ column.name }}_value
109
125
  {% endfor %}
126
+ {% for calc_col in calculated_columns %}
127
+ kwargs.pop('{{ calc_col.name }}', None)
128
+ {% endfor %}
110
129
  super().__init__(**kwargs)
130
+ {% for calc_col in calculated_columns %}
131
+ self._recompute_{{ calc_col.name }}()
132
+ {% endfor %}
111
133
  {% endif %}
112
134
 
113
135
  {# ── 4. Columns ──────────────────────────────────────────────────────── #}
@@ -123,14 +145,14 @@ class {{ model.name }}(Base):
123
145
  3. name= override when the column is encrypted (_name vs name in DB)
124
146
  - Columns without any SA type or constraints use bare Mapped[T]. #}
125
147
  {% for column in model.columns %}
126
- {# Encrypted columns use a private attribute; the public name becomes a hybrid_property #}
127
- {% set col_attr = '_' + column.name if column.encrypt else column.name %}
148
+ {# Encrypted and calculated columns use a private attribute; the public name becomes a hybrid_property #}
149
+ {% set col_attr = '_' + column.name if (column.encrypt or column.is_calculated) else column.name %}
128
150
  {# Python type for the Mapped[] annotation — always a native Python type #}
129
151
  {% set py_type = 'Dict[str, Any]' if column.python_type == 'dict' else ('List[float]' if column.type == 'vector' else column.python_type) %}
130
152
  {% set mapped_type = 'Optional[' + py_type + ']' if column.nullable else py_type %}
131
153
  {# Determine if mapped_column() call is needed #}
132
154
  {% set has_constraints = column.constraints.values() | select | list | length > 0 %}
133
- {% set needs_mapped_column = has_constraints or column.encrypt or column.sa_type is not none or column.type == 'vector' %}
155
+ {% set needs_mapped_column = has_constraints or column.encrypt or column.is_calculated or column.sa_type is not none or column.type == 'vector' %}
134
156
  {% if needs_mapped_column %}
135
157
  {% set mc_args = [] %}
136
158
  {% if column.type == 'vector' %}{% set _ = mc_args.append('Vector(' + column.dimensions|string + ')') %}
@@ -150,6 +172,7 @@ class {{ model.name }}(Base):
150
172
  {% endfor %}
151
173
  {% endif %}
152
174
  {% if column.encrypt %}{% set _ = mc_args.append('name="' + column.name + '"') %}{% endif %}
175
+ {% if column.is_calculated %}{% set _ = mc_args.append('name="' + column.name + '"') %}{% endif %}
153
176
  {{ col_attr }}: Mapped[{{ mapped_type }}] = mapped_column({{ mc_args | join(', ') }})
154
177
  {% else %}
155
178
  {{ col_attr }}: Mapped[{{ mapped_type }}]
@@ -178,7 +201,34 @@ class {{ model.name }}(Base):
178
201
  {% endif %}
179
202
  {% endfor %}
180
203
 
181
- {# ── 6. Relationships ────────────────────────────────────────────────── #}
204
+ {# ── 6. Calculated hybrid properties ─────────────────────────────────── #}
205
+ {# For each calculated column, expose a hybrid_property that reads the
206
+ stored value. The setter allows direct assignment; the expression
207
+ clause maps to the physical _<name> column for SQL-level queries.
208
+ A _recompute_<name>() helper contains the user-defined computation. #}
209
+ {% for calc_col in model.calculated_columns | default([]) %}
210
+ {% set prop_type = 'Optional[' + calc_col.python_type + ']' if calc_col.nullable else calc_col.python_type %}
211
+
212
+ @hybrid_property
213
+ def {{ calc_col.name }}(self) -> {{ prop_type }}:
214
+ return self._{{ calc_col.name }}
215
+
216
+ @{{ calc_col.name }}.setter
217
+ def {{ calc_col.name }}(self, value: {{ prop_type }}):
218
+ self._{{ calc_col.name }} = value
219
+
220
+ @{{ calc_col.name }}.expression
221
+ def {{ calc_col.name }}(cls):
222
+ return cls._{{ calc_col.name }}
223
+
224
+ def _recompute_{{ calc_col.name }}(self):
225
+ """Recompute calculated column ``{{ calc_col.name }}``."""
226
+ {% for line in calc_col.body_lines %}
227
+ {{ line }}
228
+ {% endfor %}
229
+ {% endfor %}
230
+
231
+ {# ── 7. Relationships ────────────────────────────────────────────────── #}
182
232
  {# SQLAlchemy relationship() with:
183
233
  - back_populates for bidirectional navigation
184
234
  - foreign_keys as string expression to avoid circular import issues
@@ -217,7 +267,7 @@ class {{ model.name }}(Base):
217
267
  __table_args__ = {'schema': '{{ schema_name }}'}
218
268
  {% endif %}
219
269
 
220
- {# ── 8. Mapper args — synthetic PK for views ────────────────────────── #}
270
+ {# ── 9. Mapper args — synthetic PK for views ────────────────────────── #}
221
271
  {% if model.is_view %}
222
272
  __mapper_args__ = {'primary_key': [
223
273
  {% for column in model.columns %}
@@ -225,3 +275,15 @@ class {{ model.name }}(Base):
225
275
  {% endfor %}
226
276
  ]}
227
277
  {% endif %}
278
+
279
+ {# ── 10. Event listeners — auto-recompute calculated columns ─────────── #}
280
+ {% if model.calculated_columns | default([]) %}
281
+
282
+ @event.listens_for({{ model.name }}, 'before_insert')
283
+ @event.listens_for({{ model.name }}, 'before_update')
284
+ def _recompute_{{ model.tablename }}_calculated(mapper, connection, target: {{ model.name }}):
285
+ """Recompute all calculated columns before insert/update."""
286
+ {% for calc_col in model.calculated_columns %}
287
+ target._recompute_{{ calc_col.name }}()
288
+ {% endfor %}
289
+ {% endif %}
@@ -23,7 +23,7 @@
23
23
  {% endfor %}
24
24
  {% if _dao_targets %}
25
25
  {% for t in _dao_targets %}
26
- from ..{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
26
+ from {{ import_prefix }}{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
27
27
  {% endfor %}
28
28
  {% set ns_hook.has_content = true %}
29
29
  {% endif %}
@@ -83,7 +83,7 @@
83
83
  {% endfor %}
84
84
  {% if _dao_targets %}
85
85
  {% for t in _dao_targets %}
86
- from ..{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
86
+ from {{ import_prefix }}{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
87
87
  {% endfor %}
88
88
  {% set ns_hook.has_content = true %}
89
89
  {% endif %}
@@ -136,7 +136,7 @@
136
136
  {% endfor %}
137
137
  {% if _dao_targets %}
138
138
  {% for t in _dao_targets %}
139
- from ..{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
139
+ from {{ import_prefix }}{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
140
140
  {% endfor %}
141
141
  {% set ns_hook.has_content = true %}
142
142
  {% endif %}
@@ -179,7 +179,7 @@
179
179
  {% endfor %}
180
180
  {% if _dao_targets %}
181
181
  {% for t in _dao_targets %}
182
- from ..{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
182
+ from {{ import_prefix }}{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
183
183
  {% endfor %}
184
184
  {% set ns_hook.has_content = true %}
185
185
  {% endif %}
@@ -222,7 +222,7 @@
222
222
  {% endfor %}
223
223
  {% if _dao_targets %}
224
224
  {% for t in _dao_targets %}
225
- from ..{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
225
+ from {{ import_prefix }}{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
226
226
  {% endfor %}
227
227
  {% set ns_hook.has_content = true %}
228
228
  {% endif %}
@@ -257,7 +257,7 @@
257
257
  {% endfor %}
258
258
  {% if _dao_targets %}
259
259
  {% for t in _dao_targets %}
260
- from ..{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
260
+ from {{ import_prefix }}{{ t.tablename }}.dao_{{ "async" if is_async else "sync" }} import {{ t.name }}{{ prefix }}DAO
261
261
  {% endfor %}
262
262
  {% set ns_hook.has_content = true %}
263
263
  {% endif %}