added a way to query entities

This commit is contained in:
Ari Sosnovsky committed 2021-11-10 11:17:43 -05:00
1 parent 759a002bce
commit c794661e05
18 files changed
+252 -172

No files matched your search

View File
Whitespace-only changes.
+33
View File
@@ -0,0 +1,33 @@
from sqlalchemy import create_engine, text
from urllib.parse import urlparse
class HassDatabase:
def __init__(self, db_url: str) -> None:
self.url = urlparse(db_url)
self.entities = None
try:
self.engine = create_engine(db_url)
self.connection = self.engine.connect()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
"The right dependency to connect to your database is "
"missing. Please make sure that it is installed."
) from exc
raise
@property
def db_type(self):
return self.url.scheme.split("+")[0]
def execute_sql(self, sql: str, **args):
resp = self.engine.execute(text(sql), **args)
return resp.fetchall()
def close(self):
self.connection.close()
def __del__(self):
self.close()
+59
View File
@@ -0,0 +1,59 @@
import json
from pydantic import BaseModel
from typing import Dict, Iterable, List, Optional, Union
from .connection import HassDatabase
class Entity(BaseModel):
entity_id: str
domain: str
attributes: dict
def search(
db_connection: HassDatabase,
search_text: str,
offset: int = 0,
limit: int = 100,
domain_filter: Optional[str] = None,
attributes_filter: Optional[Dict[str, Union[str, bool, int, float]]] = None,
) -> Iterable[Entity]:
filter_sql = f"entity_id like '%%{search_text}%%' AND old_state_id is NULL"
if domain_filter:
filter_sql += f" AND `domain` like '%%{domain_filter}%%'"
for entity_id, domain, attributes_str in db_connection.execute_sql(
f"""
SELECT
entity_id,
`domain` ,
`attributes`
FROM
states
WHERE
{filter_sql}
LIMIT {offset}, {limit}
"""
):
attributes: dict = json.loads(attributes_str)
if attributes_filter:
if not _compare_attr(attributes, attributes_filter):
continue
yield Entity(
entity_id=entity_id,
domain=domain,
attributes=attributes,
)
def _compare_attr(attributes: dict, attributes_filter: dict) -> bool:
for attr_name, attr_value in attributes_filter.items():
if attr_name not in attributes:
return False
if not type(attributes[attr_name]) == type(attr_value):
return False
if isinstance(attr_value, str):
if attributes[attr_name].find(attr_value) < 0:
return False
if attributes[attr_name] != attr_value:
return False
return True