1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
* Copyright 2004-2008 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.sql.SQLException;
import org.h2.command.Prepared;
import org.h2.command.dml.Query;
import org.h2.constant.ErrorCode;
import org.h2.engine.Constants;
import org.h2.engine.Session;
import org.h2.engine.User;
import org.h2.expression.Expression;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.index.ViewIndex;
import org.h2.message.Message;
import org.h2.result.Row;
import org.h2.schema.Schema;
import org.h2.util.IntArray;
import org.h2.util.ObjectArray;
import org.h2.util.SmallLRUCache;
import org.h2.util.StringUtils;
import org.h2.value.Value;
/**
* A view is a virtual table that is defined by a query.
*/
public class TableView extends Table {
private String querySQL;
private ObjectArray tables;
private final String[] columnNames;
private Query viewQuery;
private ViewIndex index;
private boolean recursive;
private SQLException createException;
private SmallLRUCache indexCache = new SmallLRUCache(Constants.VIEW_INDEX_CACHE_SIZE);
private long lastModificationCheck;
private long maxDataModificationId;
private User owner;
public TableView(Schema schema, int id, String name, String querySQL, ObjectArray params, String[] columnNames,
Session session, boolean recursive) throws SQLException {
super(schema, id, name, false);
this.querySQL = querySQL;
this.columnNames = columnNames;
this.recursive = recursive;
index = new ViewIndex(this, querySQL, params, recursive);
initColumnsAndTables(session);
}
private Query recompileQuery(Session session) throws SQLException {
Prepared p = session.prepare(querySQL);
if (!(p instanceof Query)) {
throw Message.getSyntaxError(querySQL, 0);
}
Query query = (Query) p;
querySQL = query.getPlanSQL();
return query;
}
private void initColumnsAndTables(Session session) throws SQLException {
Column[] cols;
removeViewFromTables();
try {
Query query = recompileQuery(session);
tables = new ObjectArray(query.getTables());
ObjectArray expressions = query.getExpressions();
ObjectArray list = new ObjectArray();
for (int i = 0; i < query.getColumnCount(); i++) {
Expression expr = (Expression) expressions.get(i);
String name = null;
if (columnNames != null && columnNames.length > i) {
name = columnNames[i];
}
if (name == null) {
name = expr.getAlias();
}
int type = expr.getType();
long precision = expr.getPrecision();
int scale = expr.getScale();
int displaySize = expr.getDisplaySize();
Column col = new Column(name, type, precision, scale, displaySize);
col.setTable(this, i);
list.add(col);
}
cols = new Column[list.size()];
list.toArray(cols);
createException = null;
if (getId() != 0) {
addViewToTables();
}
viewQuery = query;
} catch (SQLException e) {
createException = e;
// if it can't be compiled, then it's a 'zero column table'
// this avoids problems when creating the view when opening the
// database
tables = new ObjectArray();
cols = new Column[0];
if (recursive && columnNames != null) {
cols = new Column[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
cols[i] = new Column(columnNames[i], Value.STRING);
}
index.setRecursive(true);
recursive = true;
createException = null;
}
}
setColumns(cols);
}
/**
* Check if this view is currently invalid.
*
* @return true if it is
*/
public boolean getInvalid() {
return createException != null;
}
public PlanItem getBestPlanItem(Session session, int[] masks) throws SQLException {
PlanItem item = new PlanItem();
item.cost = index.getCost(session, masks);
IntArray masksArray = new IntArray(masks == null ? new int[0] : masks);
ViewIndex i2 = (ViewIndex) indexCache.get(masksArray);
if (i2 == null || i2.getSession() != session) {
i2 = new ViewIndex(this, index, session, masks);
indexCache.put(masksArray, i2);
}
item.setIndex(i2);
return item;
}
public String getDropSQL() {
return "DROP VIEW IF EXISTS " + getSQL();
}
public String getCreateSQL() {
StringBuffer buff = new StringBuffer();
buff.append("CREATE FORCE VIEW ");
buff.append(getSQL());
if (comment != null) {
buff.append(" COMMENT ");
buff.append(StringUtils.quoteStringSQL(comment));
}
if (columns.length > 0) {
buff.append('(');
for (int i = 0; i < columns.length; i++) {
if (i > 0) {
buff.append(", ");
}
buff.append(columns[i].getSQL());
}
buff.append(")");
}
buff.append(" AS\n");
buff.append(querySQL);
return buff.toString();
}
public void checkRename() {
// ok
}
public void lock(Session session, boolean exclusive, boolean force) {
// exclusive lock means: the view will be dropped
}
public void close(Session session) {
// nothing to do
}
public void unlock(Session s) {
// nothing to do
}
public boolean isLockedExclusively() {
return false;
}
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
int headPos, String comment) throws SQLException {
throw Message.getUnsupportedException();
}
public void removeRow(Session session, Row row) throws SQLException {
throw Message.getUnsupportedException();
}
public void addRow(Session session, Row row) throws SQLException {
throw Message.getUnsupportedException();
}
public void checkSupportAlter() throws SQLException {
// TODO view: alter what? rename is ok
throw Message.getUnsupportedException();
}
public void truncate(Session session) throws SQLException {
throw Message.getUnsupportedException();
}
public long getRowCount(Session session) {
throw Message.getInternalError();
}
public boolean canGetRowCount() {
// TODO view: could get the row count, but not that easy
return false;
}
public boolean canDrop() {
return true;
}
public String getTableType() {
return Table.VIEW;
}
public void removeChildrenAndResources(Session session) throws SQLException {
removeViewFromTables();
super.removeChildrenAndResources(session);
database.removeMeta(session, getId());
querySQL = null;
index = null;
invalidate();
}
public String getSQL() {
if (getTemporary()) {
StringBuffer buff = new StringBuffer(querySQL.length());
buff.append("(");
buff.append(querySQL);
buff.append(")");
return buff.toString();
}
return super.getSQL();
}
public Index getScanIndex(Session session) throws SQLException {
if (createException != null) {
String msg = createException.getMessage();
throw Message.getSQLException(ErrorCode.VIEW_IS_INVALID_2, new String[] { getSQL(), msg }, createException);
}
PlanItem item = getBestPlanItem(session, null);
return item.getIndex();
}
public ObjectArray getIndexes() {
return null;
}
/**
* Re-compile the view query.
*
* @param session the session
*/
public void recompile(Session session) throws SQLException {
for (int i = 0; i < tables.size(); i++) {
Table t = (Table) tables.get(i);
t.removeView(this);
}
tables.clear();
initColumnsAndTables(session);
}
public long getMaxDataModificationId() {
if (createException != null) {
throw Message.getInternalError();
}
if (viewQuery == null) {
return Long.MAX_VALUE;
}
// if nothing was modified in the database since the last check, and the
// last is known, then we don't need to check again
// this speeds up nested views
long dbMod = database.getModificationDataId();
if (dbMod > lastModificationCheck && maxDataModificationId <= dbMod) {
maxDataModificationId = viewQuery.getMaxDataModificationId();
lastModificationCheck = dbMod;
}
return maxDataModificationId;
}
public Index getUniqueIndex() {
return null;
}
private void removeViewFromTables() {
if (tables != null) {
for (int i = 0; i < tables.size(); i++) {
Table t = (Table) tables.get(i);
t.removeView(this);
}
tables.clear();
}
}
private void addViewToTables() {
for (int i = 0; i < tables.size(); i++) {
Table t = (Table) tables.get(i);
t.addView(this);
}
}
private void setOwner(User owner) {
this.owner = owner;
}
public User getOwner() {
return owner;
}
/**
* Create a temporary view out of the given query.
*
* @param session the session
* @param owner the owner of the query
* @param query the query
* @return the view table
*/
public static TableView createTempView(Session session, User owner, Query query) throws SQLException {
String tempViewName = session.getNextTempViewName();
Schema mainSchema = session.getDatabase().getSchema(Constants.SCHEMA_MAIN);
String querySQL = query.getPlanSQL();
TableView v = new TableView(mainSchema, 0, tempViewName, querySQL, query.getParameters(), null, session,
false);
if (v.createException != null) {
throw v.createException;
}
v.setOwner(owner);
v.setTemporary(true);
return v;
}
}