Implemented 'sqlite-utils upsert my.db tablename --pk=x'

This commit is contained in:
Simon Willison 2019-01-24 21:20:10 -08:00
commit b30f924c49
3 changed files with 55 additions and 3 deletions

View file

@ -68,8 +68,27 @@ def optimize(path, no_vacuum):
@click.argument("json_file", type=click.File(), required=True)
@click.option("--pk", help="Column to use as the primary key, e.g. id")
def insert(path, table, json_file, pk):
"Insert records from JSON file into the table, create table if it is missing"
db = sqlite_utils.Database(path)
docs = json.load(json_file)
if isinstance(docs, dict):
docs = [docs]
db[table].insert_all(docs, pk=pk)
@cli.command()
@click.argument(
"path",
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
required=True,
)
@click.argument("table")
@click.argument("json_file", type=click.File(), required=True)
@click.option("--pk", help="Column to use as the primary key, e.g. id")
def upsert(path, table, json_file, pk):
"Upsert records based on their primary key"
db = sqlite_utils.Database(path)
docs = json.load(json_file)
if isinstance(docs, dict):
docs = [docs]
db[table].upsert_all(docs, pk=pk)