Загрузка данных


-- DROP FUNCTION utils.save_file_content_ex3(text, text, bytea);

CREATE OR REPLACE FUNCTION utils.save_file_content_ex3(base_path text, file_name text, data bytea)
RETURNS integer
LANGUAGE plpython3u
SECURITY DEFINER
AS $function$
import os
import re

if base_path == '':
    base_path_loc = plpy.execute("select value from robot.params p where p.name = 'root';", 1)
    if base_path_loc:
        base_path_loc = base_path_loc[0]["value"]
    else:
        return 4
else:
    base_path_loc = base_path
    
    if file_name.startswith('../') or file_name.endswith('..') or file_name.find('/../') > 0 or file_name.startswith('/'):
        return 0

full_path = os.path.join(base_path_loc, file_name)

if os.path.exists(full_path):
    try:
        os.remove(os.path.join(base_path_loc, file_name))
        #os.remove(os.path.join(base_path_loc, 'payment_register/951/4857_00951.dbf'))
        #os.rmdir(os.path.join(base_path_loc, 'payment_register/951'))
        #os.rmdir(os.path.join(base_path_loc, 'payment_register'))
        #files = os.listdir(os.path.join(base_path_loc, 'payment_register/951'))
        return 1
    except OSError as e:
        plpy.notice(f"Ошибка удаления: {e}")
        return -2

try:
    dir_path = os.path.dirname(full_path)
    if dir_path and not os.path.exists(dir_path):
        os.makedirs(dir_path, mode=0o777, exist_ok=True)
        os.chmod(dir_path, 0o777)
except OSError as e:
    plpy.error(f"Ошибка создания директорий: {e}")
    return 2

try:
    with open(full_path, 'wb') as binary_file:
        binary_file.write(data)
    os.chmod(full_path, 0o666)
except Exception as e:
    plpy.error(f"Ошибка операций с файлом: {e}")
    return 2

return 0
$function$
;