Skip to content

Commit

Permalink
capitalize sql keywords
Browse files Browse the repository at this point in the history
  • Loading branch information
edisj committed Jul 4, 2024
1 parent 5e08698 commit 0a7936f
Show file tree
Hide file tree
Showing 2 changed files with 253 additions and 98 deletions.
232 changes: 182 additions & 50 deletions mdaadb/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
import sqlite3
import pandas as pd
from dataclasses import dataclass
from collections import namedtuple
from collections import namedtuple, UserDict
from typing import List, Iterable, Any

from query import Query


Expand All @@ -14,6 +15,11 @@ def _namedtuple_factory(cursor, row):
return Row(*row)


class Tables(UserDict):
def __init__(self, db, *args, **kwargs):
self.db = db


class Database:

def __init__(self, database):
Expand All @@ -35,49 +41,133 @@ def tables(self):
def _get_table_names(self) -> List[str]:
""""""
table_names = (
self.select("name")
.from_("sqlite_schema")
.where("type = 'table'")
self.SELECT("name")
.FROM("sqlite_schema")
.WHERE("type = 'table'")
.execute()
.fetchall()
)
return [name[0] for name in table_names]

@property
def schema(self) -> pd.DataFrame:
return Query(db=self).select("*").from_("sqlite_schema").to_df()

def select(self, *fields):
""""""
return Query(db=self).select(*fields)

def pragma(self, *fields):
""""""
return Query(db=self).pragma(*fields)

def insert_into(self, *tables):
""""""
return Query(db=self).insert_into(*tables)

def create_table(self, *fields):
""""""
return Query(db=self).create_table(*fields)
return (
Query(db=self)
.SELECT("*")
.FROM("sqlite_schema")
.to_df()
)

def insert_row_into_table(self, table, row) -> None:
""""""
if isinstance(table, str):
table = Table(table, self)
table.insert_row(row)

def insert_array_into_table(self, table, array) -> None:
""""""
if isinstance(table, str):
table = Table(table, self)
table.insert_array(array)

def CREATE_TABLE(self, *fields) -> Query:
""""""
return (
Query(db=self)
.CREATE_TABLE(*fields)
)

def DELETE(self, *fields) -> Query:
""""""
return (
Query(db=self)
.DELETE(*fields)
)

def FROM(self, *fields) -> Query:
""""""
return (
Query(db=self)
.FROM(*fields)
)

def INNER_JOIN(self, *fields) -> Query:
""""""
return (
Query(db=self)
.INNER_JOIN(*fields)
)

def INSERT(self, row) -> Query:
""""""
return (
Query(db=self)
.INSERT(row)
)

def INTO(self, table) -> Query:
""""""
return (
Query(db=self)
.INTO(table)
)

def LIMIT(self, limit) -> Query:
""""""
return (
Query(db=self)
.LIMIT(limit)
)

def ON(self, *fields) -> Query:
""""""
return (
Query(db=self)
.ON(*fields)
)

def ORDER_BY(self, *fields) -> Query:
""""""
return (
Query(db=self)
.ORDER_BY(*fields)
)

def PRAGMA(self, *fields) -> Query:
""""""
return (
Query(db=self)
.PRAGMA(*fields)
)

def SELECT(self, *fields) -> Query:
""""""
return (
Query(db=self)
.SELECT(*fields)
)

def VALUES(self, *values) -> Query:
""""""
return (
Query(db=self)
.VALUES(*values)
)

def WHERE(self, *fields) -> Query:
""""""
return (
Query(db=self)
.WHERE(*fields)
)

def __iter__(self):
return iter(self.tables)

def __contains__(self, table):
return table.database == self
return table.db == self



@dataclass
Expand All @@ -88,12 +178,23 @@ class Table:
@property
def schema(self) -> str:
""""""
return self.db.select("sql").from_("sqlite_schema").where(f"name = '{self.name}'").execute().fetchone()[0]
return (
self.db
.SELECT("sql")
.FROM("sqlite_schema")
.WHERE(f"name = '{self.name}'")
.execute()
.fetchone()[0]
)

@property
def info(self) -> pd.DataFrame:
""""""
return self.db.pragma(f"table_info('{self.name}')").to_df()
return (
self.db
.PRAGMA(f"table_info('{self.name}')")
.to_df()
)

