
CREATE OR REPLACE FUNCTION pieces_membre(int) RETURNS TABLE(id_piece int, quantite_piece int)
AS 
$$ 
SELECT id_piece, SUM(quantite_pieces_possedees) FROM (
  SELECT id_piece, quantite_contenir * quantite_enregistrer as quantite_pieces_possedees
  FROM enregistrer
  NATURAL JOIN boites
  NATURAL JOIN contenir
  WHERE id_membre=$1
  UNION
  (SELECT id_piece, quantite_acheter as quantite_pieces_possedees
    FROM acheter WHERE id_membre=$1)
  )
  GROUP BY id_piece
$$
LANGUAGE SQL;
;


CREATE OR REPLACE FUNCTION pieces_boite(int) RETURNS TABLE(id_piece int, quantite_piece int)
AS 
$$ 
(SELECT id_piece, quantite_contenir
  FROM contenir WHERE id_boite=$1);
$$
LANGUAGE SQL;
;


-- Liste des modèles faisables à partir d'un membre
CREATE OR REPLACE FUNCTION modeles_faisables_membre(int) RETURNS TABLE(
 id_modele int
) AS 
$$
SELECT id_modele
FROM modeles
WHERE id_modele not IN
(
  SELECT id_modele FROM (SELECT * FROM pieces_membre($1)) as pieces_possedees
  RIGHT OUTER JOIN (SELECT id_piece as id_necessaire, quantite_necessiter, id_modele
                    FROM necessiter) as pieces_modeles
  ON pieces_possedees.id_piece = id_necessaire
  WHERE quantite_necessiter > quantite_piece OR quantite_piece IS NULL
)
$$
LANGUAGE SQL;


-- Liste des modèles faisables à partir d'une boite
CREATE OR REPLACE FUNCTION modeles_faisables_boite(int) RETURNS TABLE(
 id_modele int
) AS 
$$
SELECT id_modele
FROM modeles
WHERE id_modele not IN
(
  SELECT id_modele FROM  (SELECT * FROM pieces_boite($1)) as pieces_possedees
  RIGHT OUTER JOIN (SELECT id_piece as id_necessaire, quantite_necessiter, id_modele
                    FROM necessiter) as pieces_modeles
  ON pieces_possedees.id_piece = id_necessaire
  WHERE quantite_necessiter > quantite_piece OR quantite_piece IS NULL
)
$$
LANGUAGE SQL;
