Help for sql.execute

Project

sql

Function

execute

Sample CLI

gway sql execute

References

['info', 'resource']

Full Code

def execute(*sql, connection=None, script=None, into=None):
    """
    Execute SQL code or a script resource. If both are given, run script first.
    Returns dict with 'data' (rows, if any) and 'sql' (last statement run).
    """
    if not connection:
        connection = open_connection()

    if sql:
        sql = " ".join(sql)

    # TODO: Implement "into" as a function or the name of a function we can get with
    # gw[into] if so, for each row we execute in a select, we pass the extracted data as
    # kwargs by name to the function, then replace row with the result.

    cursor = connection.cursor()

    try:
        if script:
            script_text = gw.resource(script, text=True)
            cursor.executescript(script_text)
            gw.info(f"Executed script from: {script}")

        if sql:
            cursor.execute(sql)
            return cursor.fetchall() if cursor.description else None
    finally:
        cursor.close()