simonw / sqlite-utils-shell

Interactive shell for sqlite-utils
Apache License 2.0
8 stars 0 forks source link

Smarter transaction handling #2

Open simonw opened 1 year ago

simonw commented 1 year ago

The user should be able to begin, commit and rollback transactions.

If they don't explicitly do this then insert/etc will be committed automatically for them when they hit return.

simonw commented 1 year ago

Here's an initial prototype with transaction support, which I have not yet tested properly:

import click
import readline
import sqlite_utils
from sqlite_utils.utils import sqlite3
import tabulate

SQL_KEYWORDS = ['select ', 'from ', 'where ', 'insert ', 'update ', 'delete ', 'create ', 'drop ', 'begin ', 'commit ', 'rollback ']

def completer(text, state):
    options = [i for i in SQL_KEYWORDS if i.lower().startswith(text.lower())]
    if state < len(options):
        return options[state]
    else:
        return None

if 'libedit' in readline.__doc__:
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")
readline.set_completer(completer)

@sqlite_utils.hookimpl
def register_commands(cli):
    @cli.command()
    @click.argument("path", type=click.Path(dir_okay=False, readable=True))
    def shell(path):
        "Start an interactive SQL shell for this database"
        run_sql_shell(path)

def run_sql_shell(path):
    db = sqlite_utils.Database(path)
    cursor = db.conn.cursor()

    print("Enter your SQL commands to execute in sqlite3.")
    print("Type 'exit' to exit.")
    print("Type 'BEGIN' to start a transaction, and 'COMMIT' or 'ROLLBACK' to end it.")

    statement = ""
    in_transaction = False

    prompt = 'sqlite-utils> '

    while True:
        line = input(prompt)
        if line:
            readline.add_history(line)

        prompt = '         ...> '

        if line.lower() in ("exit", "quit"):
            break

        if line.lower() == "begin":
            in_transaction = True

        if in_transaction and line.lower() in ["commit", "rollback"]:
            in_transaction = False

        statement += ' ' + line

        if sqlite3.complete_statement(statement):
            try:
                statement = statement.strip()
                cursor.execute(statement)

                if statement.lower().startswith("select"):
                    print(cursor.fetchall())
                elif not in_transaction:
                    db.conn.commit()

            except sqlite3.Error as e:
                print("An error occurred:", e)
                if in_transaction:
                    print("Transaction has been rolled back.")
                    db.conn.rollback()

            finally:
                prompt = 'sqlite-utils> '

            statement = ""

    db.conn.close()