pragma foreign_keys = 0;

begin;
attach database 'lahman-raw.db' as 'raw';

create temp table pitchingpost as
select * from "raw".pitchingpost;

alter table pitchingpost drop column "lgID";
alter table pitchingpost drop column "teamID";

update pitchingpost
set
	W = nullif(W, ''),
	L = nullif(L, ''),
	G = nullif(G, ''),
	GS = nullif(GS, ''),
	CG = nullif(CG, ''),
	SHO = nullif(SHO, ''),
	SV = nullif(SV, ''),
	IPouts = nullif(IPouts, ''),
	H = nullif(H, ''),
	ER = nullif(ER, ''),
	HR = nullif(HR, ''),
	BB = nullif(BB, ''),
	SO = nullif(SO, ''),
	BAOpp = nullif(BAOpp, ''),
	IBB = nullif(IBB, ''),
	WP = nullif(WP, ''),
	HBP = nullif(HBP, ''),
	BK = nullif(BK, ''),
	BFP = nullif(BFP, ''),
	GF = nullif(GF, ''),
	R = nullif(R, ''),
	SH = nullif(SH, ''),
	SF = nullif(SF, ''),
	GIDP = nullif(GIDP, '');

CREATE TABLE IF NOT EXISTS main."pitchingpost" (
	"player"	TEXT,
	"year"	NUMERIC,
	"round"	NUMERIC,
	"W"	NUMERIC	check (W <= G),
	"L"	NUMERIC	check (L <= G),
	"G"	NUMERIC	check (W + L + SV <= G),
	"GS"	NUMERIC	check (GS <= G),
	"CG"	NUMERIC	check (CG <= GS),
	"SHO"	NUMERIC check (SHO <= G),
	"SV"	NUMERIC	check (SV <= G),
	"IPouts"	NUMERIC,
	"H"	NUMERIC,
	"ER"	NUMERIC	check (ER <= R),
	"HR"	NUMERIC check (HR <= H),
	"BB"	NUMERIC,
	"SO"	NUMERIC	check (SO <= IPouts),
	"BAOpp"	NUMERIC,
	"ERA"	NUMERIC,
	"IBB"	NUMERIC,
	"WP"	NUMERIC,
	"HBP"	NUMERIC,
	"BK"	NUMERIC,
	"BFP"	NUMERIC,
	"GF"	NUMERIC	check (GF <= G),
	"R"	NUMERIC,
	"SH"	NUMERIC,
	"SF"	NUMERIC,
	"GIDP"	NUMERIC	check (2 * GIDP <= IPouts),
	PRIMARY KEY("player","year","round"),
	foreign key("player","year") references "appearancespost"("player","year"),
	foreign key("year","round") references "seriespost"("year","round")
);

insert into main.pitchingpost select distinct * from temp."pitchingpost";
commit;
