01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.command.ddl;
07:
08: import java.sql.SQLException;
09:
10: import org.h2.command.Prepared;
11: import org.h2.engine.Constants;
12: import org.h2.engine.Database;
13: import org.h2.engine.DbObject;
14: import org.h2.engine.Session;
15: import org.h2.result.LocalResult;
16: import org.h2.table.Column;
17: import org.h2.table.Table;
18: import org.h2.table.TableData;
19: import org.h2.util.ObjectArray;
20:
21: /**
22: * This class represents the statement
23: * ANALYZE
24: */
25: public class Analyze extends DefineCommand {
26:
27: private int sampleRows = Constants.SELECTIVITY_ANALYZE_SAMPLE_ROWS;
28:
29: public Analyze(Session session) {
30: super (session);
31: }
32:
33: public int update() throws SQLException {
34: session.commit(true);
35: Database db = session.getDatabase();
36: session.getUser().checkAdmin();
37: ObjectArray tables = db
38: .getAllSchemaObjects(DbObject.TABLE_OR_VIEW);
39: // TODO do we need to lock the table?
40: for (int i = 0; i < tables.size(); i++) {
41: Table table = (Table) tables.get(i);
42: if (!(table instanceof TableData)) {
43: continue;
44: }
45: Column[] columns = table.getColumns();
46: StringBuffer buff = new StringBuffer();
47: buff.append("SELECT ");
48: for (int j = 0; j < columns.length; j++) {
49: if (j > 0) {
50: buff.append(", ");
51: }
52: buff.append("SELECTIVITY(");
53: buff.append(columns[j].getSQL());
54: buff.append(")");
55: }
56: buff.append(" FROM ");
57: buff.append(table.getSQL());
58: if (sampleRows > 0) {
59: buff.append(" LIMIT 1 SAMPLE_SIZE ");
60: buff.append(sampleRows);
61: }
62: String sql = buff.toString();
63: Prepared command = session.prepare(sql);
64: LocalResult result = command.query(0);
65: result.next();
66: for (int j = 0; j < columns.length; j++) {
67: int selectivity = result.currentRow()[j].getInt();
68: columns[j].setSelectivity(selectivity);
69: }
70: db.update(session, table);
71: }
72: return 0;
73: }
74:
75: public void setTop(int top) {
76: this.sampleRows = top;
77: }
78:
79: }
|