import sqlite3


def open_database(path):
    """Open SQLite database specified by path, configure connection and
    create tables if they don't exist.
    """
    db = sqlite3.connect(path, timeout = 600)
    # massively improves commit performance, introduces risk of corrupt
    # Database on machine/OS crash or power out. Application crashes still
    # don't corrupt database.
    db.execute('PRAGMA synchronous = OFF;')
    #db.set_trace_callback(print)

    db.execute("""CREATE TABLE IF NOT EXISTS kernels
            -- Contains a unique id for each kernel launch of an application run.
            -- 'tag' is the unique name of an application run.
            -- One use case is to encode application parameters with it, e.g.
            -- 'matmul-n-512' could be used as the tag for a matrix multiply with
            -- a problem size of 512.
            (id INTEGER PRIMARY KEY, tag TEXT, kernel TEXT, launch INTEGER,
             UNIQUE(id, tag, kernel, launch));""")
    db.execute("""CREATE TABLE IF NOT EXISTS ctas
            -- Contains non-overlapping semi-closed intervals of addresses accessed
            -- by a CTA during a kernel launch (identified by 'kernel').
            -- E.g. the record 10, 2,3,4, 0, 500,700 indicates that during kernel 10,
            -- the cta with index (2, 3, 4) read addresses 500 (inclusive) to
            -- 700 (exclusive), or {500 .. 699}.
            -- Kind: 0 = loads, 1 = stores, 2 = atomics
            (kernel INTEGER, x INTEGER, y INTEGER, z INTEGER, kind INTEGER,
             start INTEGER, stop INTEGER,
             FOREIGN KEY(kernel) REFERENCES kernels(id) ON DELETE CASCADE);""")
    return db