
// ViewTables.java
// Andrew Davison, Nov 2022, ad@coe.psu.ac.th

/* For the supplied database, display 
   tables information to stdout. For each table give
   the schema, up to the first 10 records, and the total number
   of records. 

   The DBTablePrinter class is from
   https://github.com/htorun/dbtableprinter

    Usage:
      > compile ViewTables.java
      > run ViewTables <fnm>
    e.g.
      > run ViewTables names.db
      > run ViewTables worldcities.db
      > run ViewTables pictures.db
*/

import java.util.*;
import java.sql.*;


public class ViewTables 
{

  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: java ViewTables <db name>");
      System.exit(1);
    }

    try {
      System.out.println("Connecting to " + args[0]);
      Connection conn = DriverManager.getConnection(         
                                   "jdbc:sqlite:" + args[0]);
      Statement stmt = conn.createStatement();

      ArrayList<String> tableNms = DBUtils.getTableNames(conn);
      if (tableNms.size() == 0) 
        System.out.println("No tables found");
      else {
        if (tableNms.size() > 1) {
          System.out.println(tableNms.size() + " tables:");
          System.out.println(tableNms);
        }

        int count = 1;
        for(String tableNm : tableNms) {
          System.out.println("\n" + count + ". Table \"" + 
                                           tableNm + "\": \n");
          DBUtils.displayColumnsInfo(stmt, tableNm);
          System.out.println();
          DBTablePrinter.printTable(conn, tableNm);
          System.out.println("Total No. rows: " +  
                                   DBUtils.getNumRows(stmt, tableNm));
          System.out.println("-------------------------");
          count++;
        }
      }

      conn.close();
    } 
    catch (SQLException e) 
    {   System.out.println(e); }
  } // end of main()



} // end of ViewTables class

