A SQLite database has an undefined number of tables having the same schema. A view is required that is a union of all these tables with the addition of a field set to the name of the source table.
Note that the table names are unknown as are their column names. All that can be assumed is that all tables have the same schema (i.e. the same columns).
Is it possible to do this in SQLite3?
I can build a view manually given prior knowledge:
create view V(A,B,C) as select 'A' as Tbl, * from A union select 'B' as Tbl, * from B ...
I can find the tables (optional: only table names beginning with X
):
SELECT name FROM sqlite_master where type='table' and name like 'X';
(as similar questions suggest: 1, 2.)
I can find the column names of a table, t
:
pragma table_info(t)
I can use the above information to build the query outside SQLite, in this case using bash
, and then apply it to the database:
# build a select for each table
selects=()
for table in $(sqlite3 "$DB" "SELECT name FROM sqlite_master where type='table'")
do
selects+=("select '$table' as Tbl, * from $table")
done
# Column names for new view, first is source table name followed
# by the table's column names (of the last table, but all assumed to be the same)
columns=(Tbl $(sqlite3 "$DB" "pragma table_info($table)" | awk -F '|' '{print $2}'))
# Build union query
set -o noglob
query=''
for union in "${selects[@]::${#selects[@]}-1}"
do
query+="$union union all "
done
query+="${selects[-1]}"
sqlite3 "$DB" "create view AllTables($(IFS=,;echo "${columns[*]}")) as $query"
Ideally I would prefer to do this from within SQLite3 without having to meta-program it in a shell.