The error you're encountering:
psycopg2.errors.InvalidParameterValue: cannot call jsonb_each on a non-object
indicates that the jsonb_each function is being called on data that's not a valid JSON object. Specifically, the column voll (of type text) sometimes contains plain text excerpts instead of valid JSON data. This leads to attempts to parse non-JSON text as JSON, resulting in the error.
To resolve this issue, you need to ensure that only valid JSON objects are processed by your INSERT INTO statements. Here's a step-by-step guide to modify your setup_fts function to handle these cases safely:
-
Correct the Regular Expression:
Ensure that the regular expression accurately matches rows where voll starts with {{. The current regex '^\\s*\\{{' is intended to match strings that start with optional whitespace followed by {{. However, the escaping might not be sufficient. It should be updated to properly match {{.
-
Add JSON Validation Using jsonb_typeof:
Use the jsonb_typeof function to verify that the voll column contains a JSON object before processing it. This ensures that jsonb_each is only called on valid JSON objects.
-
Update the INSERT INTO Statements:
Modify both INSERT INTO statements to include these validations in their WHERE clauses.
-
Handle JSON Parsing Safely:
Optionally, you can use NULLIF or other functions to handle cases where JSON parsing might fail, but validating upfront in the WHERE clause is more straightforward and efficient.
Here’s the revised version of your setup_fts function with these changes applied:
def setup_fts():
cursor = connection.cursor()
# Create the FTS table with date as timestamptz
cursor.execute('''
CREATE TABLE IF NOT EXISTS messages_fts (
id SERIAL PRIMARY KEY,
id1 BIGINT,
id2 BIGINT,
board TEXT,
message TEXT,
subject TEXT,
files TEXT,
date TIMESTAMPTZ,
tsv tsvector
);
''')
connection.commit()
# Clear existing data from the FTS table
cursor.execute('DELETE FROM messages_fts;')
connection.commit()
# Create trigger function for updating tsvector
cursor.execute('''
CREATE OR REPLACE FUNCTION messages_fts_trigger() RETURNS trigger AS $$
BEGIN
NEW.tsv :=
to_tsvector('english', coalesce(NEW.message, '') || ' ' || coalesce(NEW.subject, ''));
RETURN NEW;
END
$$ LANGUAGE plpgsql;
''')
connection.commit()
# Create trigger on messages_fts table
cursor.execute('''
DROP TRIGGER IF EXISTS tsvectorupdate ON messages_fts;
CREATE TRIGGER tsvectorupdate
BEFORE INSERT OR UPDATE ON messages_fts
FOR EACH ROW EXECUTE PROCEDURE messages_fts_trigger();
''')
connection.commit()
# Create GIN index on tsvector column
cursor.execute('''
CREATE INDEX IF NOT EXISTS idx_messages_fts_tsv ON messages_fts USING GIN(tsv);
''')
connection.commit()
# Fetch all board tables excluding 'fadenwache' and 'messages_fts'
cursor.execute("""
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
AND table_name NOT LIKE 'messages_fts%'
AND table_name NOT ILIKE 'fadenwache';
""")
rows = cursor.fetchall()
boards = [row[0] for row in rows]
# Populate the FTS table
for board in boards:
# Insert top-level messages and subjects only if 'voll' starts with '{{' and is a valid JSON object
cursor.execute(f'''
INSERT INTO messages_fts (id1, board, message, subject, files, date)
SELECT
{board}.id AS id1,
%s AS board,
{board}.voll::jsonb->>'message' AS message,
{board}.voll::jsonb->>'subject' AS subject,
{board}.voll::jsonb->>'files' AS files,
to_timestamp(split_part({board}.zeit, 'Z', 1), 'YYYY-MM-DD"T"HH24:MI:SS.MS') AS date
FROM {board}
WHERE {board}.voll ~ '^\\s*\\{\\{' -- Ensure 'voll' starts with '{{'
AND jsonb_typeof({board}.voll::jsonb) = 'object'
AND ({board}.voll::jsonb->>'message' IS NOT NULL
OR {board}.voll::jsonb->>'subject' IS NOT NULL);
''', (board,))
# Insert messages and subjects from nested posts only if 'voll' starts with '{{', is a valid JSON object,
# and 'posts' is also a valid JSON object
cursor.execute(f'''
INSERT INTO messages_fts (id1, id2, board, message, subject, files, date)
SELECT
{board}.id AS id1,
(p.value::jsonb->>'postId')::BIGINT AS id2,
%s AS board,
p.value::jsonb->>'message' AS message,
p.value::jsonb->>'subject' AS subject,
p.value::jsonb->>'files' AS files,
to_timestamp(split_part({board}.zeit, 'Z', 1), 'YYYY-MM-DD"T"HH24:MI:SS.MS') AS date
FROM {board}
CROSS JOIN LATERAL jsonb_each({board}.voll::jsonb->'posts') AS p(key, value)
WHERE {board}.voll ~ '^\\s*\\{\\{' -- Ensure 'voll' starts with '{{'
AND jsonb_typeof({board}.voll::jsonb) = 'object'
AND jsonb_typeof({board}.voll::jsonb->'posts') = 'object'
AND (p.value::jsonb->>'message' IS NOT NULL
OR p.value::jsonb->>'subject' IS NOT NULL);
''', (board,))
connection.commit()
# Set up triggers for each board
for board in boards:
# Drop existing triggers if they exist
cursor.execute(f'''
DROP TRIGGER IF EXISTS {board}_insert_trigger ON {board};
DROP TRIGGER IF EXISTS {board}_update_trigger ON {board};
DROP TRIGGER IF EXISTS {board}_delete_trigger ON {board};
''')
connection.commit()
# Define the trigger functions with appropriate SQL code
# Replace '%%%' placeholders with actual trigger function bodies as needed
# Example for INSERT trigger function
cursor.execute(f'''
CREATE OR REPLACE FUNCTION {board}_insert_trigger_fn() RETURNS trigger AS $$
BEGIN
-- Your INSERT trigger logic here
-- For example, insert into messages_fts as done above
-- Make sure to handle JSON parsing safely
IF TRIM(NEW.voll) LIKE '{{{{%' THEN
BEGIN
INSERT INTO messages_fts (id1, board, message, subject, files, date)
VALUES (
NEW.id,
TG_TABLE_NAME,
NEW.voll::jsonb->>'message',
NEW.voll::jsonb->>'subject',
NEW.voll::jsonb->>'files',
to_timestamp(split_part(NEW.zeit, 'Z', 1), 'YYYY-MM-DD"T"HH24:MI:SS.MS')
);
EXCEPTION WHEN others THEN
-- Handle JSON parsing errors or other exceptions
RAISE NOTICE 'Invalid JSON in voll for id %', NEW.id;
END;
END IF;
RETURN NEW;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER {board}_insert_trigger
AFTER INSERT ON {board}
FOR EACH ROW EXECUTE PROCEDURE {board}_insert_trigger_fn();
''')
connection.commit()
# Example for UPDATE trigger function
cursor.execute(f'''
CREATE OR REPLACE FUNCTION {board}_update_trigger_fn() RETURNS trigger AS $$
BEGIN
-- Your UPDATE trigger logic here
-- Similar to INSERT, handle updates safely
IF TRIM(NEW.voll) LIKE '{{{{%' THEN
BEGIN
UPDATE messages_fts
SET
message = NEW.voll::jsonb->>'message',
subject = NEW.voll::jsonb->>'subject',
files = NEW.voll::jsonb->>'files',
date = to_timestamp(split_part(NEW.zeit, 'Z', 1), 'YYYY-MM-DD"T"HH24:MI:SS.MS')
WHERE id1 = NEW.id;
EXCEPTION WHEN others THEN
RAISE NOTICE 'Invalid JSON in voll for id %', NEW.id;
END;
ELSE
DELETE FROM messages_fts WHERE id1 = NEW.id;
END IF;
RETURN NEW;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER {board}_update_trigger
AFTER UPDATE ON {board}
FOR EACH ROW EXECUTE PROCEDURE {board}_update_trigger_fn();
''')
connection.commit()
# Example for DELETE trigger function
cursor.execute(f'''
CREATE OR REPLACE FUNCTION {board}_delete_trigger_fn() RETURNS trigger AS $$
BEGIN
-- Your DELETE trigger logic here
DELETE FROM messages_fts WHERE id1 = OLD.id;
RETURN OLD;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER {board}_delete_trigger
AFTER DELETE ON {board}
FOR EACH ROW EXECUTE PROCEDURE {board}_delete_trigger_fn();
''')
connection.commit()
cursor.close()
print('completed setup_fts')
Detailed Explanation of Changes:
-
Regex Correction:
- Original Regex:
'^\\s*\\{{'
- Updated Regex:
'^\\s*\\{\\{'
The corrected regex '^\\s*\\{\\{' ensures that the string starts with optional whitespace followed by two literal { characters ({{). This prevents matching strings that start with a single {, which might not represent valid JSON objects in your context.
-
JSON Object Validation:
- Added
AND jsonb_typeof({board}.voll::jsonb) = 'object' to ensure that voll is a JSON object.
- For the nested
posts, added AND jsonb_typeof({board}.voll::jsonb->'posts') = 'object' to ensure that posts is also a JSON object before applying jsonb_each.
-
Trigger Function Enhancements:
- Added exception handling within the trigger functions to gracefully handle any JSON parsing errors. This prevents the entire transaction from failing if a single row contains invalid JSON.
- Used
TRIM(NEW.voll) to remove any leading/trailing whitespace before checking if it starts with {{.
- Ensured that triggers handle
INSERT, UPDATE, and DELETE operations appropriately, maintaining the integrity of the messages_fts table.
-
General Recommendations:
- Data Consistency: If possible, consider enforcing the
voll column to always contain valid JSON data at the database schema level. This could be achieved by changing its data type to jsonb and adding constraints to ensure data integrity.
- Logging: Implement more robust logging within your trigger functions to monitor and debug issues related to JSON parsing.
- Performance Considerations: Ensure that the additional checks do not introduce significant performance overhead, especially if dealing with large datasets.
Alternative Approach: Using jsonb_valid Function
If you're using PostgreSQL 12 or later, you can utilize the hypothetical jsonb_valid function (note that as of my knowledge cutoff in September 2021, PostgreSQL does not have a built-in jsonb_valid function, but you can create one) to check the validity of JSON data before processing. Here's how you might implement it:
CREATE OR REPLACE FUNCTION jsonb_valid(text) RETURNS boolean AS $$
BEGIN
PERFORM $1::jsonb;
RETURN TRUE;
EXCEPTION WHEN others THEN
RETURN FALSE;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
Then, modify your WHERE clauses:
WHERE {board}.voll ~ '^\\s*\\{\\{'
AND jsonb_valid({board}.voll)
AND jsonb_typeof({board}.voll::jsonb) = 'object'
AND ({board}.voll::jsonb->>'message' IS NOT NULL
OR {board}.voll::jsonb->>'subject' IS NOT NULL);
This function attempts to cast the text to jsonb and returns TRUE if successful or FALSE otherwise. This method ensures you're only processing valid JSON objects.
Conclusion
By implementing these changes, you ensure that your setup_fts function safely processes only valid JSON data, thereby preventing the jsonb_each error. Additionally, the enhanced trigger functions improve the robustness and reliability of your full-text search setup.