1 34 package smallsql.database; 35 36 import java.io.*; 37 38 39 42 class View extends TableView{ 43 final String sql; 44 final CommandSelect commandSelect; 45 46 47 50 View(SSConnection con, String name, RandomAccessFile raFile, long offset) throws Exception { 51 super( name, new Columns() ); 52 StorePage storePage = new StorePage( null, -1, raFile, offset); 53 StoreImpl store = StoreImpl.createStore( null, storePage, SQLTokenizer.SELECT, offset); 54 sql = store.readString(); 55 56 int type; 58 while((type = store.readInt()) != 0){ 59 int offsetInPage = store.getCurrentOffsetInPage(); 60 int size = store.readInt(); 61 switch(type){ 62 } 64 store.setCurrentOffsetInPage(offsetInPage + size); 65 } 66 67 raFile.close(); 68 commandSelect = (CommandSelect)new SQLParser().parse(con, sql); 69 createColumns(con); 70 } 71 72 73 76 View(Database database, String name, String sql) throws Exception { 77 super( name, new Columns() ); 78 this.sql = sql; 79 this.commandSelect = null; 80 write(database); 81 } 82 83 84 87 View(SSConnection con, CommandSelect commandSelect) throws Exception { 88 super("UNION", new Columns()); 89 this.sql = null; 90 this.commandSelect = commandSelect; 91 createColumns(con); 92 } 93 94 95 private void createColumns(SSConnection con) throws Exception { 96 commandSelect.compile(con); 97 Expressions exprs = commandSelect.columnExpressions; 98 for(int c=0; c<exprs.size(); c++){ 99 Expression expr = exprs.get(c); 100 if(expr instanceof ExpressionName){ 101 Column column = ((ExpressionName)expr).getColumn().copy(); 102 column.setName( expr.getAlias() ); 103 columns.add( column ); 104 }else{ 105 columns.add( new ColumnExpression(expr)); 106 } 107 } 108 } 109 110 111 114 static void drop(Database database, String name) throws Exception { 115 File file = new File( Utils.createTableViewFileName( database, name ) ); 116 boolean ok = file.delete(); 117 if(!ok) throw Utils.createSQLException("View '" + name + "' can't drop."); 118 } 119 120 121 private void write(Database database) throws Exception { 122 RandomAccessFile raFile = createFile( database ); 123 StorePage storePage = new StorePage( null, -1, raFile, 8); 124 StoreImpl store = StoreImpl.createStore( null, storePage, SQLTokenizer.CREATE, 8); 125 store.writeString(sql); 126 127 store.writeInt( 0 ); 130 store.writeFinsh(null); 131 raFile.close(); 132 } 133 134 void writeMagic(RandomAccessFile raFile) throws Exception { 135 raFile.writeInt(MAGIC_VIEW); 136 raFile.writeInt(TABLE_VIEW_VERSION); 137 } 138 139 } 140 | Popular Tags |