J'ai rencontré des problèmes pour modéliser un schéma électrique en SQL. La structure que j'aimerais capturer est
part ←────────── pin
↑ ↑
part_inst ←───── pin_inst
où "inst" est l'abréviation de "instance".
Par exemple, je pourrais avoir un partampli-op LM358 avec pins 1OUT, 1IN-, 1IN +, GND, 2IN +, 2IN-, 2OUT et V CC . Je pourrais alors placer cette partie sur un schéma, créant un part_instet 8
pin_insts.
Ignorant les champs de données, ma tentative initiale de schéma était
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
);
Le principal problème avec ce schéma est qu'un pin_instpeut être lié à un part_instavec part_id=1mais qu'il pina part_id=2.
Je voudrais éviter ce problème au niveau de la base de données plutôt qu'au niveau de l'application. J'ai donc modifié mes clés primaires pour appliquer cela. J'ai marqué les lignes modifiées avec --.
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 --
);
Mon reproche avec cette méthode est qu'elle pollue les clés primaires: partout où je me réfère à un part_inst, je dois garder une trace à la fois du
part_inst_idet du part_id. Existe-t-il un autre moyen de faire respecter la contrainte
pin_inst.part_inst.part_id = pin_inst.pin.part_idsans être trop verbeux?
pin_inst_idqui est une redondance. Vous pouvez utiliser la(part_inst_id, part_id, pin_id)clé primaire.