pragma foreign_keys = 0;

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

CREATE TEMP TABLE "allstarstartingpos" (
	"player"	NUMERIC,
	"year"	NUMERIC,
	"gameNum"	NUMERIC,
	"league"	NUMERIC,
	"startingPos"	NUMERIC,
	"gameid"	text
);

insert into "allstarstartingpos"
select distinct playerid, yearid, gamenum, lgid, startingpos, gameid
from "raw".allstarfull;

-- fix game numbers for 1962 all-star games
update allstarstartingpos
set gamenum = 1
where gameid = 'ALS196207100';

update allstarstartingpos
set gamenum = 2
where gameid = 'NLS196207300';

-- rocky colavito was a reserve, not starter
delete from allstarstartingpos
where gameid = 'ALS196207100' and player = 'colavro01';

alter table allstarstartingpos drop column "gameid";

update allstarstartingpos
set startingpos = null
where startingpos = '';

delete from allstarstartingpos
where startingpos is null;

CREATE TABLE "allstarstartingpos" (
	"player"	NUMERIC,
	"year"	NUMERIC,
	"gameNum"	NUMERIC,
	"league"	NUMERIC,
	"startingPos"	NUMERIC,
	primary key("year","gameNum","league","startingPos"),
	foreign key("player","year","gameNum") references "allstars"("player","year","gameNum"),
	foreign key("league") references "leagues"("ID")
);

insert into main.allstarstartingpos select distinct * from temp.allstarstartingpos;
commit;
