Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

correctly replace database name in query #7585

Merged
merged 2 commits into from
Dec 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog/7585.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Fixed an error when using the [SQLTrackerStore](tracker-stores.mdx#sqltrackerstore)
with a Postgres database and the parameter `login_db` specified.

The error was:

```bash
psycopg2.errors.SyntaxError: syntax error at end of input
rasa-production_1 | LINE 1: SELECT 1 FROM pg_catalog.pg_database WHERE datname = ?
```
35 changes: 23 additions & 12 deletions rasa/core/tracker_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -917,33 +917,44 @@ def get_db_url(
)

def _create_database_and_update_engine(self, db: Text, engine_url: "URL"):
"""Create databse `db` and update engine to reflect the updated `engine_url`."""

"""Creates database `db` and updates engine accordingly."""
from sqlalchemy import create_engine

if not self.engine.dialect.name == "postgresql":
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could also use https://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/database.html#create_database but that only supports mysql in addition which doesn't seem worth to include it as extra library (login_db doesn't make sense for sqlite)

rasa.shared.utils.io.raise_warning(
"The parameter 'login_db' can only be used with a postgres database.",
)
return

self._create_database(self.engine, db)
engine_url.database = db
self.engine = create_engine(engine_url)

@staticmethod
def _create_database(engine: "Engine", db: Text):
def _create_database(engine: "Engine", database_name: Text) -> None:
"""Create database `db` on `engine` if it does not exist."""

import psycopg2

conn = engine.connect()

cursor = conn.connection.cursor()
cursor.execute("COMMIT")
cursor.execute("SELECT 1 FROM pg_catalog.pg_database WHERE datname = ?", (db,))
exists = cursor.fetchone()
if not exists:
matching_rows = (
conn.execution_options(isolation_level="AUTOCOMMIT")
.execute(
sa.text(
"SELECT 1 FROM pg_catalog.pg_database "
"WHERE datname = :database_name"
),
database_name=database_name,
)
.rowcount
)

if not matching_rows:
try:
cursor.execute(f"CREATE DATABASE {db}")
conn.execute(f"CREATE DATABASE {database_name}")
except psycopg2.IntegrityError as e:
logger.error(f"Could not create database '{db}': {e}")
logger.error(f"Could not create database '{database_name}': {e}")

cursor.close()
conn.close()

@contextlib.contextmanager
Expand Down
5 changes: 5 additions & 0 deletions tests/core/test_tracker_stores.py
Original file line number Diff line number Diff line change
Expand Up @@ -891,3 +891,8 @@ def test_current_state_without_events(default_domain: Domain):

# `events` key should not be in there
assert state and "events" not in state


def test_login_db_with_no_postgresql(tmp_path: Path):
with pytest.warns(UserWarning):
SQLTrackerStore(db=str(tmp_path / "rasa.db"), login_db="other")