def row(self, id:int) -> Row:
""""""
Expand Down Expand Up @@ -130,14 +231,19 @@ def columns(self) -> Iterable[Column]:
def _get_row_ids(self) -> List[int]:
"""Helper function that returns a list of integer indices
that correspond to the primary key of this table."""
row_ids = self.select(self.primary_key).execute().fetchall()
row_ids = (
self.SELECT(self.primary_key)
.execute()
.fetchall()
)
return [id[0] for id in row_ids]

def _get_column_names(self) -> List[str]:
"""Helper function that returns a list of column names for this table.."""
column_names = (
self.db.select("name")
.from_(f"pragma_table_info('simulations')")
self.db
.SELECT("name")
.FROM(f"pragma_table_info('simulations')")
.execute()
.fetchall()
)
Expand All @@ -147,44 +253,66 @@ def _get_column_names(self) -> List[str]:
def primary_key(self) -> str:
"""Returns the primary key of this table as a string."""
result = (
self.db.select("name")
.from_(f"pragma_table_info('{self.name}') as ti")
.where("ti.pk = 1")
self.db
.SELECT("name")
.FROM(f"pragma_table_info('{self.name}') as tblinfo")
.WHERE("tblinfo.pk = 1")
.execute()
.fetchall()
)
assert len(result[0]) == 1
return result[0][0]

def select(self, *columns) -> Query:
""""""
return self.db.select(*columns).from_(self.name)

def insert_row(self, row) -> None:
""""""
return self.db.insert_into(self.name).values(row).execute().commit()
return (
self.db
.INSERT("")
.INTO(self.name)
.VALUES(row)
.execute()
.commit()
)

def insert_array(self, array) -> None:
""""""
n_cols = self.n_cols
values = "(" + ", ".join(["?" for _ in range(n_cols)]) + ")"
return (
self.db
.insert_into(self.name)
.values(values)
.INSERT("")
.INTO(self.name)
.VALUES(values)
.executemany(array)
.commit()
)

def delete_row(self, row) -> None:
...
def DELETE(self, *rows) -> Query:
return (
self.db
.DELETE(*rows)
.FROM(self.name)
)

def delete_row_by_id(self, id) -> None:
...
def INSERT(self, *rows) -> Query:
""""""
return (
self.db
.INSERT(*rows)
.INTO(self.name)
)

def SELECT(self, *columns) -> Query:
"""Builds query with SELECT keyword"""
return (
self.db
.SELECT(*columns)
.FROM(self.name)
)

def to_sql(self) -> str:
"""Returns the sqlite query that generates this table."""
return self.select("*").to_sql()
return self.SELECT("*").to_sql()

def to_df(self) -> pd.DataFrame:
"""Returns a pandas DataFrame of this table."""
Expand Down Expand Up @@ -212,8 +340,8 @@ def data(self):
""""""
return (
self.table
.select("*")
.where(f"{self.table.primary_key}={self.id}")
.SELECT("*")
.WHERE(f"{self.table.primary_key}={self.id}")
.execute()
.fetchall()
)
Expand All @@ -222,8 +350,8 @@ def to_sql(self) -> str:
"""Returns the sqlite query that generates this row."""
return (
self.table
.select("*")
.where(f"{self.table.primary_key}={self.id}")
.SELECT("*")
.WHERE(f"{self.table.primary_key}={self.id}")
.to_sql()
)

Expand All @@ -247,9 +375,9 @@ def type_(self) -> str:
""""""
_type = (
Query(db=self.db)
.select("type")
.from_(f"pragma_table_info('{self.table.name}') as t_info")
.where(f"t_info.name='{self.name}'")
.SELECT("type")
.FROM(f"pragma_table_info('{self.table.name}') as t_info")
.WHERE(f"t_info.name='{self.name}'")
.execute()
.fetchall()
)
Expand All @@ -258,12 +386,16 @@ def type_(self) -> str:
@property
def data(self) -> List[Any]:
""""""
_data = self.table.select(self.name).execute().fetchall()
_data = self.table.SELECT(self.name).execute().fetchall()
return [data[0] for data in _data]

def to_sql(self) -> str:
""""""
return self.table.select(self.name).to_sql()
return (
self.table
.SELECT(self.name)
.to_sql()
)

def to_df(self) -> pd.DataFrame:
""""""
Expand Down
Loading

0 comments on commit 0a7936f

Please sign in to comment.