Я смог написать функцию на plpgsql, но она возвращает None.
Вот весь код моего проекта.
Создание таблиц и функций в бд:
from psycopg2 import connect
with connect(host='localhost',
port=5432,
database='uNeuro',
user='postgres',
password='3680') as conn, conn.cursor() as cur:
cur.execute("SET TIMEZONE='Europe/Moscow'")
cur.execute("SET DateStyle='SQL, DMY'")
cur.execute("CREATE TABLE profile_table( "
"id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "
"firstname varchar(50) NOT NULL, "
"lastname varchar(50) NOT NULL, "
"patronymic varchar(50) NOT NULL, "
"gender boolean NOT NULL, "
"date_of_birth timestamp NOT NULL, "
"registration_date timestamp NOT NULL);")
cur.execute("CREATE TABLE visit_table( "
"id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "
"visit_time timestamp NOT NULL, "
"profile_id int references profile_table(id) NOT NULL, "
"point int NOT NULL);")
cur.execute("CREATE TABLE img_table( "
"id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "
"profile_id int references profile_table(id) NOT NULL, "
"img bytea, "
"encoding double precision[]);")
cur.execute("CREATE FUNCTION linalg(en1 double precision[], en2 double precision[]) RETURNS float8 AS $$"
"DECLARE"
" s float8 := 0;"
"BEGIN"
" FOR i IN 0..127 LOOP"
" s = s + abs(en1[i] - en2[i]);"
" END LOOP;"
" RETURN s;"
"END;"
"$$ LANGUAGE plpgsql;")
Файл postgre.py
import io
import random
import numpy as np
class Interface:
def __init__(self, cur):
self.cur = cur
def _img_to_byte_array(self, image):
imgByteArr = io.BytesIO()
image.save(imgByteArr, format=image.format)
imgByteArr = imgByteArr.getvalue()
return imgByteArr
def _cur_to_list(self):
res = list()
for row in self.cur:
res.append(row)
return res
def _datetime_to_string(self, date):
return str(date.year) + "-" + str(date.month) + "-" + str(date.day) + " "\
+ str(date.hour) + ":" + str(date.minute) + ":" + str(date.second)
def _make_random_encoding(self):
arr = np.array(range(128), float)
for i in range(128):
arr[i] = random.random()
return arr
def _encoding_to_string(self, encoding):
if (encoding.shape == (1, 128)):
encoding = encoding[0]
res = ' {'
for a in encoding:
res += str(a)
res += ', '
res = res[:res.rfind(',')] + ' } '
return res
def _test(self, en1, en2):
self.cur.execute("SELECT linalg(%(en1)s, %(en2)s);",
{"en1": self._encoding_to_string(en1),
"en2": self._encoding_to_string(en2)})
return self._cur_to_list()
def set_profile(self, lastname, firstname, gender, date_of_birth, patronymic="None"):
if (gender == "man"):
gender = "true"
else:
gender = "false"
self.cur.execute(
"INSERT INTO profile_table (firstname, lastname, patronymic, gender, date_of_birth, registration_date)"
"VALUES (%(firstname)s, %(lastname)s, %(patronymic)s, %(gender)s, %(date_of_birth)s, "
"%(registration_date)s);",
{"lastname": lastname,
"firstname": firstname,
"patronymic": patronymic,
"gender": gender,
"date_of_birth": self._datetime_to_string(date_of_birth),
"registration_date": "NOW()"
})
def set_visit(self, profile_id, point):
self.cur.execute("INSERT INTO visit_table (visit_time, profile_id, point) "
"VALUES (NOW(), %(profile_id)s, %(point)s);",
{"profile_id": profile_id,
"point": point})
def set_img(self, profile_id, img, encoding):
self.cur.execute("INSERT INTO img_table (profile_id, img, encoding) "
"VALUES (%(profile_id)s, %(img)s, %(encoding)s);",
{"profile_id": profile_id,
"img": self._img_to_byte_array(img),
"encoding": self._encoding_to_string(encoding)})
def get_profiles(self):
self.cur.execute("SELECT * FROM profile_table;")
return self._cur_to_list()
def get_visits(self):
self.cur.execute("SELECT * FROM visit_table;")
return self._cur_to_list()
Файл main.py
from postgre import Interface
from psycopg2 import connect
with connect(host='localhost',
port=5432,
database='uNeuro',
user='postgres',
password='3680') as conn, conn.cursor() as cur:
I = Interface(cur)
en1 = I._make_random_encoding()
en2 = I._make_random_encoding()
a = I._test(en1, en2)
print(a)
При исполнении main.py в консоль выводится [(None,)], что неправильно.