-
Notifications
You must be signed in to change notification settings - Fork 15
/
Parser.java
598 lines (509 loc) · 23 KB
/
Parser.java
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
package simpledb;
import Zql.*;
import java.io.*;
import java.util.*;
import jline.ArgumentCompletor;
import jline.ConsoleReader;
import jline.SimpleCompletor;
public class Parser {
static boolean explain = false;
static HashMap<String, TableStats> statsMap = new HashMap<String,TableStats>();
private static final int IOCOSTPERPAGE = 1000;
public static void setStatsMap(HashMap<String, TableStats> _statsMap) {
statsMap = _statsMap;
}
static Predicate.Op getOp(String s) throws simpledb.ParsingException {
if (s.equals("=")) return Predicate.Op.EQUALS;
if (s.equals(">")) return Predicate.Op.GREATER_THAN;
if (s.equals(">=")) return Predicate.Op.GREATER_THAN_OR_EQ;
if (s.equals("<")) return Predicate.Op.LESS_THAN;
if (s.equals("<=")) return Predicate.Op.LESS_THAN_OR_EQ;
if (s.equals("LIKE")) return Predicate.Op.LIKE;
if (s.equals("~")) return Predicate.Op.LIKE;
if (s.equals("<>")) return Predicate.Op.NOT_EQUALS;
if (s.equals("!=")) return Predicate.Op.NOT_EQUALS;
throw new simpledb.ParsingException("Unknown predicate " + s);
}
static void processExpression(TransactionId tid, ZExpression wx, LogicalPlan lp) throws simpledb.ParsingException {
if (wx.getOperator().equals("AND")) {
for (int i = 0; i < wx.nbOperands(); i++) {
if (!(wx.getOperand(i) instanceof ZExpression)) {
throw new simpledb.ParsingException("Nested queries are currently unsupported.");
}
ZExpression newWx = (ZExpression)wx.getOperand(i);
processExpression(tid, newWx, lp);
}
} else if (wx.getOperator().equals("OR")) {
throw new simpledb.ParsingException("OR expressions currently unsupported.");
} else {
// this is a binary expression comparing two constants
@SuppressWarnings("unchecked")
Vector<ZExp> ops = wx.getOperands();
if (ops.size() != 2) {
throw new simpledb.ParsingException("Only simple binary expresssions of the form A op B are currently supported.");
}
boolean isJoin = false;
Predicate.Op op = getOp(wx.getOperator());
boolean op1const = ops.elementAt(0) instanceof ZConstant; //otherwise is a Query
boolean op2const = ops.elementAt(1) instanceof ZConstant; //otherwise is a Query
if (op1const && op2const) {
isJoin = ((ZConstant)ops.elementAt(0)).getType() == ZConstant.COLUMNNAME && ((ZConstant)ops.elementAt(1)).getType() == ZConstant.COLUMNNAME;
} else if (ops.elementAt(0) instanceof ZQuery || ops.elementAt(1) instanceof ZQuery) {
isJoin = true;
} else if (ops.elementAt(0) instanceof ZExpression || ops.elementAt(1) instanceof ZExpression) {
throw new simpledb.ParsingException("Only simple binary expresssions of the form A op B are currently supported, where A or B are fields, constants, or subqueries.");
} else isJoin = false;
if (isJoin) { //join node
String tab1field="", tab2field="";
if (!op1const) { //left op is a nested query
//generate a virtual table for the left op
//this isn't a valid ZQL query
} else {
tab1field = ((ZConstant)ops.elementAt(0)).getValue();
}
if (!op2const) { //right op is a nested query
try {
lp.addJoin(tab1field,parseQuery(tid, (ZQuery)ops.elementAt(1)), op);
} catch (IOException e) {
throw new simpledb.ParsingException("Invalid subquery " + ops.elementAt(1));
} catch (Zql.ParseException e) {
throw new simpledb.ParsingException("Invalid subquery " + ops.elementAt(1));
}
} else {
tab2field = ((ZConstant)ops.elementAt(1)).getValue();
lp.addJoin(tab1field,tab2field,op);
}
} else { //select node
String column;
String compValue;
ZConstant op1 = (ZConstant)ops.elementAt(0);
ZConstant op2 = (ZConstant)ops.elementAt(1);
if (op1.getType() == ZConstant.COLUMNNAME) {
column = op1.getValue();
compValue = new String(op2.getValue());
} else {
column = op2.getValue();
compValue = new String(op1.getValue());
}
lp.addFilter(column, op, compValue);
}
}
}
public static LogicalPlan parseQueryLogicalPlan(TransactionId tid, ZQuery q) throws IOException, Zql.ParseException, simpledb.ParsingException {
@SuppressWarnings("unchecked")
Vector<ZFromItem> from = q.getFrom();
LogicalPlan lp = new LogicalPlan();
lp.setQuery(q.toString());
//walk through tables in the FROM clause
for (int i = 0; i < from.size(); i++) {
ZFromItem fromIt = from.elementAt(i);
try {
int id = Database.getCatalog().getTableId(fromIt.getTable()); //will fall through if table doesn't exist
String name;
if (fromIt.getAlias() != null)
name = fromIt.getAlias();
else
name = fromIt.getTable();
lp.addScan(id, name);
//XXX handle subquery?
} catch (NoSuchElementException e) {
e.printStackTrace();
throw new simpledb.ParsingException("Table " + fromIt.getTable() + " is not in catalog");
}
}
// now parse the where clause, creating Filter and Join nodes as needed
ZExp w = q.getWhere();
if (w != null) {
if (!(w instanceof ZExpression)) {
throw new simpledb.ParsingException("Nested queries are currently unsupported.");
}
ZExpression wx = (ZExpression)w;
processExpression(tid, wx, lp);
}
// now look for group by fields
ZGroupBy gby = q.getGroupBy();
String groupByField = null;
if (gby != null) {
@SuppressWarnings("unchecked")
Vector<ZExp> gbs = gby.getGroupBy();
if (gbs.size() > 1) {
throw new simpledb.ParsingException("At most one grouping field expression supported.");
}
if (gbs.size() == 1) {
ZExp gbe = gbs.elementAt(0);
if (! (gbe instanceof ZConstant)) {
throw new simpledb.ParsingException("Complex grouping expressions (" + gbe + ") not supported.");
}
groupByField = ((ZConstant)gbe).getValue();
System.out.println ("GROUP BY FIELD : " + groupByField);
}
}
// walk the select list, pick out aggregates, and check for query validity
@SuppressWarnings("unchecked")
Vector<ZSelectItem> selectList = q.getSelect();
String aggField = null;
String aggFun = null;
for (int i = 0; i < selectList.size(); i++) {
ZSelectItem si = selectList.elementAt(i);
if (si.getAggregate() == null && (si.isExpression() && !(si.getExpression() instanceof ZConstant))) {
throw new simpledb.ParsingException("Expressions in SELECT list are not supported.");
}
if (si.getAggregate() != null) {
if (aggField != null) {
throw new simpledb.ParsingException("Aggregates over multiple fields not supported.");
}
aggField = ((ZConstant)((ZExpression)si.getExpression()).getOperand(0)).getValue();
aggFun = si.getAggregate();
System.out.println ("Aggregate field is " + aggField + ", agg fun is : " + aggFun);
lp.addProjectField(aggField, aggFun);
} else {
if (groupByField != null && ! (groupByField.equals(si.getTable() + "." + si.getColumn()) || groupByField.equals(si.getColumn()))) {
throw new simpledb.ParsingException("Non-aggregate field " + si.getColumn() + " does not appear in GROUP BY list.");
}
lp.addProjectField(si.getTable() + "." + si.getColumn(), null);
}
}
if (groupByField != null && aggFun == null) {
throw new simpledb.ParsingException("GROUP BY without aggregation.");
}
if (aggFun != null) {
lp.addAggregate(aggFun, aggField, groupByField);
}
// sort the data
if (q.getOrderBy() != null) {
@SuppressWarnings("unchecked")
Vector<ZOrderBy> obys = q.getOrderBy();
if (obys.size() > 1) {
throw new simpledb.ParsingException("Multi-attribute ORDER BY is not supported.");
}
ZOrderBy oby = obys.elementAt(0);
if (!(oby.getExpression() instanceof ZConstant)) {
throw new simpledb.ParsingException("Complex ORDER BY's are not supported");
}
ZConstant f = (ZConstant)oby.getExpression();
lp.addOrderBy(f.getValue(), oby.getAscOrder());
}
return lp;
}
public static DbIterator parseQuery(TransactionId tid, ZQuery q) throws IOException, Zql.ParseException, simpledb.ParsingException {
return parseQueryLogicalPlan(tid, q).physicalPlan(tid, statsMap, explain);
}
static Transaction curtrans = null;
public static void handleQueryStatement(ZQuery s) throws TransactionAbortedException, DbException, IOException, simpledb.ParsingException, Zql.ParseException {
// and run it
DbIterator node;
node = parseQuery(curtrans.getId(), s);
Query sdbq = new Query(node, curtrans.getId());
TupleDesc td = node.getTupleDesc();
String names = "";
for (int i = 0; i < td.numFields(); i ++) {
names += td.getFieldName(i) + "\t";
}
System.out.println(names);
for (int i = 0; i < names.length() + td.numFields() * 4; i++) {
System.out.print("-");
}
System.out.println("");
sdbq.start();
int cnt = 0;
while (sdbq.hasNext()) {
Tuple tup = sdbq.next();
System.out.println(tup);
cnt++;
}
System.out.println("\n " + cnt + " rows.");
sdbq.close();
}
public static void handleInsertStatement(ZInsert s) throws TransactionAbortedException, DbException, IOException, simpledb.ParsingException, Zql.ParseException {
int id;
try {
id = Database.getCatalog().getTableId(s.getTable()); //will fall through if table doesn't exist
} catch (NoSuchElementException e) {
throw new simpledb.ParsingException ("Unknown table : " + s.getTable());
}
TupleDesc td = Database.getCatalog().getTupleDesc(id);
Tuple t = new Tuple(td);
int i = 0;
DbIterator newTups;
if (s.getValues() != null) {
@SuppressWarnings("unchecked")
Vector<ZExp> values = (Vector<ZExp>)s.getValues();
if (td.numFields() != values.size()) {
throw new simpledb.ParsingException("INSERT statement does not contain same number of fields as table " + s.getTable());
}
for (ZExp e : values) {
if (!(e instanceof ZConstant))
throw new simpledb.ParsingException("Complex expressions not allowed in INSERT statements.");
ZConstant zc = (ZConstant)e;
if (zc.getType() == ZConstant.NUMBER) {
if (td.getFieldType(i) != Type.INT_TYPE) {
throw new simpledb.ParsingException("Value " + zc.getValue() + " is not an integer, expected a string.");
}
IntField f= new IntField(new Integer(zc.getValue()));
t.setField(i,f);
} else if(zc.getType() == ZConstant.STRING) {
if (td.getFieldType(i) != Type.STRING_TYPE) {
throw new simpledb.ParsingException("Value " + zc.getValue() + " is a string, expected an integer.");
}
StringField f= new StringField(zc.getValue(), Type.STRING_LEN);
t.setField(i,f);
} else {
throw new simpledb.ParsingException("Only string or int fields are supported.");
}
i ++;
}
ArrayList<Tuple> tups = new ArrayList<Tuple>();
tups.add(t);
newTups = new TupleArrayIterator(tups);
} else {
ZQuery query = (ZQuery)s.getQuery();
newTups = parseQuery(curtrans.getId(),query);
}
Query sdbq = new Query(new Insert(curtrans.getId(), newTups, id), curtrans.getId());
// XXX print field names
sdbq.start();
System.out.print("Inserted ");
while (sdbq.hasNext()) {
Tuple tup = sdbq.next();
System.out.println(tup);
}
sdbq.close();
}
public static void handleDeleteStatement(ZDelete s) throws TransactionAbortedException, DbException, IOException, simpledb.ParsingException, Zql.ParseException {
int id;
try {
id = Database.getCatalog().getTableId(s.getTable()); //will fall through if table doesn't exist
} catch (NoSuchElementException e) {
throw new simpledb.ParsingException ("Unknown table : " + s.getTable());
}
String name = s.getTable();
LogicalPlan lp = new LogicalPlan();
lp.setQuery(s.toString());
lp.addScan(id, name);
if (s.getWhere() != null)
processExpression(curtrans.getId(), (ZExpression)s.getWhere(), lp);
lp.addProjectField("null.*",null);
Query sdbq = new Query(new Delete(curtrans.getId(), lp.physicalPlan(curtrans.getId(), statsMap, false)), curtrans.getId());
// XXX print field names
sdbq.start();
System.out.print("Deleted ");
while (sdbq.hasNext()) {
Tuple tup = sdbq.next();
System.out.println(tup);
}
sdbq.close();
}
public static void handleTransactStatement(ZTransactStmt s) throws TransactionAbortedException, DbException, IOException, simpledb.ParsingException, Zql.ParseException {
if (s.getStmtType().equals("COMMIT")) {
curtrans.transactionComplete(false);
curtrans = null;
System.out.println("Transaction committed.");
} else if (s.getStmtType().equals("ROLLBACK")) {
curtrans.transactionComplete(true);
curtrans = null;
System.out.println("Transaction aborted.");
} else {
throw new simpledb.ParsingException("Can't start new transactions until current transaction has been committed or rolledback.");
}
}
public static LogicalPlan generateLogicalPlan(TransactionId tid, String s) throws simpledb.ParsingException {
ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes());
ZqlParser p = new ZqlParser(bis);
try {
ZStatement stmt = p.readStatement();
if (stmt instanceof ZQuery) {
LogicalPlan lp = parseQueryLogicalPlan(tid, (ZQuery)stmt);
return lp;
}
}
catch (Zql.ParseException e) {
throw new simpledb.ParsingException("Invalid SQL expression: \n \t " + e);
}
catch (IOException e) {
throw new simpledb.ParsingException(e);
}
throw new simpledb.ParsingException("Cannot generate logical plan for expression : " + s);
}
public static void setTransaction(Transaction t) {
curtrans = t;
}
public static Transaction getTransaction() {
return curtrans;
}
public static void processNextStatement(String s) {
try {
processNextStatement(new ByteArrayInputStream(s.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void processNextStatement(InputStream is) {
try {
ZqlParser p = new ZqlParser(is);
ZStatement s = p.readStatement();
if (s instanceof ZTransactStmt)
handleTransactStatement((ZTransactStmt)s);
else if (s instanceof ZInsert)
handleInsertStatement((ZInsert)s);
else if (s instanceof ZDelete)
handleDeleteStatement((ZDelete)s);
else if (s instanceof ZQuery)
handleQueryStatement((ZQuery)s);
else {
System.out.println("Can't parse " + s + "\n -- parser only handles SQL transactions, insert, delete, and select statements");
}
} catch (TransactionAbortedException e) {
e.printStackTrace();
} catch (DbException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (simpledb.ParsingException e) {
System.out.println("Invalid SQL expression: \n \t" + e.getMessage());
} catch (Zql.ParseException e) {
System.out.println("Invalid SQL expression: \n \t " + e);
} catch (Zql.TokenMgrError e) {
System.out.println("Invalid SQL expression: \n \t " + e);
}
}
// Basic SQL completions
static final String[] SQL_COMMANDS = {
"select",
"from",
"where",
"group by",
"max(",
"min(",
"avg(",
"count",
"rollback",
"commit",
"insert",
"delete",
"values",
"into"
};
public static void main(String argv[]) throws IOException {
String usage = "Usage: parser catalogFile [-explain] [-f queryFile]";
if (argv.length < 1 || argv.length > 4) {
System.out.println("Invalid number of arguments.\n" + usage);
System.exit(0);
}
//first add tables to database
Database.getCatalog().loadSchema(argv[0]);
Iterator<Integer> tableIt = Database.getCatalog().tableIdIterator();
System.out.println("Computing table stats.");
while (tableIt.hasNext()) {
int tableid = tableIt.next();
TableStats s = new TableStats(tableid, IOCOSTPERPAGE);
statsMap.put(Database.getCatalog().getTableName(tableid), s);
}
System.out.println("Done.");
boolean interactive = true;
String queryFile = null;
if (argv.length > 1) {
for (int i = 1; i<argv.length; i++) {
if (argv[i].equals("-explain")) {
explain = true;
System.out.println("Explain mode enabled.");
} else if (argv[i].equals("-f")) {
interactive = false;
if (i++ == argv.length) {
System.out.println("Expected file name after -f\n" + usage);
System.exit(0);
}
queryFile = argv[i];
} else {
System.out.println("Unknown argument " + argv[i] + "\n " + usage);
}
}
}
if (!interactive) {
try {
curtrans = new Transaction();
curtrans.start();
processNextStatement(new FileInputStream(new File(queryFile)));
} catch (FileNotFoundException e) {
System.out.println("Unable to find query file" + queryFile);
e.printStackTrace();
}
} else { // no query file, run interactive prompt
ConsoleReader reader = new ConsoleReader();
// Add really stupid tab completion for simple SQL
ArgumentCompletor completor = new ArgumentCompletor(new SimpleCompletor(SQL_COMMANDS));
completor.setStrict(false); // match at any position
reader.addCompletor(completor);
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine("SimpleDB> ")) != null) {
// Split statements at ';': handles multiple statements on one line, or one
// statement spread across many lines
while (line.indexOf(';') >= 0) {
int split = line.indexOf(';');
buffer.append(line.substring(0, split+1));
byte[] statementBytes = buffer.toString().getBytes("UTF-8");
//create a transaction for the query
if (curtrans == null) {
curtrans = new Transaction();
curtrans.start();
System.out.println("Started a new transaction tid = " + curtrans.getId().getId());
}
long startTime = System.currentTimeMillis();
processNextStatement(new ByteArrayInputStream(statementBytes));
long time = System.currentTimeMillis() - startTime;
System.out.printf("----------------\n%.2f seconds\n\n", ((double)time/1000.0));
// Grab the remainder of the line
line = line.substring(split+1);
buffer = new StringBuilder();
}
if (line.length() > 0) {
buffer.append(line);
buffer.append("\n");
}
}
}
}
}
class TupleArrayIterator implements DbIterator {
ArrayList<Tuple> tups;
Iterator<Tuple> it = null;
public TupleArrayIterator(ArrayList<Tuple> tups) {
this.tups = tups;
}
public void open()
throws DbException, TransactionAbortedException {
it = tups.iterator();
}
/** @return true if the iterator has more items. */
public boolean hasNext() throws DbException, TransactionAbortedException {
return it.hasNext();
}
/**
* Gets the next tuple from the operator (typically implementing by reading
* from a child operator or an access method).
*
* @return The next tuple in the iterator, or null if there are no more tuples.
*/
public Tuple next() throws DbException, TransactionAbortedException, NoSuchElementException {
return it.next();
}
/**
* Resets the iterator to the start.
* @throws DbException When rewind is unsupported.
*/
public void rewind() throws DbException, TransactionAbortedException {
it = tups.iterator();
}
/**
* Returns the TupleDesc associated with this DbIterator.
*/
public TupleDesc getTupleDesc() {
return tups.get(0).getTupleDesc();
}
/**
* Closes the iterator.
*/
public void close() {
}
}