#!/usr/bin/mumps

#	Kevin C. O'Kane
#	March 4, 2026

#	tmp2 will be executable script of sqlite3 commands to
#	extract data from tables and insert results into mumps table

	o 3:"tmp2,new"
	u 3 w "#!/bin/bash",!

#	create a file of table names

	set %=$zsystem("sqlite3 mumps.sqlite .tables > tmp")

#	open and process list of table names

	o 1:"tmp,old"
	o 4:"tmp3,new"
	u 4 w "#!/bin/bash",!

	for  do
	. u 1 r line
	. i '$t break
	. s line=$zb(line)
	. for i=1:1 do
	.. set table=$p(line," ",i)
	.. if table="" break
	.. if table="mumps" quit

#	write file to be used later to drop the tables

	.. u 4
	.. w "sqlite3 mumps.sqlite ""drop table ",table,";""",!

#	for each table name:
#	write a command to create a file containing the
#	column names and data types of each column.

	.. s x="sqlite3 mumps.sqlite "
	.. s x=x_"""pragma table_info("_table_");"" > tmp1"
	.. s %=$zsystem(x)

	.. u 3 w "sqlite3 mumps.sqlite ""insert into mumps ("
	.. o 2:"tmp1,old"

	.. for j=1:1 do

#	for each table, creat a line of the form:
#	sqlite3 mumps.sqlite "insert into mumps (a1,a2,a3) select 'probtab',icd_code,diagnosis 
#		from probtab limit 10;"
#	j is number of cols in table

	... u 2
	... r col
	... i '$t break

	.. c 2

	.. u 3 f k=1:1:j w "a",k,","
	.. u 3 f k=j+1:1:$zindexmax+1 w "a",k,","
	.. u 3 w "a",$zindexmax+2
	.. u 3 w ") select '",table,"',"

	.. o 2:"tmp1,old"
	.. s hdr=""

	.. for k=1:1:j-2 do
	... u 2
	... r col
	... u 3 w $p(col,"|",2),","
	... s hdr=hdr_$p(col,"|",2)_","

	.. u 2
	.. r col
	.. s hdr=hdr_$p(col,"|",2)

	.. u 3 w $p(col,"|",2),","

	.. u 3 for k=j:1:$zindexmax w "'',"
	.. u 3 w "'' from ",table," limit 10;""",!

	.. w "sqlite3 mumps.sqlite ""insert into mumps ("
	.. f m=1:1:$zindexmax+1 w "a",m,","
	.. w "a",$zindexmax+2,") "

	.. w "values ('",table,"',"
	.. f m=1:1:$zindexmax w "'',"
	.. w "'",hdr,"');""",!

	.. c 2

	c 4
	c 3
	o 3:"tmp2,old"
	for  do
	. u 3 r line
	. i '$t break
	. s %=$zsystem(line)

#	remove original tables 

	o 4:"tmp3,old"
	for  do
	. u 4 r line
	. i '$t break
	. s %=$zsystem(line)
