1 5 package org.h2.command.ddl; 6 7 import java.sql.SQLException ; 8 9 import org.h2.command.Prepared; 10 import org.h2.engine.Constants; 11 import org.h2.engine.Database; 12 import org.h2.engine.DbObject; 13 import org.h2.engine.Session; 14 import org.h2.result.LocalResult; 15 import org.h2.table.Column; 16 import org.h2.table.Table; 17 import org.h2.table.TableData; 18 import org.h2.util.ObjectArray; 19 20 public class Analyze extends DefineCommand { 21 22 private int sampleRows = Constants.SELECTIVITY_ANALYZE_SAMPLE_ROWS; 23 24 public Analyze(Session session) { 25 super(session); 26 } 27 28 public int update() throws SQLException { 29 session.commit(); 30 Database db = session.getDatabase(); 31 session.getUser().checkAdmin(); 32 ObjectArray tables = db.getAllSchemaObjects(DbObject.TABLE_OR_VIEW); 33 for(int i=0; i<tables.size(); i++) { 35 Table table = (Table) tables.get(i); 36 if(!(table instanceof TableData)) { 37 continue; 38 } 39 Column[] columns = table.getColumns(); 40 StringBuffer buff = new StringBuffer (); 41 buff.append("SELECT "); 42 for(int j=0; j<columns.length; j++) { 43 if(j>0) { 44 buff.append(", "); 45 } 46 buff.append("SELECTIVITY("); 47 buff.append(columns[j].getSQL()); 48 buff.append(")"); 49 } 50 buff.append(" FROM "); 51 buff.append(table.getSQL()); 52 if(sampleRows > 0) { 53 buff.append(" LIMIT 1 SAMPLE_SIZE "); 54 buff.append(sampleRows); 55 } 56 String sql = buff.toString(); 57 Prepared command = session.prepare(sql); 58 LocalResult result = command.query(0); 59 result.next(); 60 for(int j=0; j<columns.length; j++) { 61 int selectivity = result.currentRow()[j].getInt(); 62 columns[j].setSelectivity(selectivity); 63 } 64 db.update(session, table); 65 } 66 return 0; 67 } 68 69 public void setTop(int top) { 70 this.sampleRows = top; 71 } 72 73 } 74 | Popular Tags |