1 package SQLite; 2 3 import java.io.PrintStream; 4 import java.io.PrintWriter; 5 6 /** 7 * SQLite SQL dump utility. 8 */ 9 10 public class SQLDump implements Callback { 11 PrintWriter pw; 12 PrintWriter err; 13 Database db; 14 Shell s; 15 SQLDump(PrintWriter pw, Database db)16 public SQLDump(PrintWriter pw, Database db) { 17 this.pw = pw; 18 this.err = this.pw; 19 this.db = db; 20 s = new Shell(this.pw, this.err); 21 s.mode = Shell.MODE_Insert; 22 s.db = db; 23 } 24 SQLDump(PrintStream ps, Database db)25 public SQLDump(PrintStream ps, Database db) { 26 this.pw = new PrintWriter(ps); 27 this.err = this.pw; 28 this.db = db; 29 s = new Shell(this.pw, this.err); 30 s.mode = Shell.MODE_Insert; 31 s.db = db; 32 } 33 dump()34 public void dump() throws SQLite.Exception { 35 pw.println("BEGIN TRANSACTION;"); 36 db.exec("SELECT name, type, sql FROM sqlite_master " + 37 "WHERE type!='meta' AND sql NOT NULL " + 38 "ORDER BY substr(type,2,1), name", this); 39 pw.println("COMMIT;"); 40 pw.flush(); 41 } 42 columns(String col[])43 public void columns(String col[]) { 44 /* Empty body to satisfy SQLite.Callback interface. */ 45 } 46 types(String args[])47 public void types(String args[]) { 48 /* Empty body to satisfy SQLite.Callback interface. */ 49 } 50 newrow(String args[])51 public boolean newrow(String args[]) { 52 if (args.length != 3) { 53 return true; 54 } 55 pw.println(args[2] + ";"); 56 if (args[1].compareTo("table") == 0) { 57 s.mode = Shell.MODE_Insert; 58 s.set_table_name(args[0]); 59 String qargs[] = new String[1]; 60 qargs[0] = args[0]; 61 try { 62 if (s.db.is3()) { 63 TableResult t = null; 64 t = s.db.get_table("PRAGMA table_info('%q')", qargs); 65 String query; 66 if (t != null) { 67 StringBuffer sb = new StringBuffer(); 68 String sep = ""; 69 70 sb.append("SELECT "); 71 for (int i = 0; i < t.nrows; i++) { 72 String col = ((String[]) t.rows.elementAt(i))[1]; 73 sb.append(sep + "quote(" + 74 Shell.sql_quote_dbl(col) + ")"); 75 sep = ","; 76 } 77 sb.append(" from '%q'"); 78 query = sb.toString(); 79 s.mode = Shell.MODE_Insert2; 80 } else { 81 query = "SELECT * from '%q'"; 82 } 83 s.db.exec(query, s, qargs); 84 pw.flush(); 85 } else { 86 s.db.exec("SELECT * from '%q'", s, qargs); 87 pw.flush(); 88 } 89 } catch (Exception e) { 90 return true; 91 } 92 } 93 s.mode = Shell.MODE_Line; 94 return false; 95 } 96 } 97