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

Minor tweaks #80

Merged
merged 1 commit into from
Dec 25, 2018
Merged
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
29 changes: 14 additions & 15 deletions detective/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ def __init__(self, url, *, fetch_entities=True):

self.db_type = get_db_type(url)

def perform_query(self, query):
def perform_query(self, query, **params):
"""Perform a query, where query is a string."""
try:
return self.engine.execute(query)
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise
Expand Down Expand Up @@ -126,16 +126,14 @@ def fetch_data_by_list(self, entities: List[str], limit=50000):
"""
SELECT entity_id, state, last_changed
FROM states
WHERE entity_id in {}
WHERE entity_id in ({})
AND NOT state='unknown'
ORDER BY last_changed DESC
LIMIT {}
""".format(
tuple(entities), limit
)
LIMIT :limit
""".format(','.join("'{}'".format(ent) for ent in entities))
)

response = self.perform_query(query)
response = self.perform_query(query, limit=limit)
df = pd.DataFrame(response.fetchall())
df.columns = ["entity", "state", "last_changed"]
df = df.set_index("last_changed") # Set the index on datetime
Expand All @@ -154,24 +152,25 @@ def fetch_data_by_list(self, entities: List[str], limit=50000):

def fetch_all_data(self, limit=50000):
"""
Fetch data for all enetites.
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE NOT state='unknown'
WHERE
state NOT IN ('unknown', 'unavailable')
ORDER BY last_changed DESC
LIMIT {}
""".format(
limit
)
LIMIT :limit
"""
)

try:
print("Querying the database, this could take a while")
response = self.engine.execute(query)
response = self.perform_query(
query, limit=limit
)
master_df = pd.DataFrame(response.fetchall())
print("master_df created successfully.")
self._master_df = master_df.copy()
Expand Down