The error you're encountering:
there is no unique constraint matching given keys for referenced table "contained_items"
occurs when you attempt to create a foreign key reference to a column that does not have a UNIQUE or PRIMARY KEY constraint on the parent (referenced) table.
However, in your case, you're adding this line in your parsed_vehicles table:
FOREIGN KEY (id) REFERENCES contained_items(id) ON DELETE CASCADE
You're referencing the id of contained_items, which is its PRIMARY KEY, so it should work.
Let's troubleshoot step by step:
1. Check schema and naming
Did you create the contained_items table in the same schema as the parsed_vehicles table (parsed_advertisements_module)? From your code:
CREATE TABLE IF NOT EXISTS contained_items (
There's no schema specified here.
Meanwhile, you are creating parsed_vehicles in:
CREATE TABLE IF NOT EXISTS parsed_advertisements_module.parsed_vehicles (
So unless your search path is properly configured, the parsed_vehicles table may be attempting to reference contained_items in the parsed_advertisements_module schema (which doesn’t contain it), or in the public schema, if that's where contained_items resides.
✅ Solution 1: Specify schema names properly
Make sure the schema of contained_items is explicit.
For example, if it's in the parsed_advertisements_module schema, write:
CREATE TABLE IF NOT EXISTS parsed_advertisements_module.contained_items (
id VARCHAR(50) PRIMARY KEY,
source_id UUID NOT NULL REFERENCES parsers_management_module.parser_links(id) ON DELETE SET NULL,
date_created DATE NOT NULL,
is_new BOOLEAN NOT NULL,
UNIQUE (source_id)
);
Then the foreign key would work fine:
FOREIGN KEY (id) REFERENCES parsed_advertisements_module.contained_items(id) ON DELETE CASCADE
✅ Solution 2: Move contained_items to relevant schema
If appropriate, consider moving contained_items to the same schema (parsed_advertisements_module) for clearer referencing and consistency.
✅ Solution 3: Use a fully qualified reference in foreign key
Update your foreign key definition to fully specify the schema:
FOREIGN KEY (id) REFERENCES your_schema_name.contained_items(id) ON DELETE CASCADE
Replace your_schema_name with the actual schema where contained_items is defined (public, maybe?).
Final Notes
- Check that
contained_items.id really is a PRIMARY KEY — it must be uniquely constrained.
- Make sure all table references use the correct schema name.
- PostgreSQL enforces that referenced columns in foreign keys must be
UNIQUE or PRIMARY KEY.
If you share which schema contained_items is in, I can offer a more tailored fix.