def __init__(self, name, raw_columns): self.name = name # Canonicalize the whitespace and then put back a little bit # of pretty-printing, so that '.schema' is readable. cnamelen = 0 columns1 = [] constraints = [] for c in raw_columns: c = sql_lexer.canonicalize(c) if sql_lexer.is_constraint(c): n = c.find("(") c = " " + c[:n] + " " + c[n:] constraints.append(c) else: n = c.find(" ") cnamelen = max(cnamelen, n) columns1.append(c) if not columns1: raise ValueError("table "+name+" has no columns") columns = [] for c in columns1: n = c.find(" ") columns.append(" {1:<{0}}{2}".format(cnamelen, c[:n], c[n:])) self.schema = "CREATE TABLE "+name+" (\n" self.schema += ",\n".join(columns) if constraints: self.schema += ",\n" self.schema += ",\n".join(constraints) self.schema += "\n)"
def ensure(self, db): """Ensure that an index with this specification exists in database DB.""" existing = db.execute("SELECT type, sql FROM sqlite_master " "WHERE name = ?", (self.name,)).fetchall() if not existing: db.executescript(self.schema) return if len(existing) > 1: raise RuntimeError("more than one item named '{}'?!" .format(self.name)) if existing[0] != "index": raise RuntimeError("existing item named '{}' is not an index" .format(self.name)) canon_schema = sql_lexer.canonicalize(self.schema) existing_schema = sql_lexer.canonicalize(existing[1]) if canon_schema != existing_schema: raise RuntimeError("schema mismatch for {}:\n" "want: {}\n" "got: {}" .format(canon_schema, existing_schema))