2020-07-26 17:48:36 -07:00
|
|
|
import base64
|
2018-07-28 06:43:18 -07:00
|
|
|
import click
|
2021-06-22 11:04:32 -07:00
|
|
|
from click_default_group import DefaultGroup # type: ignore
|
2020-07-27 00:08:57 -07:00
|
|
|
from datetime import datetime
|
|
|
|
|
import hashlib
|
|
|
|
|
import pathlib
|
2019-01-24 19:30:47 -08:00
|
|
|
import sqlite_utils
|
2021-05-28 22:01:38 -07:00
|
|
|
from sqlite_utils.db import AlterError, DescIndex
|
2020-12-12 23:20:11 -08:00
|
|
|
import textwrap
|
2021-02-14 10:33:26 -08:00
|
|
|
import io
|
2019-01-26 10:58:45 -08:00
|
|
|
import itertools
|
2019-01-29 07:37:01 -08:00
|
|
|
import json
|
2020-10-16 12:14:22 -07:00
|
|
|
import os
|
2019-01-25 07:50:20 -08:00
|
|
|
import sys
|
2019-02-22 17:40:21 -08:00
|
|
|
import csv as csv_std
|
2019-02-23 22:45:17 -08:00
|
|
|
import tabulate
|
2021-06-18 20:11:54 -07:00
|
|
|
from .utils import (
|
|
|
|
|
file_progress,
|
|
|
|
|
find_spatialite,
|
|
|
|
|
sqlite3,
|
|
|
|
|
decode_base64_values,
|
|
|
|
|
rows_from_file,
|
|
|
|
|
Format,
|
2021-06-18 21:18:58 -07:00
|
|
|
TypeTracker,
|
2021-06-18 20:11:54 -07:00
|
|
|
)
|
2018-07-28 06:43:18 -07:00
|
|
|
|
2021-06-18 07:55:26 -07:00
|
|
|
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
|
2021-06-18 07:56:59 -07:00
|
|
|
|
2020-05-02 20:55:40 -07:00
|
|
|
VALID_COLUMN_TYPES = ("INTEGER", "TEXT", "FLOAT", "BLOB")
|
|
|
|
|
|
2020-10-16 10:18:46 -07:00
|
|
|
UNICODE_ERROR = """
|
|
|
|
|
{}
|
|
|
|
|
|
|
|
|
|
The input you provided uses a character encoding other than utf-8.
|
|
|
|
|
|
|
|
|
|
You can fix this by passing the --encoding= option with the encoding of the file.
|
|
|
|
|
|
|
|
|
|
If you do not know the encoding, running 'file filename.csv' may tell you.
|
|
|
|
|
|
|
|
|
|
It's often worth trying: --encoding=latin-1
|
|
|
|
|
""".strip()
|
|
|
|
|
|
2018-07-28 06:43:18 -07:00
|
|
|
|
2021-02-14 13:33:21 -08:00
|
|
|
# Increase CSV field size limit to maximim possible
|
|
|
|
|
# https://stackoverflow.com/a/15063941
|
|
|
|
|
field_size_limit = sys.maxsize
|
|
|
|
|
|
|
|
|
|
while True:
|
|
|
|
|
try:
|
|
|
|
|
csv_std.field_size_limit(field_size_limit)
|
|
|
|
|
break
|
|
|
|
|
except OverflowError:
|
|
|
|
|
field_size_limit = int(field_size_limit / 10)
|
|
|
|
|
|
|
|
|
|
|
2019-02-22 18:12:53 -08:00
|
|
|
def output_options(fn):
|
|
|
|
|
for decorator in reversed(
|
|
|
|
|
(
|
|
|
|
|
click.option(
|
|
|
|
|
"--nl",
|
|
|
|
|
help="Output newline-delimited JSON",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
|
|
|
|
),
|
|
|
|
|
click.option(
|
|
|
|
|
"--arrays",
|
|
|
|
|
help="Output rows as arrays instead of objects",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
|
|
|
|
),
|
2020-11-03 14:01:14 -08:00
|
|
|
click.option("--csv", is_flag=True, help="Output CSV"),
|
2020-11-06 16:09:42 -08:00
|
|
|
click.option("--tsv", is_flag=True, help="Output TSV"),
|
2019-02-22 18:12:53 -08:00
|
|
|
click.option("--no-headers", is_flag=True, help="Omit CSV headers"),
|
2019-02-23 22:45:17 -08:00
|
|
|
click.option("-t", "--table", is_flag=True, help="Output as a table"),
|
|
|
|
|
click.option(
|
|
|
|
|
"--fmt",
|
|
|
|
|
help="Table format - one of {}".format(
|
|
|
|
|
", ".join(tabulate.tabulate_formats)
|
|
|
|
|
),
|
|
|
|
|
default="simple",
|
|
|
|
|
),
|
2019-05-24 17:56:44 -07:00
|
|
|
click.option(
|
|
|
|
|
"--json-cols",
|
|
|
|
|
help="Detect JSON cols and output them as JSON, not escaped strings",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
|
|
|
|
),
|
2019-02-22 18:12:53 -08:00
|
|
|
)
|
|
|
|
|
):
|
|
|
|
|
fn = decorator(fn)
|
|
|
|
|
return fn
|
|
|
|
|
|
|
|
|
|
|
2020-10-16 12:14:22 -07:00
|
|
|
def load_extension_option(fn):
|
|
|
|
|
return click.option(
|
|
|
|
|
"--load-extension",
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="SQLite extensions to load",
|
|
|
|
|
)(fn)
|
|
|
|
|
|
|
|
|
|
|
2021-06-18 07:55:26 -07:00
|
|
|
@click.group(
|
|
|
|
|
cls=DefaultGroup,
|
|
|
|
|
default="query",
|
|
|
|
|
default_if_no_args=True,
|
|
|
|
|
context_settings=CONTEXT_SETTINGS,
|
|
|
|
|
)
|
2019-01-24 19:30:47 -08:00
|
|
|
@click.version_option()
|
|
|
|
|
def cli():
|
|
|
|
|
"Commands for interacting with a SQLite database"
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
2019-01-24 19:57:04 -08:00
|
|
|
@click.option(
|
|
|
|
|
"--fts4", help="Just show FTS4 enabled tables", default=False, is_flag=True
|
|
|
|
|
)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--fts5", help="Just show FTS5 enabled tables", default=False, is_flag=True
|
|
|
|
|
)
|
2019-02-22 18:12:53 -08:00
|
|
|
@click.option(
|
|
|
|
|
"--counts", help="Include row counts per table", default=False, is_flag=True
|
|
|
|
|
)
|
|
|
|
|
@output_options
|
|
|
|
|
@click.option(
|
|
|
|
|
"--columns",
|
|
|
|
|
help="Include list of columns for each table",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
|
|
|
|
)
|
2020-05-01 10:09:36 -07:00
|
|
|
@click.option(
|
2020-08-28 15:30:57 -07:00
|
|
|
"--schema",
|
|
|
|
|
help="Include schema for each table",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
2020-05-01 10:09:36 -07:00
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
2019-05-24 17:56:44 -07:00
|
|
|
def tables(
|
|
|
|
|
path,
|
|
|
|
|
fts4,
|
|
|
|
|
fts5,
|
|
|
|
|
counts,
|
|
|
|
|
nl,
|
|
|
|
|
arrays,
|
|
|
|
|
csv,
|
2020-11-06 16:09:42 -08:00
|
|
|
tsv,
|
2019-05-24 17:56:44 -07:00
|
|
|
no_headers,
|
|
|
|
|
table,
|
|
|
|
|
fmt,
|
|
|
|
|
json_cols,
|
2020-05-01 10:09:36 -07:00
|
|
|
columns,
|
|
|
|
|
schema,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension,
|
2020-05-01 13:38:28 -07:00
|
|
|
views=False,
|
2019-05-24 17:56:44 -07:00
|
|
|
):
|
2019-01-24 19:30:47 -08:00
|
|
|
"""List the tables in the database"""
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-05-01 13:38:28 -07:00
|
|
|
headers = ["view" if views else "table"]
|
2019-02-22 18:12:53 -08:00
|
|
|
if counts:
|
|
|
|
|
headers.append("count")
|
|
|
|
|
if columns:
|
|
|
|
|
headers.append("columns")
|
2020-05-01 10:09:36 -07:00
|
|
|
if schema:
|
|
|
|
|
headers.append("schema")
|
2019-02-22 18:12:53 -08:00
|
|
|
|
|
|
|
|
def _iter():
|
2020-05-01 13:38:28 -07:00
|
|
|
if views:
|
|
|
|
|
items = db.view_names()
|
|
|
|
|
else:
|
|
|
|
|
items = db.table_names(fts4=fts4, fts5=fts5)
|
|
|
|
|
for name in items:
|
2019-02-22 18:12:53 -08:00
|
|
|
row = [name]
|
|
|
|
|
if counts:
|
|
|
|
|
row.append(db[name].count)
|
|
|
|
|
if columns:
|
|
|
|
|
cols = [c.name for c in db[name].columns]
|
|
|
|
|
if csv:
|
|
|
|
|
row.append("\n".join(cols))
|
|
|
|
|
else:
|
|
|
|
|
row.append(cols)
|
2020-05-01 10:09:36 -07:00
|
|
|
if schema:
|
|
|
|
|
row.append(db[name].schema)
|
2019-02-22 18:12:53 -08:00
|
|
|
yield row
|
|
|
|
|
|
2019-02-23 22:45:17 -08:00
|
|
|
if table:
|
|
|
|
|
print(tabulate.tabulate(_iter(), headers=headers, tablefmt=fmt))
|
2020-11-06 16:09:42 -08:00
|
|
|
elif csv or tsv:
|
|
|
|
|
writer = csv_std.writer(sys.stdout, dialect="excel-tab" if tsv else "excel")
|
2019-02-22 18:12:53 -08:00
|
|
|
if not no_headers:
|
|
|
|
|
writer.writerow(headers)
|
|
|
|
|
for row in _iter():
|
|
|
|
|
writer.writerow(row)
|
|
|
|
|
else:
|
2019-05-24 17:56:44 -07:00
|
|
|
for line in output_rows(_iter(), headers, nl, arrays, json_cols):
|
2019-02-22 18:12:53 -08:00
|
|
|
click.echo(line)
|
2019-01-24 19:39:04 -08:00
|
|
|
|
|
|
|
|
|
2020-05-01 13:38:28 -07:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--counts", help="Include row counts per view", default=False, is_flag=True
|
|
|
|
|
)
|
|
|
|
|
@output_options
|
|
|
|
|
@click.option(
|
|
|
|
|
"--columns",
|
|
|
|
|
help="Include list of columns for each view",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
|
|
|
|
)
|
|
|
|
|
@click.option(
|
2020-08-28 15:30:57 -07:00
|
|
|
"--schema",
|
|
|
|
|
help="Include schema for each view",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
2020-05-01 13:38:28 -07:00
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
2020-05-01 13:38:28 -07:00
|
|
|
def views(
|
2020-08-28 15:30:57 -07:00
|
|
|
path,
|
|
|
|
|
counts,
|
|
|
|
|
nl,
|
|
|
|
|
arrays,
|
|
|
|
|
csv,
|
2020-11-06 16:09:42 -08:00
|
|
|
tsv,
|
2020-08-28 15:30:57 -07:00
|
|
|
no_headers,
|
|
|
|
|
table,
|
|
|
|
|
fmt,
|
|
|
|
|
json_cols,
|
|
|
|
|
columns,
|
|
|
|
|
schema,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension,
|
2020-05-01 13:38:28 -07:00
|
|
|
):
|
|
|
|
|
"""List the views in the database"""
|
|
|
|
|
tables.callback(
|
|
|
|
|
path=path,
|
|
|
|
|
fts4=False,
|
|
|
|
|
fts5=False,
|
|
|
|
|
counts=counts,
|
|
|
|
|
nl=nl,
|
|
|
|
|
arrays=arrays,
|
|
|
|
|
csv=csv,
|
2020-11-06 16:09:42 -08:00
|
|
|
tsv=tsv,
|
2020-05-01 13:38:28 -07:00
|
|
|
no_headers=no_headers,
|
|
|
|
|
table=table,
|
|
|
|
|
fmt=fmt,
|
|
|
|
|
json_cols=json_cols,
|
|
|
|
|
columns=columns,
|
|
|
|
|
schema=schema,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension=load_extension,
|
2020-05-01 13:38:28 -07:00
|
|
|
views=True,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2019-01-24 20:35:51 -08:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
2020-09-08 15:34:55 -07:00
|
|
|
@click.argument("tables", nargs=-1)
|
2019-01-24 20:35:51 -08:00
|
|
|
@click.option("--no-vacuum", help="Don't run VACUUM", default=False, is_flag=True)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def optimize(path, tables, no_vacuum, load_extension):
|
2021-03-07 08:41:49 -08:00
|
|
|
"""Optimize all full-text search tables and then run VACUUM - should shrink the database file"""
|
2019-01-24 20:35:51 -08:00
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-09-08 15:34:55 -07:00
|
|
|
if not tables:
|
|
|
|
|
tables = db.table_names(fts4=True) + db.table_names(fts5=True)
|
2019-01-24 20:35:51 -08:00
|
|
|
with db.conn:
|
|
|
|
|
for table in tables:
|
|
|
|
|
db[table].optimize()
|
|
|
|
|
if not no_vacuum:
|
|
|
|
|
db.vacuum()
|
2019-01-24 21:06:41 -08:00
|
|
|
|
|
|
|
|
|
2020-09-08 16:16:03 -07:00
|
|
|
@cli.command(name="rebuild-fts")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("tables", nargs=-1)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def rebuild_fts(path, tables, load_extension):
|
2021-03-07 08:41:49 -08:00
|
|
|
"""Rebuild all or specific full-text search tables"""
|
2020-09-08 16:16:03 -07:00
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-09-08 16:16:03 -07:00
|
|
|
if not tables:
|
|
|
|
|
tables = db.table_names(fts4=True) + db.table_names(fts5=True)
|
|
|
|
|
with db.conn:
|
|
|
|
|
for table in tables:
|
|
|
|
|
db[table].rebuild_fts()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
def vacuum(path):
|
|
|
|
|
"""Run VACUUM against the database"""
|
|
|
|
|
sqlite_utils.Database(path).vacuum()
|
|
|
|
|
|
|
|
|
|
|
2021-06-16 16:51:48 -07:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@load_extension_option
|
|
|
|
|
def dump(path, load_extension):
|
|
|
|
|
"""Output a SQL dump of the schema and full contents of the database"""
|
|
|
|
|
db = sqlite_utils.Database(path)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
for line in db.conn.iterdump():
|
|
|
|
|
click.echo(line)
|
|
|
|
|
|
|
|
|
|
|
2019-02-24 12:04:33 -08:00
|
|
|
@cli.command(name="add-column")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.argument("col_name")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"col_type",
|
|
|
|
|
type=click.Choice(
|
|
|
|
|
["integer", "float", "blob", "text", "INTEGER", "FLOAT", "BLOB", "TEXT"]
|
|
|
|
|
),
|
2019-02-24 14:24:00 -08:00
|
|
|
required=False,
|
2019-02-24 12:04:33 -08:00
|
|
|
)
|
2019-06-12 18:35:02 -07:00
|
|
|
@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",
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def add_column(
|
|
|
|
|
path, table, col_name, col_type, fk, fk_col, not_null_default, load_extension
|
|
|
|
|
):
|
2019-02-24 12:04:33 -08:00
|
|
|
"Add a column to the specified table"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2019-06-12 18:35:02 -07:00
|
|
|
db[table].add_column(
|
|
|
|
|
col_name, col_type, fk=fk, fk_col=fk_col, not_null_default=not_null_default
|
|
|
|
|
)
|
2019-02-24 12:04:33 -08:00
|
|
|
|
|
|
|
|
|
2019-02-24 13:33:45 -08:00
|
|
|
@cli.command(name="add-foreign-key")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.argument("column")
|
2019-06-12 21:51:09 -07:00
|
|
|
@click.argument("other_table", required=False)
|
|
|
|
|
@click.argument("other_column", required=False)
|
2020-09-20 15:17:25 -07:00
|
|
|
@click.option(
|
|
|
|
|
"--ignore",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
help="If foreign key already exists, do nothing",
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def add_foreign_key(
|
|
|
|
|
path, table, column, other_table, other_column, ignore, load_extension
|
|
|
|
|
):
|
2019-02-24 13:33:45 -08:00
|
|
|
"""
|
|
|
|
|
Add a new foreign key constraint to an existing table. Example usage:
|
|
|
|
|
|
|
|
|
|
$ sqlite-utils add-foreign-key my.db books author_id authors id
|
|
|
|
|
|
|
|
|
|
WARNING: Could corrupt your database! Back up your database file first.
|
|
|
|
|
"""
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2019-02-24 13:33:45 -08:00
|
|
|
try:
|
2020-09-20 15:17:25 -07:00
|
|
|
db[table].add_foreign_key(column, other_table, other_column, ignore=ignore)
|
2019-02-24 13:33:45 -08:00
|
|
|
except AlterError as e:
|
|
|
|
|
raise click.ClickException(e)
|
|
|
|
|
|
|
|
|
|
|
2020-09-20 13:14:25 -07:00
|
|
|
@cli.command(name="add-foreign-keys")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("foreign_key", nargs=-1)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def add_foreign_keys(path, foreign_key, load_extension):
|
2020-09-20 13:14:25 -07:00
|
|
|
"""
|
|
|
|
|
Add multiple new foreign key constraints to a database. Example usage:
|
|
|
|
|
|
|
|
|
|
\b
|
|
|
|
|
sqlite-utils add-foreign-keys my.db \\
|
|
|
|
|
books author_id authors id \\
|
|
|
|
|
authors country_id countries id
|
|
|
|
|
"""
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-09-20 13:14:25 -07:00
|
|
|
if len(foreign_key) % 4 != 0:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
"Each foreign key requires four values: table, column, other_table, other_column"
|
|
|
|
|
)
|
|
|
|
|
tuples = []
|
|
|
|
|
for i in range(len(foreign_key) // 4):
|
|
|
|
|
tuples.append(tuple(foreign_key[i * 4 : (i * 4) + 4]))
|
|
|
|
|
try:
|
|
|
|
|
db.add_foreign_keys(tuples)
|
|
|
|
|
except AlterError as e:
|
|
|
|
|
raise click.ClickException(e)
|
|
|
|
|
|
|
|
|
|
|
2019-06-30 16:50:54 -07:00
|
|
|
@cli.command(name="index-foreign-keys")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def index_foreign_keys(path, load_extension):
|
2019-06-30 16:50:54 -07:00
|
|
|
"""
|
|
|
|
|
Ensure every foreign key column has an index on it.
|
|
|
|
|
"""
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2019-06-30 16:50:54 -07:00
|
|
|
db.index_foreign_keys()
|
|
|
|
|
|
|
|
|
|
|
2019-02-24 11:11:21 -08:00
|
|
|
@cli.command(name="create-index")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.argument("column", nargs=-1, required=True)
|
|
|
|
|
@click.option("--name", help="Explicit name for the new index")
|
|
|
|
|
@click.option("--unique", help="Make this a unique index", default=False, is_flag=True)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--if-not-exists",
|
|
|
|
|
help="Ignore if index already exists",
|
|
|
|
|
default=False,
|
|
|
|
|
is_flag=True,
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def create_index(path, table, column, name, unique, if_not_exists, load_extension):
|
2021-05-28 22:01:38 -07:00
|
|
|
"""
|
|
|
|
|
Add an index to the specified table covering the specified columns.
|
|
|
|
|
Use "sqlite-utils create-index mydb -- -column" to specify descending
|
|
|
|
|
order for a column.
|
|
|
|
|
"""
|
2019-02-24 11:11:21 -08:00
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2021-05-28 22:01:38 -07:00
|
|
|
# Treat -prefix as descending for columns
|
|
|
|
|
columns = []
|
|
|
|
|
for col in column:
|
|
|
|
|
if col.startswith("-"):
|
|
|
|
|
col = DescIndex(col[1:])
|
|
|
|
|
columns.append(col)
|
2019-02-24 11:11:21 -08:00
|
|
|
db[table].create_index(
|
2021-05-28 22:01:38 -07:00
|
|
|
columns, index_name=name, unique=unique, if_not_exists=if_not_exists
|
2019-02-24 11:11:21 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2019-02-07 21:18:24 -08:00
|
|
|
@cli.command(name="enable-fts")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.argument("column", nargs=-1, required=True)
|
2019-05-24 17:56:44 -07:00
|
|
|
@click.option("--fts4", help="Use FTS4", default=False, is_flag=True)
|
|
|
|
|
@click.option("--fts5", help="Use FTS5", default=False, is_flag=True)
|
2020-08-01 13:51:05 -07:00
|
|
|
@click.option("--tokenize", help="Tokenizer to use, e.g. porter")
|
2019-09-02 16:42:28 -07:00
|
|
|
@click.option(
|
|
|
|
|
"--create-triggers",
|
|
|
|
|
help="Create triggers to update the FTS tables when the parent table changes.",
|
|
|
|
|
default=False,
|
|
|
|
|
is_flag=True,
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def enable_fts(
|
|
|
|
|
path, table, column, fts4, fts5, tokenize, create_triggers, load_extension
|
|
|
|
|
):
|
2021-03-07 08:41:49 -08:00
|
|
|
"Enable full-text search for specific table and columns"
|
2019-02-07 21:18:24 -08:00
|
|
|
fts_version = "FTS5"
|
|
|
|
|
if fts4 and fts5:
|
|
|
|
|
click.echo("Can only use one of --fts4 or --fts5", err=True)
|
|
|
|
|
return
|
|
|
|
|
elif fts4:
|
|
|
|
|
fts_version = "FTS4"
|
|
|
|
|
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2019-09-02 16:42:28 -07:00
|
|
|
db[table].enable_fts(
|
2020-08-01 13:51:05 -07:00
|
|
|
column,
|
|
|
|
|
fts_version=fts_version,
|
|
|
|
|
tokenize=tokenize,
|
|
|
|
|
create_triggers=create_triggers,
|
2019-09-02 16:42:28 -07:00
|
|
|
)
|
2019-02-07 21:18:24 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command(name="populate-fts")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.argument("column", nargs=-1, required=True)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def populate_fts(path, table, column, load_extension):
|
2021-03-07 08:41:49 -08:00
|
|
|
"Re-populate full-text search for specific table and columns"
|
2019-02-07 21:18:24 -08:00
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2019-02-07 21:18:24 -08:00
|
|
|
db[table].populate_fts(column)
|
|
|
|
|
|
|
|
|
|
|
2020-02-26 20:40:35 -08:00
|
|
|
@cli.command(name="disable-fts")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def disable_fts(path, table, load_extension):
|
2021-03-07 08:41:49 -08:00
|
|
|
"Disable full-text search for specific table"
|
2020-02-26 20:40:35 -08:00
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-02-26 20:40:35 -08:00
|
|
|
db[table].disable_fts()
|
|
|
|
|
|
|
|
|
|
|
2020-08-10 11:59:21 -07:00
|
|
|
@cli.command(name="enable-wal")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
nargs=-1,
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def enable_wal(path, load_extension):
|
2020-08-10 11:59:21 -07:00
|
|
|
"Enable WAL for database files"
|
|
|
|
|
for path_ in path:
|
2020-10-16 12:14:22 -07:00
|
|
|
db = sqlite_utils.Database(path_)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
db.enable_wal()
|
2020-08-10 11:59:21 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command(name="disable-wal")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
nargs=-1,
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def disable_wal(path, load_extension):
|
2020-08-10 11:59:21 -07:00
|
|
|
"Disable WAL for database files"
|
|
|
|
|
for path_ in path:
|
2020-10-16 12:14:22 -07:00
|
|
|
db = sqlite_utils.Database(path_)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
db.disable_wal()
|
2020-08-10 11:59:21 -07:00
|
|
|
|
|
|
|
|
|
2021-01-02 20:26:39 -08:00
|
|
|
@cli.command(name="enable-counts")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("tables", nargs=-1)
|
|
|
|
|
@load_extension_option
|
|
|
|
|
def enable_counts(path, tables, load_extension):
|
|
|
|
|
"Configure triggers to update a _counts table with row counts"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
if not tables:
|
|
|
|
|
db.enable_counts()
|
|
|
|
|
else:
|
|
|
|
|
# Check all tables exist
|
|
|
|
|
bad_tables = [table for table in tables if not db[table].exists()]
|
|
|
|
|
if bad_tables:
|
|
|
|
|
raise click.ClickException("Invalid tables: {}".format(bad_tables))
|
|
|
|
|
for table in tables:
|
|
|
|
|
db[table].enable_counts()
|
|
|
|
|
|
|
|
|
|
|
2021-01-03 12:41:24 -08:00
|
|
|
@cli.command(name="reset-counts")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@load_extension_option
|
|
|
|
|
def reset_counts(path, load_extension):
|
|
|
|
|
"Reset calculated counts in the _counts table"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
db.reset_counts()
|
|
|
|
|
|
|
|
|
|
|
2019-02-06 21:50:25 -08:00
|
|
|
def insert_upsert_options(fn):
|
|
|
|
|
for decorator in reversed(
|
|
|
|
|
(
|
|
|
|
|
click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
),
|
|
|
|
|
click.argument("table"),
|
2020-10-16 10:18:46 -07:00
|
|
|
click.argument("json_file", type=click.File("rb"), required=True),
|
2019-07-14 21:28:51 -07:00
|
|
|
click.option(
|
|
|
|
|
"--pk", help="Columns to use as the primary key, e.g. id", multiple=True
|
|
|
|
|
),
|
2019-02-06 21:50:25 -08:00
|
|
|
click.option("--nl", is_flag=True, help="Expect newline-delimited JSON"),
|
2019-02-23 22:45:17 -08:00
|
|
|
click.option("-c", "--csv", is_flag=True, help="Expect CSV"),
|
2019-07-18 21:50:38 -07:00
|
|
|
click.option("--tsv", is_flag=True, help="Expect TSV"),
|
2021-02-05 17:34:47 -08:00
|
|
|
click.option("--delimiter", help="Delimiter to use for CSV files"),
|
|
|
|
|
click.option("--quotechar", help="Quote character to use for CSV/TSV"),
|
2021-02-14 11:23:12 -08:00
|
|
|
click.option(
|
|
|
|
|
"--sniff", is_flag=True, help="Detect delimiter and quote character"
|
|
|
|
|
),
|
2021-02-14 14:25:03 -08:00
|
|
|
click.option(
|
|
|
|
|
"--no-headers", is_flag=True, help="CSV file has no header row"
|
|
|
|
|
),
|
2019-02-06 21:50:25 -08:00
|
|
|
click.option(
|
|
|
|
|
"--batch-size", type=int, default=100, help="Commit every X records"
|
|
|
|
|
),
|
2019-05-24 17:41:04 -07:00
|
|
|
click.option(
|
|
|
|
|
"--alter",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
help="Alter existing table to add any missing columns",
|
|
|
|
|
),
|
2019-06-12 23:30:16 -07:00
|
|
|
click.option(
|
|
|
|
|
"--not-null",
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="Columns that should be created as NOT NULL",
|
|
|
|
|
),
|
|
|
|
|
click.option(
|
|
|
|
|
"--default",
|
|
|
|
|
multiple=True,
|
|
|
|
|
type=(str, str),
|
|
|
|
|
help="Default value that should be set for a column",
|
|
|
|
|
),
|
2020-10-16 10:18:46 -07:00
|
|
|
click.option(
|
|
|
|
|
"--encoding",
|
|
|
|
|
help="Character encoding for input, defaults to utf-8",
|
|
|
|
|
),
|
2021-06-18 21:18:58 -07:00
|
|
|
click.option(
|
|
|
|
|
"-d",
|
|
|
|
|
"--detect-types",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
envvar="SQLITE_UTILS_DETECT_TYPES",
|
|
|
|
|
help="Detect types for columns in CSV/TSV data",
|
|
|
|
|
),
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension_option,
|
2020-10-27 11:16:02 -07:00
|
|
|
click.option("--silent", is_flag=True, help="Do not show progress bar"),
|
2019-02-06 21:50:25 -08:00
|
|
|
)
|
|
|
|
|
):
|
|
|
|
|
fn = decorator(fn)
|
|
|
|
|
return fn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def insert_upsert_implementation(
|
2019-06-12 23:30:16 -07:00
|
|
|
path,
|
|
|
|
|
table,
|
|
|
|
|
json_file,
|
|
|
|
|
pk,
|
|
|
|
|
nl,
|
|
|
|
|
csv,
|
2019-07-18 21:50:38 -07:00
|
|
|
tsv,
|
2021-02-05 17:34:47 -08:00
|
|
|
delimiter,
|
|
|
|
|
quotechar,
|
2021-02-14 11:23:12 -08:00
|
|
|
sniff,
|
2021-02-14 14:25:03 -08:00
|
|
|
no_headers,
|
2019-06-12 23:30:16 -07:00
|
|
|
batch_size,
|
|
|
|
|
alter,
|
|
|
|
|
upsert,
|
|
|
|
|
ignore=False,
|
2019-12-27 09:15:31 +00:00
|
|
|
replace=False,
|
2020-07-06 14:18:23 -07:00
|
|
|
truncate=False,
|
2019-06-12 23:30:16 -07:00
|
|
|
not_null=None,
|
|
|
|
|
default=None,
|
2020-10-16 10:18:46 -07:00
|
|
|
encoding=None,
|
2021-06-18 21:18:58 -07:00
|
|
|
detect_types=None,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension=None,
|
2020-10-27 11:16:02 -07:00
|
|
|
silent=False,
|
2019-02-06 21:50:25 -08:00
|
|
|
):
|
2019-01-24 21:06:41 -08:00
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2021-02-14 14:25:03 -08:00
|
|
|
if delimiter or quotechar or sniff or no_headers:
|
2021-02-05 17:34:47 -08:00
|
|
|
csv = True
|
2019-07-18 21:50:38 -07:00
|
|
|
if (nl + csv + tsv) >= 2:
|
|
|
|
|
raise click.ClickException("Use just one of --nl, --csv or --tsv")
|
2020-10-16 10:18:46 -07:00
|
|
|
if encoding and not (csv or tsv):
|
|
|
|
|
raise click.ClickException("--encoding must be used with --csv or --tsv")
|
2021-06-18 08:00:52 -07:00
|
|
|
if pk and len(pk) == 1:
|
|
|
|
|
pk = pk[0]
|
2021-05-28 22:34:17 -07:00
|
|
|
encoding = encoding or "utf-8-sig"
|
2021-02-14 11:23:12 -08:00
|
|
|
buffered = io.BufferedReader(json_file, buffer_size=4096)
|
2021-02-15 11:18:28 -08:00
|
|
|
decoded = io.TextIOWrapper(buffered, encoding=encoding)
|
2021-06-18 21:18:58 -07:00
|
|
|
tracker = None
|
2019-07-18 21:50:38 -07:00
|
|
|
if csv or tsv:
|
2021-02-14 11:23:12 -08:00
|
|
|
if sniff:
|
|
|
|
|
# Read first 2048 bytes and use that to detect
|
|
|
|
|
first_bytes = buffered.peek(2048)
|
|
|
|
|
dialect = csv_std.Sniffer().sniff(first_bytes.decode(encoding, "ignore"))
|
|
|
|
|
else:
|
|
|
|
|
dialect = "excel-tab" if tsv else "excel"
|
|
|
|
|
with file_progress(decoded, silent=silent) as decoded:
|
2021-02-05 17:34:47 -08:00
|
|
|
csv_reader_args = {"dialect": dialect}
|
|
|
|
|
if delimiter:
|
|
|
|
|
csv_reader_args["delimiter"] = delimiter
|
|
|
|
|
if quotechar:
|
|
|
|
|
csv_reader_args["quotechar"] = quotechar
|
2021-02-14 11:23:12 -08:00
|
|
|
reader = csv_std.reader(decoded, **csv_reader_args)
|
2021-02-14 14:25:03 -08:00
|
|
|
first_row = next(reader)
|
|
|
|
|
if no_headers:
|
|
|
|
|
headers = ["untitled_{}".format(i + 1) for i in range(len(first_row))]
|
|
|
|
|
reader = itertools.chain([first_row], reader)
|
|
|
|
|
else:
|
|
|
|
|
headers = first_row
|
2020-10-27 11:16:02 -07:00
|
|
|
docs = (dict(zip(headers, row)) for row in reader)
|
2021-06-18 21:18:58 -07:00
|
|
|
if detect_types:
|
|
|
|
|
tracker = TypeTracker()
|
|
|
|
|
docs = tracker.wrap(docs)
|
2019-01-27 18:17:38 -08:00
|
|
|
else:
|
2021-01-03 10:42:17 -08:00
|
|
|
try:
|
|
|
|
|
if nl:
|
2021-02-14 11:23:12 -08:00
|
|
|
docs = (json.loads(line) for line in decoded)
|
2021-01-03 10:42:17 -08:00
|
|
|
else:
|
2021-02-14 11:23:12 -08:00
|
|
|
docs = json.load(decoded)
|
2021-01-03 10:42:17 -08:00
|
|
|
if isinstance(docs, dict):
|
|
|
|
|
docs = [docs]
|
|
|
|
|
except json.decoder.JSONDecodeError:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
"Invalid JSON - use --csv for CSV or --tsv for TSV files"
|
|
|
|
|
)
|
|
|
|
|
|
2020-07-06 14:18:23 -07:00
|
|
|
extra_kwargs = {"ignore": ignore, "replace": replace, "truncate": truncate}
|
2019-06-12 23:30:16 -07:00
|
|
|
if not_null:
|
|
|
|
|
extra_kwargs["not_null"] = set(not_null)
|
|
|
|
|
if default:
|
|
|
|
|
extra_kwargs["defaults"] = dict(default)
|
2019-12-29 21:03:43 -08:00
|
|
|
if upsert:
|
|
|
|
|
extra_kwargs["upsert"] = upsert
|
2020-07-26 20:59:15 -07:00
|
|
|
# Apply {"$base64": true, ...} decoding, if needed
|
|
|
|
|
docs = (decode_base64_values(doc) for doc in docs)
|
2021-05-18 20:26:13 -07:00
|
|
|
try:
|
|
|
|
|
db[table].insert_all(
|
|
|
|
|
docs, pk=pk, batch_size=batch_size, alter=alter, **extra_kwargs
|
|
|
|
|
)
|
|
|
|
|
except sqlite3.OperationalError as e:
|
|
|
|
|
if e.args and "has no column named" in e.args[0]:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
"{}\n\nTry using --alter to add additional columns".format(e.args[0])
|
|
|
|
|
)
|
|
|
|
|
raise
|
2021-06-18 21:18:58 -07:00
|
|
|
if tracker is not None:
|
|
|
|
|
db[table].transform(types=tracker.types)
|
2019-01-24 21:20:10 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
2019-02-06 21:50:25 -08:00
|
|
|
@insert_upsert_options
|
2019-05-28 21:15:57 -07:00
|
|
|
@click.option(
|
|
|
|
|
"--ignore", is_flag=True, default=False, help="Ignore records if pk already exists"
|
|
|
|
|
)
|
2019-12-27 09:15:31 +00:00
|
|
|
@click.option(
|
2019-12-27 09:30:29 +00:00
|
|
|
"--replace",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
|
|
|
|
help="Replace records if pk already exists",
|
2019-12-27 09:15:31 +00:00
|
|
|
)
|
2020-07-06 14:18:23 -07:00
|
|
|
@click.option(
|
|
|
|
|
"--truncate",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
default=False,
|
|
|
|
|
help="Truncate table before inserting records, if table already exists",
|
|
|
|
|
)
|
2019-06-12 23:30:16 -07:00
|
|
|
def insert(
|
2019-07-18 21:50:38 -07:00
|
|
|
path,
|
|
|
|
|
table,
|
|
|
|
|
json_file,
|
|
|
|
|
pk,
|
|
|
|
|
nl,
|
|
|
|
|
csv,
|
|
|
|
|
tsv,
|
2021-02-05 17:34:47 -08:00
|
|
|
delimiter,
|
|
|
|
|
quotechar,
|
2021-02-14 11:23:12 -08:00
|
|
|
sniff,
|
2021-02-14 14:25:03 -08:00
|
|
|
no_headers,
|
2019-07-18 21:50:38 -07:00
|
|
|
batch_size,
|
|
|
|
|
alter,
|
2020-10-16 10:18:46 -07:00
|
|
|
encoding,
|
2021-06-18 21:18:58 -07:00
|
|
|
detect_types,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension,
|
2020-10-27 11:16:02 -07:00
|
|
|
silent,
|
2019-07-18 21:50:38 -07:00
|
|
|
ignore,
|
2019-12-27 09:15:31 +00:00
|
|
|
replace,
|
2020-07-06 14:18:23 -07:00
|
|
|
truncate,
|
2019-07-18 21:50:38 -07:00
|
|
|
not_null,
|
|
|
|
|
default,
|
2019-06-12 23:30:16 -07:00
|
|
|
):
|
2019-02-06 21:50:25 -08:00
|
|
|
"""
|
|
|
|
|
Insert records from JSON file into a table, creating the table if it
|
|
|
|
|
does not already exist.
|
|
|
|
|
|
|
|
|
|
Input should be a JSON array of objects, unless --nl or --csv is used.
|
|
|
|
|
"""
|
2020-10-16 10:18:46 -07:00
|
|
|
try:
|
|
|
|
|
insert_upsert_implementation(
|
|
|
|
|
path,
|
|
|
|
|
table,
|
|
|
|
|
json_file,
|
|
|
|
|
pk,
|
|
|
|
|
nl,
|
|
|
|
|
csv,
|
|
|
|
|
tsv,
|
2021-02-05 17:34:47 -08:00
|
|
|
delimiter,
|
|
|
|
|
quotechar,
|
2021-02-14 11:23:12 -08:00
|
|
|
sniff,
|
2021-02-14 14:25:03 -08:00
|
|
|
no_headers,
|
2020-10-16 10:18:46 -07:00
|
|
|
batch_size,
|
|
|
|
|
alter=alter,
|
|
|
|
|
upsert=False,
|
|
|
|
|
ignore=ignore,
|
|
|
|
|
replace=replace,
|
|
|
|
|
truncate=truncate,
|
|
|
|
|
encoding=encoding,
|
2021-06-18 21:18:58 -07:00
|
|
|
detect_types=detect_types,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension=load_extension,
|
2020-10-27 11:16:02 -07:00
|
|
|
silent=silent,
|
2020-10-16 10:18:46 -07:00
|
|
|
not_null=not_null,
|
|
|
|
|
default=default,
|
|
|
|
|
)
|
|
|
|
|
except UnicodeDecodeError as ex:
|
|
|
|
|
raise click.ClickException(UNICODE_ERROR.format(ex))
|
2019-02-06 21:50:25 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
|
@insert_upsert_options
|
2019-07-18 21:50:38 -07:00
|
|
|
def upsert(
|
2020-10-16 10:18:46 -07:00
|
|
|
path,
|
|
|
|
|
table,
|
|
|
|
|
json_file,
|
|
|
|
|
pk,
|
|
|
|
|
nl,
|
|
|
|
|
csv,
|
|
|
|
|
tsv,
|
|
|
|
|
batch_size,
|
2021-02-05 17:34:47 -08:00
|
|
|
delimiter,
|
|
|
|
|
quotechar,
|
2021-02-14 11:23:12 -08:00
|
|
|
sniff,
|
2021-02-14 14:25:03 -08:00
|
|
|
no_headers,
|
2020-10-16 10:18:46 -07:00
|
|
|
alter,
|
|
|
|
|
not_null,
|
|
|
|
|
default,
|
|
|
|
|
encoding,
|
2021-06-18 21:18:58 -07:00
|
|
|
detect_types,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension,
|
2020-10-27 11:16:02 -07:00
|
|
|
silent,
|
2019-07-18 21:50:38 -07:00
|
|
|
):
|
2019-02-06 21:50:25 -08:00
|
|
|
"""
|
|
|
|
|
Upsert records based on their primary key. Works like 'insert' but if
|
|
|
|
|
an incoming record has a primary key that matches an existing record
|
2019-12-29 22:05:31 -08:00
|
|
|
the existing record will be updated.
|
2019-02-06 21:50:25 -08:00
|
|
|
"""
|
2020-10-16 10:18:46 -07:00
|
|
|
try:
|
|
|
|
|
insert_upsert_implementation(
|
|
|
|
|
path,
|
|
|
|
|
table,
|
|
|
|
|
json_file,
|
|
|
|
|
pk,
|
|
|
|
|
nl,
|
|
|
|
|
csv,
|
|
|
|
|
tsv,
|
2021-02-05 17:34:47 -08:00
|
|
|
delimiter,
|
|
|
|
|
quotechar,
|
2021-02-14 11:23:12 -08:00
|
|
|
sniff,
|
2021-02-14 14:25:03 -08:00
|
|
|
no_headers,
|
2020-10-16 10:18:46 -07:00
|
|
|
batch_size,
|
|
|
|
|
alter=alter,
|
|
|
|
|
upsert=True,
|
|
|
|
|
not_null=not_null,
|
|
|
|
|
default=default,
|
|
|
|
|
encoding=encoding,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension=load_extension,
|
2020-10-27 11:16:02 -07:00
|
|
|
silent=silent,
|
2020-10-16 10:18:46 -07:00
|
|
|
)
|
|
|
|
|
except UnicodeDecodeError as ex:
|
|
|
|
|
raise click.ClickException(UNICODE_ERROR.format(ex))
|
2019-01-25 07:50:20 -08:00
|
|
|
|
|
|
|
|
|
2020-05-02 20:55:40 -07:00
|
|
|
@cli.command(name="create-table")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.argument("columns", nargs=-1, required=True)
|
|
|
|
|
@click.option("--pk", help="Column to use as primary key")
|
2020-05-03 08:09:00 -07:00
|
|
|
@click.option(
|
2020-08-28 15:30:57 -07:00
|
|
|
"--not-null",
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="Columns that should be created as NOT NULL",
|
2020-05-03 08:09:00 -07:00
|
|
|
)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--default",
|
|
|
|
|
multiple=True,
|
|
|
|
|
type=(str, str),
|
|
|
|
|
help="Default value that should be set for a column",
|
|
|
|
|
)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--fk",
|
|
|
|
|
multiple=True,
|
|
|
|
|
type=(str, str, str),
|
|
|
|
|
help="Column, other table, other column to set as a foreign key",
|
|
|
|
|
)
|
2020-05-03 08:24:39 -07:00
|
|
|
@click.option(
|
2020-08-28 15:30:57 -07:00
|
|
|
"--ignore",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
help="If table already exists, do nothing",
|
2020-05-03 08:24:39 -07:00
|
|
|
)
|
|
|
|
|
@click.option(
|
2020-08-28 15:30:57 -07:00
|
|
|
"--replace",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
help="If table already exists, replace it",
|
2020-05-03 08:24:39 -07:00
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def create_table(
|
|
|
|
|
path, table, columns, pk, not_null, default, fk, ignore, replace, load_extension
|
|
|
|
|
):
|
2021-05-28 22:00:11 -07:00
|
|
|
"""
|
|
|
|
|
Add a table with the specified columns. Columns should be specified using
|
|
|
|
|
name, type pairs, for example:
|
|
|
|
|
|
|
|
|
|
\b
|
|
|
|
|
sqlite-utils create-table my.db people \\
|
|
|
|
|
id integer \\
|
|
|
|
|
name text \\
|
|
|
|
|
height float \\
|
|
|
|
|
photo blob --pk id
|
|
|
|
|
"""
|
2020-05-02 20:55:40 -07:00
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-05-02 20:55:40 -07:00
|
|
|
if len(columns) % 2 == 1:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
"columns must be an even number of 'name' 'type' pairs"
|
|
|
|
|
)
|
|
|
|
|
coltypes = {}
|
|
|
|
|
columns = list(columns)
|
|
|
|
|
while columns:
|
|
|
|
|
name = columns.pop(0)
|
|
|
|
|
ctype = columns.pop(0)
|
|
|
|
|
if ctype.upper() not in VALID_COLUMN_TYPES:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
"column types must be one of {}".format(VALID_COLUMN_TYPES)
|
|
|
|
|
)
|
|
|
|
|
coltypes[name] = ctype.upper()
|
2020-05-03 08:24:39 -07:00
|
|
|
# Does table already exist?
|
|
|
|
|
if table in db.table_names():
|
|
|
|
|
if ignore:
|
|
|
|
|
return
|
|
|
|
|
elif replace:
|
|
|
|
|
db[table].drop()
|
|
|
|
|
else:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
'Table "{}" already exists. Use --replace to delete and replace it.'.format(
|
|
|
|
|
table
|
|
|
|
|
)
|
|
|
|
|
)
|
2020-05-03 08:09:00 -07:00
|
|
|
db[table].create(
|
|
|
|
|
coltypes, pk=pk, not_null=not_null, defaults=dict(default), foreign_keys=fk
|
|
|
|
|
)
|
2020-05-02 20:55:40 -07:00
|
|
|
|
|
|
|
|
|
2020-05-10 17:44:21 -07:00
|
|
|
@cli.command(name="drop-table")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
2021-02-25 09:11:37 -08:00
|
|
|
@click.option("--ignore", is_flag=True)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
2021-02-25 09:11:37 -08:00
|
|
|
def drop_table(path, table, ignore, load_extension):
|
2020-05-10 17:44:21 -07:00
|
|
|
"Drop the specified table"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2021-02-25 09:11:37 -08:00
|
|
|
try:
|
|
|
|
|
db[table].drop(ignore=ignore)
|
|
|
|
|
except sqlite3.OperationalError:
|
2020-05-10 17:44:21 -07:00
|
|
|
raise click.ClickException('Table "{}" does not exist'.format(table))
|
|
|
|
|
|
|
|
|
|
|
2020-05-03 08:36:29 -07:00
|
|
|
@cli.command(name="create-view")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("view")
|
|
|
|
|
@click.argument("select")
|
|
|
|
|
@click.option(
|
2020-08-28 15:30:57 -07:00
|
|
|
"--ignore",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
help="If view already exists, do nothing",
|
2020-05-03 08:36:29 -07:00
|
|
|
)
|
|
|
|
|
@click.option(
|
2020-08-28 15:30:57 -07:00
|
|
|
"--replace",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
help="If view already exists, replace it",
|
2020-05-03 08:36:29 -07:00
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def create_view(path, view, select, ignore, replace, load_extension):
|
2020-05-03 08:36:29 -07:00
|
|
|
"Create a view for the provided SELECT query"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-05-03 08:36:29 -07:00
|
|
|
# Does view already exist?
|
|
|
|
|
if view in db.view_names():
|
|
|
|
|
if ignore:
|
|
|
|
|
return
|
|
|
|
|
elif replace:
|
|
|
|
|
db[view].drop()
|
|
|
|
|
else:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
'View "{}" already exists. Use --replace to delete and replace it.'.format(
|
|
|
|
|
view
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
db.create_view(view, select)
|
|
|
|
|
|
|
|
|
|
|
2020-05-10 17:44:21 -07:00
|
|
|
@cli.command(name="drop-view")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("view")
|
2021-02-25 09:11:37 -08:00
|
|
|
@click.option("--ignore", is_flag=True)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
2021-02-25 09:11:37 -08:00
|
|
|
def drop_view(path, view, ignore, load_extension):
|
2020-05-10 17:44:21 -07:00
|
|
|
"Drop the specified view"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2021-02-25 09:11:37 -08:00
|
|
|
try:
|
|
|
|
|
db[view].drop(ignore=ignore)
|
|
|
|
|
except sqlite3.OperationalError:
|
2020-05-10 17:44:21 -07:00
|
|
|
raise click.ClickException('View "{}" does not exist'.format(view))
|
|
|
|
|
|
|
|
|
|
|
2019-02-22 17:40:21 -08:00
|
|
|
@cli.command()
|
2019-01-25 18:06:29 -08:00
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("sql")
|
2021-02-18 21:08:39 -08:00
|
|
|
@click.option(
|
|
|
|
|
"--attach",
|
|
|
|
|
type=(str, click.Path(file_okay=True, dir_okay=False, allow_dash=False)),
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="Additional databases to attach - specify alias and filepath",
|
|
|
|
|
)
|
2019-02-22 17:40:21 -08:00
|
|
|
@output_options
|
2020-07-26 09:43:45 -07:00
|
|
|
@click.option("-r", "--raw", is_flag=True, help="Raw output, first column of first row")
|
2020-07-26 20:53:51 -07:00
|
|
|
@click.option(
|
|
|
|
|
"-p",
|
|
|
|
|
"--param",
|
|
|
|
|
multiple=True,
|
|
|
|
|
type=(str, str),
|
|
|
|
|
help="Named :parameters for SQL query",
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
2020-08-21 13:54:11 -07:00
|
|
|
def query(
|
|
|
|
|
path,
|
|
|
|
|
sql,
|
2021-02-18 21:08:39 -08:00
|
|
|
attach,
|
2020-08-21 13:54:11 -07:00
|
|
|
nl,
|
|
|
|
|
arrays,
|
|
|
|
|
csv,
|
2020-11-06 16:09:42 -08:00
|
|
|
tsv,
|
2020-08-21 13:54:11 -07:00
|
|
|
no_headers,
|
|
|
|
|
table,
|
|
|
|
|
fmt,
|
|
|
|
|
json_cols,
|
|
|
|
|
raw,
|
|
|
|
|
param,
|
|
|
|
|
load_extension,
|
|
|
|
|
):
|
2019-01-25 18:06:29 -08:00
|
|
|
"Execute SQL query and return the results as JSON"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2021-02-18 21:08:39 -08:00
|
|
|
for alias, attach_path in attach:
|
|
|
|
|
db.attach(alias, attach_path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-11-06 15:40:42 -08:00
|
|
|
db.register_fts4_bm25()
|
2021-06-18 08:00:52 -07:00
|
|
|
|
|
|
|
|
_execute_query(
|
|
|
|
|
db, sql, param, raw, table, csv, tsv, no_headers, fmt, nl, arrays, json_cols
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"paths",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=True),
|
|
|
|
|
required=False,
|
|
|
|
|
nargs=-1,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("sql")
|
|
|
|
|
@click.option(
|
|
|
|
|
"--attach",
|
|
|
|
|
type=(str, click.Path(file_okay=True, dir_okay=False, allow_dash=False)),
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="Additional databases to attach - specify alias and filepath",
|
|
|
|
|
)
|
|
|
|
|
@output_options
|
|
|
|
|
@click.option("-r", "--raw", is_flag=True, help="Raw output, first column of first row")
|
|
|
|
|
@click.option(
|
|
|
|
|
"-p",
|
|
|
|
|
"--param",
|
|
|
|
|
multiple=True,
|
|
|
|
|
type=(str, str),
|
|
|
|
|
help="Named :parameters for SQL query",
|
|
|
|
|
)
|
2021-06-18 08:29:41 -07:00
|
|
|
@click.option(
|
|
|
|
|
"--encoding",
|
|
|
|
|
help="Character encoding for CSV input, defaults to utf-8",
|
|
|
|
|
)
|
2021-06-18 21:37:56 -07:00
|
|
|
@click.option(
|
|
|
|
|
"-n",
|
|
|
|
|
"--no-detect-types",
|
|
|
|
|
is_flag=True,
|
|
|
|
|
help="Treat all CSV/TSV columns as TEXT",
|
|
|
|
|
)
|
2021-06-20 11:25:21 -07:00
|
|
|
@click.option("--schema", is_flag=True, help="Show SQL schema for in-memory database")
|
2021-06-18 08:00:52 -07:00
|
|
|
@click.option("--dump", is_flag=True, help="Dump SQL for in-memory database")
|
|
|
|
|
@click.option(
|
|
|
|
|
"--save",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
help="Save in-memory database to this file",
|
|
|
|
|
)
|
|
|
|
|
@load_extension_option
|
|
|
|
|
def memory(
|
|
|
|
|
paths,
|
|
|
|
|
sql,
|
|
|
|
|
attach,
|
|
|
|
|
nl,
|
|
|
|
|
arrays,
|
|
|
|
|
csv,
|
|
|
|
|
tsv,
|
|
|
|
|
no_headers,
|
|
|
|
|
table,
|
|
|
|
|
fmt,
|
|
|
|
|
json_cols,
|
|
|
|
|
raw,
|
|
|
|
|
param,
|
2021-06-18 08:29:41 -07:00
|
|
|
encoding,
|
2021-06-18 21:37:56 -07:00
|
|
|
no_detect_types,
|
2021-06-20 11:25:21 -07:00
|
|
|
schema,
|
2021-06-18 08:00:52 -07:00
|
|
|
dump,
|
|
|
|
|
save,
|
|
|
|
|
load_extension,
|
|
|
|
|
):
|
2021-06-18 20:20:56 -07:00
|
|
|
"""Execute SQL query against an in-memory database, optionally populated by imported data
|
|
|
|
|
|
|
|
|
|
To import data from CSV, TSV or JSON files pass them on the command-line:
|
|
|
|
|
|
|
|
|
|
\b
|
|
|
|
|
sqlite-utils memory one.csv two.json \\
|
|
|
|
|
"select * from one join two on one.two_id = two.id"
|
|
|
|
|
|
|
|
|
|
For data piped into the tool from standard input, use "-" or "stdin":
|
|
|
|
|
|
|
|
|
|
\b
|
|
|
|
|
cat animals.csv | sqlite-utils memory - \\
|
|
|
|
|
"select * from stdin where species = 'dog'"
|
|
|
|
|
|
|
|
|
|
The format of the data will be automatically detected. You can specify the format
|
|
|
|
|
explicitly using :json, :csv, :tsv or :nl (for newline-delimited JSON) - for example:
|
|
|
|
|
|
|
|
|
|
\b
|
|
|
|
|
cat animals.csv | sqlite-utils memory stdin:csv places.dat:nl \\
|
|
|
|
|
"select * from stdin where place_id in (select id from places)"
|
|
|
|
|
|
2021-06-28 09:35:01 -07:00
|
|
|
Use --schema to view the SQL schema of any imported files:
|
|
|
|
|
|
|
|
|
|
\b
|
|
|
|
|
sqlite-utils memory animals.csv --schema
|
2021-06-18 20:20:56 -07:00
|
|
|
"""
|
2021-06-18 08:00:52 -07:00
|
|
|
db = sqlite_utils.Database(memory=True)
|
|
|
|
|
# If --dump or --save used but no paths detected, assume SQL query is a path:
|
2021-06-20 11:25:21 -07:00
|
|
|
if (dump or save or schema) and not paths:
|
2021-06-18 08:00:52 -07:00
|
|
|
paths = [sql]
|
|
|
|
|
sql = None
|
|
|
|
|
for i, path in enumerate(paths):
|
2021-06-18 20:11:54 -07:00
|
|
|
# Path may have a :format suffix
|
|
|
|
|
if ":" in path and path.rsplit(":", 1)[-1].upper() in Format.__members__:
|
|
|
|
|
path, suffix = path.rsplit(":", 1)
|
|
|
|
|
format = Format[suffix.upper()]
|
|
|
|
|
else:
|
|
|
|
|
format = None
|
|
|
|
|
if path in ("-", "stdin"):
|
2021-06-18 08:29:41 -07:00
|
|
|
csv_fp = sys.stdin.buffer
|
2021-06-18 08:00:52 -07:00
|
|
|
csv_table = "stdin"
|
|
|
|
|
else:
|
|
|
|
|
csv_path = pathlib.Path(path)
|
|
|
|
|
csv_table = csv_path.stem
|
2021-06-18 08:36:09 -07:00
|
|
|
csv_fp = csv_path.open("rb")
|
2021-06-19 07:52:44 -07:00
|
|
|
rows, format_used = rows_from_file(csv_fp, format=format, encoding=encoding)
|
2021-06-18 21:37:56 -07:00
|
|
|
tracker = None
|
2021-06-19 07:52:44 -07:00
|
|
|
if format_used in (Format.CSV, Format.TSV) and not no_detect_types:
|
2021-06-18 21:37:56 -07:00
|
|
|
tracker = TypeTracker()
|
|
|
|
|
rows = tracker.wrap(rows)
|
2021-06-18 20:11:54 -07:00
|
|
|
db[csv_table].insert_all(rows, alter=True)
|
2021-06-18 21:37:56 -07:00
|
|
|
if tracker is not None:
|
|
|
|
|
db[csv_table].transform(types=tracker.types)
|
2021-06-18 08:00:52 -07:00
|
|
|
# Add convenient t / t1 / t2 views
|
|
|
|
|
view_names = ["t{}".format(i + 1)]
|
|
|
|
|
if i == 0:
|
|
|
|
|
view_names.append("t")
|
|
|
|
|
for view_name in view_names:
|
|
|
|
|
if not db[view_name].exists():
|
|
|
|
|
db.create_view(view_name, "select * from [{}]".format(csv_table))
|
|
|
|
|
|
|
|
|
|
if dump:
|
|
|
|
|
for line in db.conn.iterdump():
|
|
|
|
|
click.echo(line)
|
|
|
|
|
return
|
|
|
|
|
|
2021-06-20 11:25:21 -07:00
|
|
|
if schema:
|
|
|
|
|
click.echo(db.schema)
|
|
|
|
|
return
|
|
|
|
|
|
2021-06-18 08:00:52 -07:00
|
|
|
if save:
|
|
|
|
|
db2 = sqlite_utils.Database(save)
|
|
|
|
|
for line in db.conn.iterdump():
|
|
|
|
|
db2.execute(line)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
for alias, attach_path in attach:
|
|
|
|
|
db.attach(alias, attach_path)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
db.register_fts4_bm25()
|
|
|
|
|
|
|
|
|
|
_execute_query(
|
|
|
|
|
db, sql, param, raw, table, csv, tsv, no_headers, fmt, nl, arrays, json_cols
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _execute_query(
|
|
|
|
|
db, sql, param, raw, table, csv, tsv, no_headers, fmt, nl, arrays, json_cols
|
|
|
|
|
):
|
2020-07-07 22:14:04 -07:00
|
|
|
with db.conn:
|
2021-06-15 21:40:28 -07:00
|
|
|
try:
|
|
|
|
|
cursor = db.execute(sql, dict(param))
|
|
|
|
|
except sqlite3.OperationalError as e:
|
|
|
|
|
raise click.ClickException(str(e))
|
2020-07-07 22:14:04 -07:00
|
|
|
if cursor.description is None:
|
|
|
|
|
# This was an update/insert
|
|
|
|
|
headers = ["rows_affected"]
|
|
|
|
|
cursor = [[cursor.rowcount]]
|
|
|
|
|
else:
|
|
|
|
|
headers = [c[0] for c in cursor.description]
|
2020-07-26 09:43:45 -07:00
|
|
|
if raw:
|
|
|
|
|
data = cursor.fetchone()[0]
|
|
|
|
|
if isinstance(data, bytes):
|
|
|
|
|
sys.stdout.buffer.write(data)
|
|
|
|
|
else:
|
|
|
|
|
sys.stdout.write(str(data))
|
|
|
|
|
elif table:
|
2020-07-07 22:14:04 -07:00
|
|
|
print(tabulate.tabulate(list(cursor), headers=headers, tablefmt=fmt))
|
2020-11-06 16:09:42 -08:00
|
|
|
elif csv or tsv:
|
|
|
|
|
writer = csv_std.writer(sys.stdout, dialect="excel-tab" if tsv else "excel")
|
2020-07-07 22:14:04 -07:00
|
|
|
if not no_headers:
|
|
|
|
|
writer.writerow(headers)
|
|
|
|
|
for row in cursor:
|
|
|
|
|
writer.writerow(row)
|
|
|
|
|
else:
|
|
|
|
|
for line in output_rows(cursor, headers, nl, arrays, json_cols):
|
|
|
|
|
click.echo(line)
|
2019-02-22 17:40:21 -08:00
|
|
|
|
|
|
|
|
|
2020-11-03 14:01:14 -08:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("dbtable")
|
|
|
|
|
@click.argument("q")
|
|
|
|
|
@click.option("-o", "--order", type=str, help="Order by ('column' or 'column desc')")
|
|
|
|
|
@click.option("-c", "--column", type=str, multiple=True, help="Columns to return")
|
2020-11-03 14:46:18 -08:00
|
|
|
@click.option(
|
|
|
|
|
"--limit",
|
|
|
|
|
type=int,
|
2020-11-08 09:00:43 -08:00
|
|
|
help="Number of rows to return - defaults to everything",
|
2020-11-03 14:46:18 -08:00
|
|
|
)
|
2020-11-03 14:01:14 -08:00
|
|
|
@click.option(
|
|
|
|
|
"--sql", "show_sql", is_flag=True, help="Show SQL query that would be run"
|
|
|
|
|
)
|
|
|
|
|
@output_options
|
|
|
|
|
@load_extension_option
|
|
|
|
|
@click.pass_context
|
|
|
|
|
def search(
|
|
|
|
|
ctx,
|
|
|
|
|
path,
|
|
|
|
|
dbtable,
|
|
|
|
|
q,
|
|
|
|
|
order,
|
|
|
|
|
show_sql,
|
|
|
|
|
column,
|
2020-11-03 14:46:18 -08:00
|
|
|
limit,
|
2020-11-03 14:01:14 -08:00
|
|
|
nl,
|
|
|
|
|
arrays,
|
|
|
|
|
csv,
|
2020-11-06 16:09:42 -08:00
|
|
|
tsv,
|
2020-11-03 14:01:14 -08:00
|
|
|
no_headers,
|
|
|
|
|
table,
|
|
|
|
|
fmt,
|
|
|
|
|
json_cols,
|
|
|
|
|
load_extension,
|
|
|
|
|
):
|
|
|
|
|
"Execute a full-text search against this table"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
# Check table exists
|
|
|
|
|
table_obj = db[dbtable]
|
|
|
|
|
if not table_obj.exists():
|
|
|
|
|
raise click.ClickException("Table '{}' does not exist".format(dbtable))
|
2020-11-03 14:46:18 -08:00
|
|
|
if not table_obj.detect_fts():
|
2020-11-03 14:01:14 -08:00
|
|
|
raise click.ClickException(
|
|
|
|
|
"Table '{}' is not configured for full-text search".format(dbtable)
|
|
|
|
|
)
|
|
|
|
|
if column:
|
|
|
|
|
# Check they all exist
|
2020-11-03 14:46:18 -08:00
|
|
|
table_columns = table_obj.columns_dict
|
2020-11-03 14:01:14 -08:00
|
|
|
for c in column:
|
2020-11-03 14:46:18 -08:00
|
|
|
if c not in table_columns:
|
2020-11-03 14:01:14 -08:00
|
|
|
raise click.ClickException(
|
|
|
|
|
"Table '{}' has no column '{}".format(dbtable, c)
|
|
|
|
|
)
|
2020-11-06 16:43:33 -08:00
|
|
|
sql = table_obj.search_sql(columns=column, order_by=order, limit=limit)
|
2020-11-03 14:01:14 -08:00
|
|
|
if show_sql:
|
|
|
|
|
click.echo(sql)
|
|
|
|
|
return
|
|
|
|
|
ctx.invoke(
|
|
|
|
|
query,
|
|
|
|
|
path=path,
|
|
|
|
|
sql=sql,
|
|
|
|
|
nl=nl,
|
|
|
|
|
arrays=arrays,
|
|
|
|
|
csv=csv,
|
2020-11-06 16:09:42 -08:00
|
|
|
tsv=tsv,
|
2020-11-03 14:01:14 -08:00
|
|
|
no_headers=no_headers,
|
|
|
|
|
table=table,
|
|
|
|
|
fmt=fmt,
|
|
|
|
|
json_cols=json_cols,
|
2020-11-03 14:46:18 -08:00
|
|
|
param=[("query", q)],
|
2020-11-03 14:01:14 -08:00
|
|
|
load_extension=load_extension,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2019-02-22 17:52:17 -08:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
2019-02-23 22:45:17 -08:00
|
|
|
@click.argument("dbtable")
|
2020-11-06 16:28:41 -08:00
|
|
|
@click.option("-c", "--column", type=str, multiple=True, help="Columns to return")
|
2019-02-22 17:52:17 -08:00
|
|
|
@output_options
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
2019-02-22 17:52:17 -08:00
|
|
|
@click.pass_context
|
2020-10-16 12:14:22 -07:00
|
|
|
def rows(
|
|
|
|
|
ctx,
|
|
|
|
|
path,
|
|
|
|
|
dbtable,
|
2020-11-06 16:28:41 -08:00
|
|
|
column,
|
2020-10-16 12:14:22 -07:00
|
|
|
nl,
|
|
|
|
|
arrays,
|
|
|
|
|
csv,
|
2020-11-06 16:09:42 -08:00
|
|
|
tsv,
|
2020-10-16 12:14:22 -07:00
|
|
|
no_headers,
|
|
|
|
|
table,
|
|
|
|
|
fmt,
|
|
|
|
|
json_cols,
|
|
|
|
|
load_extension,
|
|
|
|
|
):
|
2019-02-22 17:52:17 -08:00
|
|
|
"Output all rows in the specified table"
|
2020-11-06 16:28:41 -08:00
|
|
|
columns = "*"
|
|
|
|
|
if column:
|
|
|
|
|
columns = ", ".join("[{}]".format(c) for c in column)
|
2019-02-22 17:52:17 -08:00
|
|
|
ctx.invoke(
|
|
|
|
|
query,
|
|
|
|
|
path=path,
|
2020-11-06 16:28:41 -08:00
|
|
|
sql="select {} from [{}]".format(columns, dbtable),
|
2019-02-22 17:52:17 -08:00
|
|
|
nl=nl,
|
|
|
|
|
arrays=arrays,
|
|
|
|
|
csv=csv,
|
2020-11-06 16:09:42 -08:00
|
|
|
tsv=tsv,
|
2019-02-22 17:52:17 -08:00
|
|
|
no_headers=no_headers,
|
2019-02-23 22:45:17 -08:00
|
|
|
table=table,
|
|
|
|
|
fmt=fmt,
|
2019-05-27 17:47:59 -07:00
|
|
|
json_cols=json_cols,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension=load_extension,
|
2019-02-22 17:52:17 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2021-01-02 19:03:15 -08:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("tables", nargs=-1)
|
|
|
|
|
@output_options
|
|
|
|
|
@load_extension_option
|
|
|
|
|
@click.pass_context
|
|
|
|
|
def triggers(
|
|
|
|
|
ctx,
|
|
|
|
|
path,
|
|
|
|
|
tables,
|
|
|
|
|
nl,
|
|
|
|
|
arrays,
|
|
|
|
|
csv,
|
|
|
|
|
tsv,
|
|
|
|
|
no_headers,
|
|
|
|
|
table,
|
|
|
|
|
fmt,
|
|
|
|
|
json_cols,
|
|
|
|
|
load_extension,
|
|
|
|
|
):
|
|
|
|
|
"Show triggers configured in this database"
|
|
|
|
|
sql = "select name, tbl_name as [table], sql from sqlite_master where type = 'trigger'"
|
|
|
|
|
if tables:
|
2021-01-02 20:15:04 -08:00
|
|
|
quote = sqlite_utils.Database(memory=True).quote
|
2021-01-02 19:03:15 -08:00
|
|
|
sql += " and [table] in ({})".format(
|
|
|
|
|
", ".join(quote(table) for table in tables)
|
|
|
|
|
)
|
|
|
|
|
ctx.invoke(
|
|
|
|
|
query,
|
|
|
|
|
path=path,
|
|
|
|
|
sql=sql,
|
|
|
|
|
nl=nl,
|
|
|
|
|
arrays=arrays,
|
|
|
|
|
csv=csv,
|
|
|
|
|
tsv=tsv,
|
|
|
|
|
no_headers=no_headers,
|
|
|
|
|
table=table,
|
|
|
|
|
fmt=fmt,
|
|
|
|
|
json_cols=json_cols,
|
|
|
|
|
load_extension=load_extension,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2021-06-02 21:26:46 -07:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("tables", nargs=-1)
|
|
|
|
|
@click.option("--aux", is_flag=True, help="Include auxiliary columns")
|
|
|
|
|
@output_options
|
|
|
|
|
@load_extension_option
|
|
|
|
|
@click.pass_context
|
|
|
|
|
def indexes(
|
|
|
|
|
ctx,
|
|
|
|
|
path,
|
|
|
|
|
tables,
|
|
|
|
|
aux,
|
|
|
|
|
nl,
|
|
|
|
|
arrays,
|
|
|
|
|
csv,
|
|
|
|
|
tsv,
|
|
|
|
|
no_headers,
|
|
|
|
|
table,
|
|
|
|
|
fmt,
|
|
|
|
|
json_cols,
|
|
|
|
|
load_extension,
|
|
|
|
|
):
|
|
|
|
|
"Show indexes for this database"
|
|
|
|
|
sql = """
|
|
|
|
|
select
|
|
|
|
|
sqlite_master.name as "table",
|
|
|
|
|
indexes.name as index_name,
|
|
|
|
|
xinfo.*
|
|
|
|
|
from sqlite_master
|
|
|
|
|
join pragma_index_list(sqlite_master.name) indexes
|
|
|
|
|
join pragma_index_xinfo(index_name) xinfo
|
|
|
|
|
where
|
|
|
|
|
sqlite_master.type = 'table'
|
|
|
|
|
"""
|
|
|
|
|
if tables:
|
|
|
|
|
quote = sqlite_utils.Database(memory=True).quote
|
|
|
|
|
sql += " and sqlite_master.name in ({})".format(
|
|
|
|
|
", ".join(quote(table) for table in tables)
|
|
|
|
|
)
|
|
|
|
|
if not aux:
|
|
|
|
|
sql += " and xinfo.key = 1"
|
|
|
|
|
ctx.invoke(
|
|
|
|
|
query,
|
|
|
|
|
path=path,
|
|
|
|
|
sql=sql,
|
|
|
|
|
nl=nl,
|
|
|
|
|
arrays=arrays,
|
|
|
|
|
csv=csv,
|
|
|
|
|
tsv=tsv,
|
|
|
|
|
no_headers=no_headers,
|
|
|
|
|
table=table,
|
|
|
|
|
fmt=fmt,
|
|
|
|
|
json_cols=json_cols,
|
|
|
|
|
load_extension=load_extension,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2021-06-11 13:51:49 -07:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@load_extension_option
|
|
|
|
|
def schema(
|
|
|
|
|
path,
|
|
|
|
|
load_extension,
|
|
|
|
|
):
|
|
|
|
|
"Show full schema for this database"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
click.echo(db.schema)
|
|
|
|
|
|
|
|
|
|
|
2020-09-22 00:46:32 -07:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.option(
|
|
|
|
|
"--type",
|
2021-05-28 20:55:46 -07:00
|
|
|
type=(
|
|
|
|
|
str,
|
|
|
|
|
click.Choice(["INTEGER", "TEXT", "FLOAT", "BLOB"], case_sensitive=False),
|
|
|
|
|
),
|
2020-09-22 00:46:32 -07:00
|
|
|
multiple=True,
|
2021-05-28 20:55:46 -07:00
|
|
|
help="Change column type to INTEGER, TEXT, FLOAT or BLOB",
|
2020-09-22 00:46:32 -07:00
|
|
|
)
|
|
|
|
|
@click.option("--drop", type=str, multiple=True, help="Drop this column")
|
|
|
|
|
@click.option(
|
|
|
|
|
"--rename", type=(str, str), multiple=True, help="Rename this column to X"
|
|
|
|
|
)
|
2020-09-24 09:11:53 -07:00
|
|
|
@click.option("-o", "--column-order", type=str, multiple=True, help="Reorder columns")
|
2020-09-22 00:46:32 -07:00
|
|
|
@click.option("--not-null", type=str, multiple=True, help="Set this column to NOT NULL")
|
|
|
|
|
@click.option(
|
|
|
|
|
"--not-null-false", type=str, multiple=True, help="Remove NOT NULL from this column"
|
|
|
|
|
)
|
|
|
|
|
@click.option("--pk", type=str, multiple=True, help="Make this column the primary key")
|
|
|
|
|
@click.option(
|
|
|
|
|
"--pk-none", is_flag=True, help="Remove primary key (convert to rowid table)"
|
|
|
|
|
)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--default",
|
|
|
|
|
type=(str, str),
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="Set default value for this column",
|
|
|
|
|
)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--default-none", type=str, multiple=True, help="Remove default from this column"
|
|
|
|
|
)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--drop-foreign-key",
|
2020-09-24 09:19:07 -07:00
|
|
|
type=str,
|
2020-09-22 00:46:32 -07:00
|
|
|
multiple=True,
|
|
|
|
|
help="Drop this foreign key constraint",
|
|
|
|
|
)
|
|
|
|
|
@click.option("--sql", is_flag=True, help="Output SQL without executing it")
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
2020-09-22 00:46:32 -07:00
|
|
|
def transform(
|
|
|
|
|
path,
|
|
|
|
|
table,
|
|
|
|
|
type,
|
|
|
|
|
drop,
|
|
|
|
|
rename,
|
2020-09-24 09:11:53 -07:00
|
|
|
column_order,
|
2020-09-22 00:46:32 -07:00
|
|
|
not_null,
|
|
|
|
|
not_null_false,
|
|
|
|
|
pk,
|
|
|
|
|
pk_none,
|
|
|
|
|
default,
|
|
|
|
|
default_none,
|
|
|
|
|
drop_foreign_key,
|
|
|
|
|
sql,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension,
|
2020-09-22 00:46:32 -07:00
|
|
|
):
|
2020-09-22 15:47:11 -07:00
|
|
|
"Transform a table beyond the capabilities of ALTER TABLE"
|
2020-09-22 00:46:32 -07:00
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-09-22 00:46:32 -07:00
|
|
|
types = {}
|
|
|
|
|
kwargs = {}
|
|
|
|
|
for column, ctype in type:
|
|
|
|
|
if ctype.upper() not in VALID_COLUMN_TYPES:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
"column types must be one of {}".format(VALID_COLUMN_TYPES)
|
|
|
|
|
)
|
|
|
|
|
types[column] = ctype.upper()
|
|
|
|
|
|
|
|
|
|
not_null_dict = {}
|
|
|
|
|
for column in not_null:
|
|
|
|
|
not_null_dict[column] = True
|
|
|
|
|
for column in not_null_false:
|
|
|
|
|
not_null_dict[column] = False
|
|
|
|
|
|
|
|
|
|
default_dict = {}
|
|
|
|
|
for column, value in default:
|
|
|
|
|
default_dict[column] = value
|
|
|
|
|
for column in default_none:
|
|
|
|
|
default_dict[column] = None
|
|
|
|
|
|
|
|
|
|
kwargs["types"] = types
|
|
|
|
|
kwargs["drop"] = set(drop)
|
|
|
|
|
kwargs["rename"] = dict(rename)
|
2020-09-24 09:11:53 -07:00
|
|
|
kwargs["column_order"] = column_order or None
|
2020-09-22 00:46:32 -07:00
|
|
|
kwargs["not_null"] = not_null_dict
|
|
|
|
|
if pk:
|
|
|
|
|
if len(pk) == 1:
|
|
|
|
|
kwargs["pk"] = pk[0]
|
|
|
|
|
else:
|
|
|
|
|
kwargs["pk"] = pk
|
|
|
|
|
elif pk_none:
|
|
|
|
|
kwargs["pk"] = None
|
|
|
|
|
kwargs["defaults"] = default_dict
|
|
|
|
|
if drop_foreign_key:
|
|
|
|
|
kwargs["drop_foreign_keys"] = drop_foreign_key
|
|
|
|
|
|
|
|
|
|
if sql:
|
|
|
|
|
for line in db[table].transform_sql(**kwargs):
|
|
|
|
|
click.echo(line)
|
|
|
|
|
else:
|
|
|
|
|
db[table].transform(**kwargs)
|
|
|
|
|
|
|
|
|
|
|
2020-09-22 16:37:39 -07:00
|
|
|
@cli.command()
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.argument("columns", nargs=-1, required=True)
|
|
|
|
|
@click.option(
|
|
|
|
|
"--table", "other_table", help="Name of the other table to extract columns to"
|
|
|
|
|
)
|
|
|
|
|
@click.option("--fk-column", help="Name of the foreign key column to add to the table")
|
|
|
|
|
@click.option(
|
|
|
|
|
"--rename",
|
|
|
|
|
type=(str, str),
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="Rename this column in extracted table",
|
|
|
|
|
)
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
2020-09-22 16:37:39 -07:00
|
|
|
def extract(
|
|
|
|
|
path,
|
|
|
|
|
table,
|
|
|
|
|
columns,
|
|
|
|
|
other_table,
|
|
|
|
|
fk_column,
|
|
|
|
|
rename,
|
2020-10-16 12:14:22 -07:00
|
|
|
load_extension,
|
2020-09-22 16:37:39 -07:00
|
|
|
):
|
|
|
|
|
"Extract one or more columns into a separate table"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-09-22 17:02:29 -07:00
|
|
|
kwargs = dict(
|
|
|
|
|
columns=columns,
|
|
|
|
|
table=other_table,
|
|
|
|
|
fk_column=fk_column,
|
|
|
|
|
rename=dict(rename),
|
2020-09-22 16:37:39 -07:00
|
|
|
)
|
2020-09-24 08:43:55 -07:00
|
|
|
db[table].extract(**kwargs)
|
2020-09-22 16:37:39 -07:00
|
|
|
|
|
|
|
|
|
2020-07-27 00:08:57 -07:00
|
|
|
@cli.command(name="insert-files")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("table")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"file_or_dir",
|
|
|
|
|
nargs=-1,
|
|
|
|
|
required=True,
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=True, allow_dash=True),
|
|
|
|
|
)
|
|
|
|
|
@click.option(
|
2020-08-28 15:30:57 -07:00
|
|
|
"-c",
|
|
|
|
|
"--column",
|
|
|
|
|
type=str,
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="Column definitions for the table",
|
2020-07-27 00:08:57 -07:00
|
|
|
)
|
|
|
|
|
@click.option("--pk", type=str, help="Column to use as primary key")
|
|
|
|
|
@click.option("--alter", is_flag=True, help="Alter table to add missing columns")
|
|
|
|
|
@click.option("--replace", is_flag=True, help="Replace files with matching primary key")
|
|
|
|
|
@click.option("--upsert", is_flag=True, help="Upsert files with matching primary key")
|
2020-07-29 20:08:12 -07:00
|
|
|
@click.option("--name", type=str, help="File name to use")
|
2020-10-16 12:14:22 -07:00
|
|
|
@load_extension_option
|
|
|
|
|
def insert_files(
|
|
|
|
|
path, table, file_or_dir, column, pk, alter, replace, upsert, name, load_extension
|
|
|
|
|
):
|
2020-07-27 00:08:57 -07:00
|
|
|
"""
|
|
|
|
|
Insert one or more files using BLOB columns in the specified table
|
|
|
|
|
|
|
|
|
|
Example usage:
|
|
|
|
|
|
|
|
|
|
\b
|
|
|
|
|
sqlite-utils insert-files pics.db images *.gif \\
|
|
|
|
|
-c name:name \\
|
|
|
|
|
-c content:content \\
|
|
|
|
|
-c content_hash:sha256 \\
|
|
|
|
|
-c created:ctime_iso \\
|
|
|
|
|
-c modified:mtime_iso \\
|
|
|
|
|
-c size:size \\
|
|
|
|
|
--pk name
|
|
|
|
|
"""
|
|
|
|
|
if not column:
|
|
|
|
|
column = ["path:path", "content:content", "size:size"]
|
|
|
|
|
if not pk:
|
|
|
|
|
pk = "path"
|
|
|
|
|
|
|
|
|
|
def yield_paths_and_relative_paths():
|
|
|
|
|
for f_or_d in file_or_dir:
|
|
|
|
|
path = pathlib.Path(f_or_d)
|
2020-07-29 20:08:12 -07:00
|
|
|
if f_or_d == "-":
|
|
|
|
|
yield "-", "-"
|
|
|
|
|
elif path.is_dir():
|
2020-07-27 00:08:57 -07:00
|
|
|
for subpath in path.rglob("*"):
|
|
|
|
|
if subpath.is_file():
|
|
|
|
|
yield subpath, subpath.relative_to(path)
|
|
|
|
|
elif path.is_file():
|
|
|
|
|
yield path, path
|
|
|
|
|
|
|
|
|
|
# Load all paths so we can show a progress bar
|
|
|
|
|
paths_and_relative_paths = list(yield_paths_and_relative_paths())
|
|
|
|
|
|
|
|
|
|
with click.progressbar(paths_and_relative_paths) as bar:
|
|
|
|
|
|
|
|
|
|
def to_insert():
|
|
|
|
|
for path, relative_path in bar:
|
|
|
|
|
row = {}
|
2020-07-29 20:08:12 -07:00
|
|
|
lookups = FILE_COLUMNS
|
|
|
|
|
if path == "-":
|
|
|
|
|
stdin_data = sys.stdin.buffer.read()
|
|
|
|
|
# We only support a subset of columns for this case
|
|
|
|
|
lookups = {
|
|
|
|
|
"name": lambda p: name or "-",
|
|
|
|
|
"path": lambda p: name or "-",
|
|
|
|
|
"content": lambda p: stdin_data,
|
|
|
|
|
"sha256": lambda p: hashlib.sha256(stdin_data).hexdigest(),
|
|
|
|
|
"md5": lambda p: hashlib.md5(stdin_data).hexdigest(),
|
|
|
|
|
"size": lambda p: len(stdin_data),
|
|
|
|
|
}
|
2020-07-27 00:08:57 -07:00
|
|
|
for coldef in column:
|
|
|
|
|
if ":" in coldef:
|
|
|
|
|
colname, coltype = coldef.rsplit(":", 1)
|
|
|
|
|
else:
|
|
|
|
|
colname, coltype = coldef, coldef
|
|
|
|
|
try:
|
2020-07-29 20:08:12 -07:00
|
|
|
value = lookups[coltype](path)
|
2020-07-27 00:08:57 -07:00
|
|
|
row[colname] = value
|
|
|
|
|
except KeyError:
|
|
|
|
|
raise click.ClickException(
|
|
|
|
|
"'{}' is not a valid column definition - options are {}".format(
|
2020-07-29 20:08:12 -07:00
|
|
|
coltype, ", ".join(lookups.keys())
|
2020-07-27 00:08:57 -07:00
|
|
|
)
|
|
|
|
|
)
|
2020-07-29 20:08:12 -07:00
|
|
|
# Special case for --name
|
|
|
|
|
if coltype == "name" and name:
|
|
|
|
|
row[colname] = name
|
2020-07-27 00:08:57 -07:00
|
|
|
yield row
|
|
|
|
|
|
|
|
|
|
db = sqlite_utils.Database(path)
|
2020-10-16 12:14:22 -07:00
|
|
|
_load_extensions(db, load_extension)
|
2020-07-27 00:08:57 -07:00
|
|
|
with db.conn:
|
|
|
|
|
db[table].insert_all(
|
|
|
|
|
to_insert(), pk=pk, alter=alter, replace=replace, upsert=upsert
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2020-12-12 23:20:11 -08:00
|
|
|
@cli.command(name="analyze-tables")
|
|
|
|
|
@click.argument(
|
|
|
|
|
"path",
|
|
|
|
|
type=click.Path(file_okay=True, dir_okay=False, allow_dash=False, exists=True),
|
|
|
|
|
required=True,
|
|
|
|
|
)
|
|
|
|
|
@click.argument("tables", nargs=-1)
|
|
|
|
|
@click.option(
|
|
|
|
|
"-c",
|
|
|
|
|
"--column",
|
|
|
|
|
"columns",
|
|
|
|
|
type=str,
|
|
|
|
|
multiple=True,
|
|
|
|
|
help="Specific columns to analyze",
|
|
|
|
|
)
|
|
|
|
|
@click.option("--save", is_flag=True, help="Save results to _analyze_tables table")
|
|
|
|
|
@load_extension_option
|
|
|
|
|
def analyze_tables(
|
|
|
|
|
path,
|
|
|
|
|
tables,
|
|
|
|
|
columns,
|
|
|
|
|
save,
|
|
|
|
|
load_extension,
|
|
|
|
|
):
|
|
|
|
|
"Analyze the columns in one or more tables"
|
|
|
|
|
db = sqlite_utils.Database(path)
|
|
|
|
|
_load_extensions(db, load_extension)
|
|
|
|
|
if not tables:
|
|
|
|
|
tables = db.table_names()
|
|
|
|
|
todo = []
|
|
|
|
|
table_counts = {}
|
|
|
|
|
for table in tables:
|
|
|
|
|
table_counts[table] = db[table].count
|
|
|
|
|
for column in db[table].columns:
|
|
|
|
|
if not columns or column.name in columns:
|
|
|
|
|
todo.append((table, column.name))
|
|
|
|
|
# Now we now how many we need to do
|
|
|
|
|
for i, (table, column) in enumerate(todo):
|
|
|
|
|
column_details = db[table].analyze_column(
|
|
|
|
|
column, total_rows=table_counts[table], value_truncate=80
|
|
|
|
|
)
|
|
|
|
|
if save:
|
|
|
|
|
db["_analyze_tables_"].insert(
|
|
|
|
|
column_details._asdict(), pk=("table", "column"), replace=True
|
|
|
|
|
)
|
|
|
|
|
most_common_rendered = _render_common(
|
|
|
|
|
"\n\n Most common:", column_details.most_common
|
|
|
|
|
)
|
|
|
|
|
least_common_rendered = _render_common(
|
|
|
|
|
"\n\n Least common:", column_details.least_common
|
|
|
|
|
)
|
|
|
|
|
details = (
|
|
|
|
|
(
|
|
|
|
|
textwrap.dedent(
|
|
|
|
|
"""
|
|
|
|
|
{table}.{column}: ({i}/{total})
|
|
|
|
|
|
|
|
|
|
Total rows: {total_rows}
|
|
|
|
|
Null rows: {num_null}
|
|
|
|
|
Blank rows: {num_blank}
|
|
|
|
|
|
|
|
|
|
Distinct values: {num_distinct}{most_common_rendered}{least_common_rendered}
|
|
|
|
|
"""
|
|
|
|
|
)
|
|
|
|
|
.strip()
|
|
|
|
|
.format(
|
|
|
|
|
i=i + 1,
|
|
|
|
|
total=len(todo),
|
|
|
|
|
most_common_rendered=most_common_rendered,
|
|
|
|
|
least_common_rendered=least_common_rendered,
|
|
|
|
|
**column_details._asdict()
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
+ "\n"
|
|
|
|
|
)
|
|
|
|
|
click.echo(details)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _render_common(title, values):
|
|
|
|
|
if values is None:
|
|
|
|
|
return ""
|
|
|
|
|
lines = [title]
|
|
|
|
|
for value, count in values:
|
|
|
|
|
lines.append(" {}: {}".format(count, value))
|
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
2020-07-27 00:08:57 -07:00
|
|
|
FILE_COLUMNS = {
|
|
|
|
|
"name": lambda p: p.name,
|
|
|
|
|
"path": lambda p: str(p),
|
|
|
|
|
"fullpath": lambda p: str(p.resolve()),
|
|
|
|
|
"sha256": lambda p: hashlib.sha256(p.resolve().read_bytes()).hexdigest(),
|
|
|
|
|
"md5": lambda p: hashlib.md5(p.resolve().read_bytes()).hexdigest(),
|
|
|
|
|
"mode": lambda p: p.stat().st_mode,
|
|
|
|
|
"content": lambda p: p.resolve().read_bytes(),
|
|
|
|
|
"mtime": lambda p: p.stat().st_mtime,
|
|
|
|
|
"ctime": lambda p: p.stat().st_ctime,
|
|
|
|
|
"mtime_int": lambda p: int(p.stat().st_mtime),
|
|
|
|
|
"ctime_int": lambda p: int(p.stat().st_ctime),
|
|
|
|
|
"mtime_iso": lambda p: datetime.utcfromtimestamp(p.stat().st_mtime).isoformat(),
|
|
|
|
|
"ctime_iso": lambda p: datetime.utcfromtimestamp(p.stat().st_ctime).isoformat(),
|
|
|
|
|
"size": lambda p: p.stat().st_size,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2019-05-24 17:56:44 -07:00
|
|
|
def output_rows(iterator, headers, nl, arrays, json_cols):
|
2019-01-25 18:06:29 -08:00
|
|
|
# We have to iterate two-at-a-time so we can know if we
|
|
|
|
|
# should output a trailing comma or if we have reached
|
|
|
|
|
# the last row.
|
2019-02-22 17:40:21 -08:00
|
|
|
current_iter, next_iter = itertools.tee(iterator, 2)
|
2019-01-26 10:58:45 -08:00
|
|
|
next(next_iter, None)
|
2019-01-25 18:06:29 -08:00
|
|
|
first = True
|
2019-01-26 10:58:45 -08:00
|
|
|
for row, next_row in itertools.zip_longest(current_iter, next_iter):
|
|
|
|
|
is_last = next_row is None
|
2019-01-25 18:06:29 -08:00
|
|
|
data = row
|
2019-05-24 17:56:44 -07:00
|
|
|
if json_cols:
|
|
|
|
|
# Any value that is a valid JSON string should be treated as JSON
|
|
|
|
|
data = [maybe_json(value) for value in data]
|
2019-01-25 18:06:29 -08:00
|
|
|
if not arrays:
|
2019-05-24 17:56:44 -07:00
|
|
|
data = dict(zip(headers, data))
|
2019-01-25 18:06:29 -08:00
|
|
|
line = "{firstchar}{serialized}{maybecomma}{lastchar}".format(
|
|
|
|
|
firstchar=("[" if first else " ") if not nl else "",
|
2020-07-26 17:48:36 -07:00
|
|
|
serialized=json.dumps(data, default=json_binary),
|
2019-01-25 18:06:29 -08:00
|
|
|
maybecomma="," if (not nl and not is_last) else "",
|
|
|
|
|
lastchar="]" if (is_last and not nl) else "",
|
|
|
|
|
)
|
2019-02-22 17:40:21 -08:00
|
|
|
yield line
|
2019-01-25 18:06:29 -08:00
|
|
|
first = False
|
2019-05-24 17:56:44 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def maybe_json(value):
|
|
|
|
|
if not isinstance(value, str):
|
|
|
|
|
return value
|
|
|
|
|
stripped = value.strip()
|
|
|
|
|
if not (stripped.startswith("{") or stripped.startswith("[")):
|
|
|
|
|
return value
|
|
|
|
|
try:
|
|
|
|
|
return json.loads(stripped)
|
|
|
|
|
except ValueError:
|
|
|
|
|
return value
|
2020-07-26 17:48:36 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def json_binary(value):
|
|
|
|
|
if isinstance(value, bytes):
|
|
|
|
|
return {"$base64": True, "encoded": base64.b64encode(value).decode("latin-1")}
|
|
|
|
|
else:
|
|
|
|
|
raise TypeError
|
2020-10-16 12:14:22 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _load_extensions(db, load_extension):
|
|
|
|
|
if load_extension:
|
|
|
|
|
db.conn.enable_load_extension(True)
|
|
|
|
|
for ext in load_extension:
|
|
|
|
|
if ext == "spatialite" and not os.path.exists(ext):
|
|
|
|
|
ext = find_spatialite()
|
|
|
|
|
db.conn.load_extension(ext)
|