-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdata_connections.py
More file actions
170 lines (147 loc) · 4.33 KB
/
data_connections.py
File metadata and controls
170 lines (147 loc) · 4.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""
Purpose of script: handles reading data in and writing data back out.
"""
import logging
import pathlib
from textwrap import dedent
import duckdb
import pandas as pd
DB_PATH = pathlib.Path(".db") # Default database path
logger = logging.getLogger(__name__)
def get_duckdb_connection(db_path: pathlib.Path = DB_PATH) -> duckdb.DuckDBPyConnection:
"""
Create a connection to the duckdb database at the given path.
Parameters
----------
db_path : pathlib.Path, optional
Path to the database file, by default DB_PATH
Returns
-------
duckdb.DuckDBPyConnection
Connection object.
"""
conn = duckdb.connect(str(db_path.resolve()))
conn.execute("SET GLOBAL pandas_analyze_sample=100000")
return conn
def create_table(
conn: duckdb.DuckDBPyConnection,
source: str,
table_name: str,
replace: bool = False,
exists_ok: bool = True,
) -> str:
"""
Create DuckDB table.
Parameters
----------
conn : duckdb.DuckDBPyConnection
Database connection.
source : str
Specifies the source in duckdb syntax. Can be a query string
or a file source (e.g. https://duckdb.org/docs/guides/import/csv_import).
table_name: str
Name of the table to be created.
replace : bool, optional
Should the table be replaced if it exists, by default False
exists_ok : bool, optional
Raise errors if the table already exists, by default True.
If replace=True then this parameter has no effect.
Returns
-------
str
Name of the table that was created.
"""
if replace:
create_expr = "CREATE OR REPLACE TABLE"
elif exists_ok:
create_expr = "CREATE TABLE IF NOT EXISTS"
else:
create_expr = "CREATE TABLE"
query = f"""
{create_expr} {table_name}
AS
SELECT * FROM {source}
"""
conn.sql(dedent(query))
return table_name
def create_table_from_csv(
conn: duckdb.DuckDBPyConnection,
csv_path: pathlib.Path,
replace: bool = False,
exists_ok: bool = True,
) -> str:
"""
Create DuckDB table using a csv source.
Parameters
----------
conn : duckdb.DuckDBPyConnection
Database connection.
csv_path : pathlib.Path
Path to the csv file.
replace : bool, optional
Should the table be replaced if it exists, by default False
exists_ok : bool, optional
Raise errors if the table already exists, by default True.
If replace=True then this parameter has no effect.
Returns
-------
str
Name of the table that was created.
"""
return create_table(
conn,
source=f"read_csv_auto('{csv_path.resolve()}')",
table_name=csv_path.stem,
replace=replace,
exists_ok=exists_ok,
)
def read_table_to_df(conn: duckdb.DuckDBPyConnection, table_name: str) -> pd.DataFrame:
"""
Read data from a duckdb table into a pandas dataframe.
Parameters
----------
conn : duckdb.DuckDBPyConnection
Database connection.
table_name : str
Name of table to query.
Returns
-------
pd.DataFrame
DataFrame from the query.
"""
query = f"SELECT * FROM {table_name}"
df = conn.sql(query).df()
return df
def write_df_to_table(
conn: duckdb.DuckDBPyConnection,
df: pd.DataFrame,
table_name: str,
replace: bool = False,
exists_ok: bool = True,
) -> str:
"""
Create DuckDB table using a pandas dataframe.
Parameters
----------
conn : duckdb.DuckDBPyConnection
Database connection.
df : pd.DataFrame
Pandas dataframe to create the table with.
table_name : str
Name of the table to create.
replace : bool, optional
Should the table be replaced if it exists, by default False
exists_ok : bool, optional
Raise errors if the table already exists, by default True.
If replace=True then this parameter has no effect.
Returns
-------
str
Name of the table that was created.
"""
# NOTE: duckdb can read 'df' based on referencing via a string, so it
# looks like df is unused from the arguments, but that is just the syntax
# highlighting not realsing!
return create_table(
conn, source="df", table_name=table_name, replace=replace, exists_ok=exists_ok
)