db.schema and 'sqlite-utils schema' command, closes #268

This commit is contained in:
Simon Willison 2021-06-11 13:51:49 -07:00
commit 0d2e4f49f3
6 changed files with 90 additions and 2 deletions

View file

@ -1348,6 +1348,23 @@ def indexes(
)
@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)
@cli.command()
@click.argument(
"path",

View file

@ -301,6 +301,18 @@ class Database:
"Returns {trigger_name: sql} dictionary"
return {trigger.name: trigger.sql for trigger in self.triggers}
@property
def schema(self):
sqls = []
for row in self.execute(
"select sql from sqlite_master where sql is not null"
).fetchall():
sql = row[0]
if not sql.strip().endswith(";"):
sql += ";"
sqls.append(sql)
return "\n".join(sqls)
@property
def journal_mode(self):
return self.execute("PRAGMA journal_mode;").fetchone()[0]