|
| 1 | +import sqlalchemy as sa |
| 2 | +from sqlalchemy.event import listen |
| 3 | +import typing as t |
| 4 | + |
| 5 | +from sqlalchemy_cratedb.support.util import refresh_dirty, refresh_table |
| 6 | + |
| 7 | + |
| 8 | +def patch_autoincrement_timestamp(): |
| 9 | + """ |
| 10 | + Configure SQLAlchemy model columns with an alternative to `autoincrement=True`. |
| 11 | + Use the current timestamp instead. |
| 12 | +
|
| 13 | + This is used by CrateDB's MLflow adapter. |
| 14 | +
|
| 15 | + TODO: Maybe enable through a dialect parameter `crate_polyfill_autoincrement` or such. |
| 16 | + """ |
| 17 | + import sqlalchemy.sql.schema as schema |
| 18 | + |
| 19 | + init_dist = schema.Column.__init__ |
| 20 | + |
| 21 | + def __init__(self, *args, **kwargs): |
| 22 | + if "autoincrement" in kwargs: |
| 23 | + del kwargs["autoincrement"] |
| 24 | + if "default" not in kwargs: |
| 25 | + kwargs["default"] = sa.func.now() |
| 26 | + init_dist(self, *args, **kwargs) |
| 27 | + |
| 28 | + schema.Column.__init__ = __init__ # type: ignore[method-assign] |
| 29 | + |
| 30 | + |
| 31 | +def check_uniqueness_factory(sa_entity, *attribute_names): |
| 32 | + """ |
| 33 | + Run a manual column value uniqueness check on a table, and raise an IntegrityError if applicable. |
| 34 | +
|
| 35 | + CrateDB does not support the UNIQUE constraint on columns. This attempts to emulate it. |
| 36 | +
|
| 37 | + https://github.com/crate/sqlalchemy-cratedb/issues/76 |
| 38 | +
|
| 39 | + This is used by CrateDB's MLflow adapter. |
| 40 | +
|
| 41 | + TODO: Maybe enable through a dialect parameter `crate_polyfill_unique` or such. |
| 42 | + """ |
| 43 | + |
| 44 | + # Synthesize a canonical "name" for the constraint, |
| 45 | + # composed of all column names involved. |
| 46 | + constraint_name: str = "-".join(attribute_names) |
| 47 | + |
| 48 | + def check_uniqueness(mapper, connection, target): |
| 49 | + from sqlalchemy.exc import IntegrityError |
| 50 | + |
| 51 | + if isinstance(target, sa_entity): |
| 52 | + # TODO: How to use `session.query(SqlExperiment)` here? |
| 53 | + stmt = mapper.selectable.select() |
| 54 | + for attribute_name in attribute_names: |
| 55 | + stmt = stmt.filter(getattr(sa_entity, attribute_name) == getattr(target, attribute_name)) |
| 56 | + stmt = stmt.compile(bind=connection.engine) |
| 57 | + results = connection.execute(stmt) |
| 58 | + if results.rowcount > 0: |
| 59 | + raise IntegrityError( |
| 60 | + statement=stmt, |
| 61 | + params=[], |
| 62 | + orig=Exception( |
| 63 | + f"DuplicateKeyException in table '{target.__tablename__}' " f"on constraint '{constraint_name}'" |
| 64 | + ), |
| 65 | + ) |
| 66 | + |
| 67 | + return check_uniqueness |
| 68 | + |
| 69 | + |
| 70 | +def refresh_after_dml_session(session: sa.orm.Session): |
| 71 | + """ |
| 72 | + Run `REFRESH TABLE` after each DML operation (INSERT, UPDATE, DELETE). |
| 73 | +
|
| 74 | + CrateDB is eventually consistent, i.e. write operations are not flushed to |
| 75 | + disk immediately, so readers may see stale data. In a traditional OLTP-like |
| 76 | + application, this is not applicable. |
| 77 | +
|
| 78 | + This SQLAlchemy extension makes sure that data is synchronized after each |
| 79 | + operation manipulating data. |
| 80 | +
|
| 81 | + > `after_{insert,update,delete}` events only apply to the session flush operation |
| 82 | + > and do not apply to the ORM DML operations described at ORM-Enabled INSERT, |
| 83 | + > UPDATE, and DELETE statements. To intercept ORM DML events, use |
| 84 | + > `SessionEvents.do_orm_execute().` |
| 85 | + > -- https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.MapperEvents.after_insert |
| 86 | +
|
| 87 | + > Intercept statement executions that occur on behalf of an ORM Session object. |
| 88 | + > -- https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.SessionEvents.do_orm_execute |
| 89 | +
|
| 90 | + > Execute after flush has completed, but before commit has been called. |
| 91 | + > -- https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.SessionEvents.after_flush |
| 92 | +
|
| 93 | + This is used by CrateDB's LangChain adapter. |
| 94 | +
|
| 95 | + TODO: Maybe enable through a dialect parameter `crate_dml_refresh` or such. |
| 96 | + """ # noqa: E501 |
| 97 | + listen(session, "after_flush", refresh_dirty) |
| 98 | + |
| 99 | + |
| 100 | +def refresh_after_dml_engine(engine: sa.engine.Engine): |
| 101 | + """ |
| 102 | + Run `REFRESH TABLE` after each DML operation (INSERT, UPDATE, DELETE). |
| 103 | +
|
| 104 | + This is used by CrateDB's Singer/Meltano and `rdflib-sqlalchemy` adapters. |
| 105 | + """ |
| 106 | + def receive_after_execute( |
| 107 | + conn: sa.engine.Connection, clauseelement, multiparams, params, execution_options, result |
| 108 | + ): |
| 109 | + if isinstance(clauseelement, (sa.sql.Insert, sa.sql.Update, sa.sql.Delete)): |
| 110 | + if not isinstance(clauseelement.table, sa.sql.Join): |
| 111 | + full_table_name = f'"{clauseelement.table.name}"' |
| 112 | + if clauseelement.table.schema is not None: |
| 113 | + full_table_name = f'"{clauseelement.table.schema}".' + full_table_name |
| 114 | + refresh_table(conn, full_table_name) |
| 115 | + |
| 116 | + sa.event.listen(engine, "after_execute", receive_after_execute) |
| 117 | + |
| 118 | + |
| 119 | +def refresh_after_dml(engine_or_session: t.Union[sa.engine.Engine, sa.orm.Session]): |
| 120 | + """ |
| 121 | + Run `REFRESH TABLE` after each DML operation (INSERT, UPDATE, DELETE). |
| 122 | + """ |
| 123 | + if isinstance(engine_or_session, sa.engine.Engine): |
| 124 | + refresh_after_dml_engine(engine_or_session) |
| 125 | + elif isinstance(engine_or_session, (sa.orm.Session, sa.orm.scoping.scoped_session)): |
| 126 | + refresh_after_dml_session(engine_or_session) |
| 127 | + else: |
| 128 | + raise TypeError(f"Unknown type: {type(engine_or_session)}") |
0 commit comments