-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcopy_data.py
208 lines (167 loc) · 5.39 KB
/
copy_data.py
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import os
import argparse
from pathlib import Path
import dotenv
from sqlalchemy import text
from joblib import Parallel, delayed
from write_csv import weather_dataframe, write_csv
from timer import Timer
from utils import get_sqlalchemy_engine, get_psycopg3_connection, num_rows
dotenv.load_dotenv()
CSV_PATH = os.getenv("CSV_PATH")
def parse_args():
parser = argparse.ArgumentParser(
description="Load data into the weather table using COPY statements."
)
parser.add_argument(
"--method",
choices=["copy_csv", "psycopg3"],
help="How to copy data into the table.",
required=True
)
parser.add_argument(
"--table-type",
choices=["regular", "hyper"],
help="Create a regular PostgreSQL table or a TimescaleDB hypertable.",
required=True
)
parser.add_argument(
"--workers",
type=int,
help="Number of parallel workers.",
required=True
)
parser.add_argument(
"--hours",
type=int,
help="How many hours of ERA5 data to load. Each hour is roughly 1 million rows.",
required=True
)
parser.add_argument(
"--benchmarks-file",
type=str,
help="Filepath to output benchmarks to a CSV file.",
required=True
)
parser.add_argument(
"--parallel-benchmarks-file",
type=str,
help="Filepath to output parallel benchmarks to a CSV file."
)
return parser.parse_args()
def log_benchmark(args, hour, num_rows, full_timer, copy_timer):
filepath = args.benchmarks_file
# Create file and write CSV header
if not Path(filepath).exists():
with open(filepath, "a") as file:
file.write(
"method,table_type,workers,hour,num_rows,"
"seconds_full,rate_full,units_full,"
"seconds_copy,rate_copy,units_copy\n"
)
with open(filepath, "a") as file:
file.write(
f"{args.method},{args.table_type},{args.workers},{hour},{num_rows},"
f"{full_timer.interval},{full_timer.rate},{full_timer.units},"
f"{copy_timer.interval},{copy_timer.rate},{copy_timer.units}\n"
)
return
def log_parallel_benchmark(args, timer):
filepath = args.parallel_benchmarks_file
# Create file and write CSV header
if not Path(filepath).exists():
with open(filepath, "a") as file:
file.write(
"method,table_type,workers,hours,num_rows,"
"seconds,rate,units\n"
)
with open(filepath, "a") as file:
file.write(
f"{args.method},{args.table_type},{args.workers},{args.hours},{num_rows(args.hours)},"
f"{timer.interval},{timer.rate},{timer.units}\n"
)
return
def copy_data_using_psycopg3(n, args):
df = weather_dataframe(n)
full_timer = Timer(
f"COPYing data using psycopg3 cursor (counting overhead)",
n=df.shape[0],
units="inserts"
)
copy_timer = Timer(
f"COPYing data using psycopg3 cursor",
n=df.shape[0],
units="inserts"
)
with get_psycopg3_connection() as conn, conn.cursor() as cur, full_timer:
with cur.copy("""
copy weather (
time,
location_id,
latitude,
longitude,
temperature_2m,
zonal_wind_10m,
meridional_wind_10m,
total_cloud_cover,
total_precipitation,
snowfall
) from stdin
"""
) as copy, copy_timer:
for row in df.itertuples(index=False, name=None):
copy.write_row(row)
conn.commit()
log_benchmark(args, n, df.shape[0], full_timer, copy_timer)
return
def copy_data_using_csv(n, args):
df = weather_dataframe(n)
full_timer = Timer(
f"COPYing data using COPY (counting overhead)",
n=df.shape[0],
units="inserts"
)
copy_timer = Timer(
f"COPYing data using COPY",
n=df.shape[0],
units="inserts"
)
with full_timer:
csv_filepath = f"{CSV_PATH}/weather_hour{n}.csv"
write_csv(df, csv_filepath)
engine = get_sqlalchemy_engine()
with engine.connect() as conn, copy_timer:
conn.execute(text(f"""--sql
copy weather
from '{csv_filepath}'
delimiter ','
csv header;
"""))
conn.commit()
log_benchmark(args, n, df.shape[0], full_timer, copy_timer)
return
def main(args):
if args.method == "psycopg3":
copy_func = copy_data_using_psycopg3
elif args.method == "copy_csv":
copy_func = copy_data_using_csv
timer = Timer(
f"COPYing {args.hours} hours of data using {args.method} "
f"with {args.workers} workers",
n=num_rows(args.hours),
units="inserts"
)
with timer:
if args.workers == 1:
for n in range(args.hours):
copy_func(n, args)
else:
Parallel(n_jobs=args.workers)(
delayed(copy_func)(n, args)
for n in range(args.hours)
)
if args.parallel_benchmarks_file:
log_parallel_benchmark(args, timer)
return
if __name__ == "__main__":
main(parse_args())