__all__ = [
    'add_if_not_exists_clause',
    'executing',
    'one_or_none',
]

import contextlib

from sqlalchemy.schema import CreateIndex

from g1.bases.assertions import ASSERT


def add_if_not_exists_clause(index, engine):
    """Add "IF NOT EXISTS" clause to create index statement.

    I don't know why but ``sqlalchemy.Index.create()`` does not take a
    ``checkfirst`` argument like the rest of others.
    """
    stmt = str(CreateIndex(index).compile(engine))
    stmt = stmt.replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS', 1)
    ASSERT.in_('IF NOT EXISTS', stmt)
    return stmt


@contextlib.contextmanager
def executing(engine, statement):
    with engine.connect() as conn:
        result = conn.execute(statement)
        try:
            yield result
        finally:
            result.close()


# I don't know why but SQLAlchemy only make this available in ORM, not
# in core.
def one_or_none(engine, statement):
    with executing(engine, statement) as result:
        row = result.fetchone()
        ASSERT.none(result.fetchone())
        return row

@@ -95,16 +95,41 @@
 extlib%0A%0A
+import sqlalchemy.engine%0A
 from sql
@@ -240,21 +240,26 @@
 (index, 
-engin
+connectabl
 e):%0A    
@@ -490,21 +490,26 @@
 compile(
-engin
+connectabl
 e))%0A    
@@ -666,37 +666,42 @@
 r%0Adef executing(
-engin
+connectabl
 e, statement):%0A 
@@ -707,38 +707,315 @@
     
-with engine.connect() as conn:
+if isinstance(connectable, sqlalchemy.engine.Connection):%0A        # Do NOT close Connection object that caller passes to us.%0A        ctx = contextlib.nullcontext(connectable)%0A    else:%0A        ctx = connectable.connect()%0A    with ctx as conn:%0A        # ResultProxy does not implement __enter__ and __exit__.
 %0A   
@@ -1234,21 +1234,26 @@
 or_none(
-engin
+connectabl
 e, state
@@ -1278,21 +1278,26 @@
 ecuting(
-engin
+connectabl
 e, state

Extend utils to accept connectable, not just Engine object