Skip to content

Commit 97491ca

Browse files
committed
export not override file
1 parent 5c08c38 commit 97491ca

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

aws_s3--1.0.0.sql

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,19 @@ AS $$
199199
module_cache[module_name] = _module
200200
return _module
201201

202+
def file_exists(bucket, file_path, s3_client):
203+
try:
204+
s3_client.head_object(Bucket=bucket, Key=file_path)
205+
return True
206+
except:
207+
return False
208+
209+
def get_unique_file_path(base_name, counter, extension):
210+
return f"{base_name}_part{counter}{extension}"
211+
202212
boto3 = cache_import('boto3')
203213
tempfile = cache_import('tempfile')
214+
re = cache_import("re")
204215

205216
plan = plpy.prepare("select name, current_setting('aws_s3.' || name, true) as value from (select unnest(array['access_key_id', 'secret_access_key', 'session_token', 'endpoint_url']) as name) a");
206217
default_aws_settings = {
@@ -222,6 +233,15 @@ AS $$
222233
**aws_settings
223234
)
224235

236+
# generate unique file path
237+
file_path_parts = re.match(r'^(.*?)(\.[^.]*$|$)', file_path)
238+
base_name = file_path_parts.group(1)
239+
extension = file_path_parts.group(2)
240+
counter = 0
241+
while file_exists(bucket, get_unique_file_path(base_name, counter, extension), s3):
242+
counter += 1
243+
unique_file_path = get_unique_file_path(base_name, counter, extension)
244+
225245
with tempfile.NamedTemporaryFile() as fd:
226246
plan = plpy.prepare(
227247
"COPY ({query}) TO '{filename}' {options}".format(
@@ -241,7 +261,7 @@ AS $$
241261
num_lines += buffer.count(b'\n')
242262
size += len(buffer)
243263
fd.seek(0)
244-
s3.upload_fileobj(fd, bucket, file_path)
264+
s3.upload_fileobj(fd, bucket, unique_file_path)
245265
if 'HEADER TRUE' in options.upper():
246266
num_lines -= 1
247267
yield (num_lines, 1, size)

0 commit comments

Comments
 (0)