Me encontré con algunos problemas al modelar un esquema eléctrico en SQL. La estructura que me gustaría capturar es
part ←────────── pin
↑ ↑
part_inst ←───── pin_inst
donde "inst" es la abreviatura de "instancia".
Por ejemplo, podría tener como partamplificador operacional pinLM358 con s 1OUT, 1IN-, 1IN +, GND, 2IN +, 2IN-, 2OUT y V CC . Entonces podría colocar esta parte en un esquema, creando ay part_inst8
pin_insts.
Ignorando los campos de datos, mi intento inicial de un esquema fue
create table parts (
part_id bigserial primary key
);
create table pins (
pin_id bigserial primary key,
part_id bigint not null references parts
);
create table part_insts (
part_inst_id bigserial primary key,
part_id bigint not null references parts
);
create table pin_insts (
pin_inst_id bigserial primary key,
part_inst_id bigint not null references part_insts,
pin_id bigint not null references pins
);
El principal problema con este esquema es que a pin_instpodría estar vinculado a un part_instcon part_id=1pero pintiene part_id=2.
Me gustaría evitar este problema en el nivel de la base de datos en lugar del nivel de la aplicación. Entonces, modifiqué mis claves principales para hacer cumplir eso. Marqué las líneas cambiadas con --.
create table parts (
part_id bigserial primary key
);
create table pins (
pin_id bigserial, --
part_id bigint not null references parts,
primary key (pin_id, part_id) --
);
create table part_insts (
part_inst_id bigserial, --
part_id bigint not null references parts,
primary key (part_inst_id, part_id) --
);
create table pin_insts (
pin_inst_id bigserial primary key,
part_inst_id bigint not null, --
pin_id bigint not null, --
part_id bigint not null references parts, --
foreign key (part_inst_id, part_id) references part_insts, --
foreign key (pin_id, part_id) references pins --
);
Mi queja con este método es que contamina las claves principales: en todas partes me refiero a part_inst, necesito hacer un seguimiento tanto de la
part_inst_idcomo de la part_id. ¿Hay alguna otra manera de hacer cumplir la restricción
pin_inst.part_inst.part_id = pin_inst.pin.part_idsin ser demasiado detallado?

pin_inst_idredundancia. Puede usar(part_inst_id, part_id, pin_id)como clave principal.