--not-null-default and not_null_default=, refs #24

This commit is contained in:
Simon Willison 2019-06-12 18:35:02 -07:00
commit 2fed87da6e
7 changed files with 87 additions and 16 deletions

View file

@ -169,12 +169,27 @@ def optimize(path, no_vacuum):
),
required=False,
)
@click.option("--fk", type=str, required=False)
@click.option("--fk-col", type=str, required=False)
def add_column(path, table, col_name, col_type, fk, fk_col):
@click.option(
"--fk", type=str, required=False, help="Table to reference as a foreign key"
)
@click.option(
"--fk-col",
type=str,
required=False,
help="Referenced column on that foreign key table - if omitted will automatically use the primary key",
)
@click.option(
"--not-null-default",
type=str,
required=False,
help="Add NOT NULL DEFAULT 'TEXT' constraint",
)
def add_column(path, table, col_name, col_type, fk, fk_col, not_null_default):
"Add a column to the specified table"
db = sqlite_utils.Database(path)
db[table].add_column(col_name, col_type, fk=fk, fk_col=fk_col)
db[table].add_column(
col_name, col_type, fk=fk, fk_col=fk_col, not_null_default=not_null_default
)
@cli.command(name="add-foreign-key")

View file

@ -292,7 +292,9 @@ class Table:
self.db.conn.execute(sql)
return self
def add_column(self, col_name, col_type=None, fk=None, fk_col=None):
def add_column(
self, col_name, col_type=None, fk=None, fk_col=None, not_null_default=None
):
fk_col_type = None
if fk is not None:
# fk must be a valid table
@ -313,10 +315,19 @@ class Table:
fk_col_type = "INTEGER"
if col_type is None:
col_type = str
sql = "ALTER TABLE [{table}] ADD COLUMN [{col_name}] {col_type};".format(
not_null_sql = None
if not_null_default is not None:
not_null_sql = "NOT NULL DEFAULT {}".format(
# Use SQLite itself to correctly escape this string:
self.db.conn.execute(
"SELECT quote(:default)", {"default": not_null_default}
).fetchone()[0]
)
sql = "ALTER TABLE [{table}] ADD COLUMN [{col_name}] {col_type}{not_null_default};".format(
table=self.name,
col_name=col_name,
col_type=fk_col_type or COLUMN_TYPE_MAPPING[col_type],
not_null_default=(" " + not_null_sql) if not_null_sql else "",
)
self.db.conn.execute(sql)
if fk is not None: