I’m looking for assistance in changing a database function from PL/Python to plain SQL because I’d like to use it with Amazon RDS where I can’t install custom languages.
Here’s the Python function I currently have that converts byte values into a human-friendly format:
CREATE OR REPLACE FUNCTION format_byte_size(bytes_value bigint DEFAULT 0)
RETURNS text AS
$$
import math
if bytes_value > 0:
power = math.floor(math.log(bytes_value) / math.log(1024))
size = bytes_value / pow(1024, power)
size = round(size * 2) / 2
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
return "%.2f %s" % (size, units[int(power)])
else:
return "0 GB"
$$
LANGUAGE plpythonu;
This function gives me outputs like:
format_byte_size(2847293847593)
results in2.50 TB
format_byte_size(8473625891)
results in7.50 GB
The function effectively calculates the correct unit and rounds to the nearest half. However, I need guidance on replicating the logarithmic calculations and array handling in pure PostgreSQL SQL.
Additionally, could someone explain what the SECURITY INVOKER clause signifies in function definitions?