1 33 package smallsql.database; 34 35 36 41 final class SortedResult extends RowSource { 42 43 final private Expressions orderBy; 44 final private RowSource rowSource; 45 private IndexScrollStatus scrollStatus; 46 private int row; 47 private boolean useSetRowPosition; 48 49 SortedResult(RowSource rowSource, Expressions orderBy){ 50 this.rowSource = rowSource; 51 this.orderBy = orderBy; 52 } 53 54 55 final boolean isScrollable(){ 56 return true; } 58 59 60 final void execute() throws Exception { 61 rowSource.execute(); 62 Index index = new Index(false); 63 while(rowSource.next()){ 64 index.addValues( rowSource.getRowPosition(), orderBy); 65 } 66 scrollStatus = index.createScrollStatus(orderBy); 67 useSetRowPosition = false; 68 } 69 70 71 void beforeFirst() throws Exception { 72 scrollStatus.reset(); 73 row = 0; 74 useSetRowPosition = false; 75 } 76 77 78 boolean first() throws Exception { 79 beforeFirst(); 80 return next(); 81 } 82 83 84 boolean previous() throws Exception { 85 return nextPrevious( -1 ); 86 } 87 88 89 boolean next() throws Exception { 90 return nextPrevious( +1 ); 91 } 92 93 94 final private boolean nextPrevious(int scroll) throws Exception { 95 if(useSetRowPosition) throw Utils.createSQLException("Internal Error with ORDER BY"); 96 long rowPosition = scrollStatus.getRowOffset(scroll == 1); 97 if(rowPosition >= 0){ 98 rowSource.setRowPosition( rowPosition ); 99 row += scroll; 100 return true; 101 }else{ 102 noRow(); 103 return false; 104 } 105 } 106 107 108 boolean last() throws Exception { 109 afterLast(); 110 return previous(); 111 } 112 113 114 void afterLast(){ 115 scrollStatus.afterLast(); 116 noRow(); 117 useSetRowPosition = false; 118 } 119 120 121 int getRow(){ 122 return row; 123 } 124 125 126 final long getRowPosition(){ 127 return rowSource.getRowPosition(); 128 } 129 130 131 final void setRowPosition(long rowPosition) throws Exception { 132 rowSource.setRowPosition(rowPosition); 133 useSetRowPosition = true; 134 } 135 136 137 final boolean rowInserted(){ 138 return rowSource.rowInserted(); 139 } 140 141 142 final boolean rowDeleted(){ 143 return rowSource.rowDeleted(); 144 } 145 146 147 void nullRow() { 148 rowSource.nullRow(); 149 row = 0; 150 151 } 152 153 154 void noRow() { 155 rowSource.noRow(); 156 row = 0; 157 } 158 159 } 160 | Popular Tags |