71 lines
1.7 KiB
Bash
71 lines
1.7 KiB
Bash
|
#!/bin/bash -ex
|
||
|
|
||
|
# Tool for documenting sql with graphviz
|
||
|
# Usage:
|
||
|
# $ cat sql_file.sql | tools/doc_sql.sh -flags -passed -to -dot > output_file.svg
|
||
|
# Outputs a subgraph and some edges that can be grouped togeather in a full graph
|
||
|
|
||
|
flags=$@
|
||
|
input_file=$(cat -)
|
||
|
# First, find the table name
|
||
|
table_name=$(echo "${input_file}" "SELECT name FROM sqlite_master WHERE type='table';" | sqlite3 | head -n 1)
|
||
|
# And get the data we need to display
|
||
|
table_schema=$(echo "${input_file}" "
|
||
|
SELECT
|
||
|
info.name,
|
||
|
info.type,
|
||
|
info.pk,
|
||
|
info.\"notnull\",
|
||
|
fk_from.\"from\" AS fk_from_col,
|
||
|
fk_from.\"on_delete\" AS fk_on_delete,
|
||
|
fk_from.\"table\" AS fk_from_tbl,
|
||
|
fk_from.\"to\" AS fk_from_to
|
||
|
FROM
|
||
|
pragma_table_info('$table_name') info
|
||
|
LEFT JOIN pragma_foreign_key_list('$table_name') fk_from
|
||
|
ON fk_from.\"from\" = info.\"name\"
|
||
|
ORDER BY
|
||
|
info.\"notnull\" DESC
|
||
|
;" | sqlite3 )
|
||
|
table_pk_1=$(echo "$table_schema" | head -n 1)
|
||
|
table_pk=$(echo "$table_schema" | head -n 1 | awk '
|
||
|
BEGIN {FS="|"}
|
||
|
{print $1}
|
||
|
')
|
||
|
#foreign_keys=$(echo "${input_file}" "pragma foreign_key_list('$table_name');" | sqlite3)
|
||
|
|
||
|
echo "$table_name ["
|
||
|
echo " shape=\"plaintext\""
|
||
|
echo " label=<<table>"
|
||
|
echo " <tr><td colspan=\"3\"><b>" $table_name "</b></td></tr>"
|
||
|
echo "$table_schema" | awk '
|
||
|
BEGIN {FS="|"}
|
||
|
{
|
||
|
if ($4)
|
||
|
print "<tr><td port=\"" $1 "\">PK</td>";
|
||
|
else if ($5)
|
||
|
print "<tr><td port=\"" $1 "\">FK</td>";
|
||
|
else
|
||
|
print "<tr><td></td>";
|
||
|
print "<td>" $1 "</td>";
|
||
|
printf "<td";
|
||
|
if($4)
|
||
|
printf " port=\"" $1 "\">";
|
||
|
else
|
||
|
printf ">";
|
||
|
if($2)
|
||
|
print $2;
|
||
|
else
|
||
|
print $2 "ON DELETE CASCADE";
|
||
|
print "</td></tr>";
|
||
|
}'
|
||
|
echo "</table>> ];"
|
||
|
echo "$table_schema" | awk -v "table_name=$table_name" -v "table_pk=$table_pk" '
|
||
|
BEGIN {FS="|"}
|
||
|
{
|
||
|
if ($5) {
|
||
|
print table_name ":" $5 "->" $7 ":" $8 ;
|
||
|
}
|
||
|
}
|
||
|
'
|