Skip to content

Commit

Permalink
add execute-sql cli command
Browse files Browse the repository at this point in the history
  • Loading branch information
jkeifer committed Jun 22, 2023
1 parent bfcab7d commit 86eaf10
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- `list-fixtures` command ([#10])
- `load-fixture` command ([#10])
- `DB.execute_sql()` method for running arbitrary SQL against a database ([#10])
- `execute-sql` command ([#10])

### Changed

Expand Down
21 changes: 21 additions & 0 deletions src/dbami/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,26 @@ async def run() -> int:
return syncrun(run())


class ExecuteSql(DbamiCommand):
help: str = "Run SQL from stdin against the database"
name: str = "execute-sql"

def set_args(
self,
parser: argparse.ArgumentParser,
) -> None:
Arguments.project(parser)
Arguments.wait_timeout(parser)
Arguments.database(parser)

def __call__(self, args: argparse.Namespace) -> int:
async def run() -> int:
await args.db.execute_sql(sys.stdin.read(), database=args.database)
return 0

return syncrun(run())


class CLI(abc.ABC):
def __init__(
self,
Expand Down Expand Up @@ -604,6 +624,7 @@ class DbamiCLI(CLI):
Version(),
ListFixtures(),
LoadFixture(),
ExecuteSql(),
)
}

Expand Down
17 changes: 17 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,3 +476,20 @@ def test_load_fixtures_extra(tmp_db, project_dir, extra_fixtures):
print(out)
print(err)
assert rc == 0


def test_execute_sql(tmp_db, project):
stdin = io.StringIO()
stdin.write("create table a_table (id int primary key);")
stdin.seek(0)
rc, out, err = run_cli(
"execute-sql",
"--database",
tmp_db,
stdin=stdin,
)
print(out)
print(err)
assert rc == 0
syncrun(project.execute_sql("select * from a_table", database=tmp_db))
assert True

0 comments on commit 86eaf10

Please sign in to comment.