Currently as written I insert the payload as JSON into a single column. I want to break the k/v into columns in the predefined table. The value from MQTT is always byte object. ie...
b'{"name":"John","age":30,"city":"New York"}'
def insertIntoDatabase(message):
"""Inserts the mqtt data into the database"""
with connection.cursor() as cursor:
print("Inserting data...)
# MQTT message always a byte object
# message.payload contains message sent in this format
b'{"name":"John","age":30,"city":"New York"}'
# Covert to string ***WORKS***
test_json = message.payload.decode('utf8')
# Convert string to dict ***WORKS***
json_dict = json.loads(test_json)
print(json_dict)
# How do I deconstruct the dict into an sql insert????
# Inserts JSON into single column. Need one column per key
cursor.callproc('InsertIntoMQTTTable', [str(message.topic),
str(message.payload)[2:][:-1], int(message.qos)])
connection.commit()
SQL Routine - Called via callproc
create function insertintomqtttable(topic text, message text,
qos numeric) returns void
language plpgsql
as
$$
BEGIN
INSERT INTO mqtt (createdAt, topic, message, qos)
VALUES (CURRENT_TIMESTAMP, topic, message, qos);
END;
$$;
alter function insertintomqtttable(text, text, numeric) owner to don;
postgres Table Structure -
CREATE TABLE mqtt (
id SERIAL PRIMARY KEY,
createdAt TIMESTAMP NOT NULL,
topic TEXT NOT NULL,
message TEXT,
qos NUMERIC(1) NOT NULL
);