提交 f076058c authored 作者: Thomas Mueller's avatar Thomas Mueller

Enable warning for 'Local variable declaration hides another field or variable'.

上级 162c96c0
...@@ -581,9 +581,9 @@ public class Data extends DataPage { ...@@ -581,9 +581,9 @@ public class Data extends DataPage {
case Value.DECIMAL: { case Value.DECIMAL: {
int scale = readVarInt(); int scale = readVarInt();
int len = readVarInt(); int len = readVarInt();
byte[] data = MemoryUtils.newBytes(len); byte[] buff = MemoryUtils.newBytes(len);
read(data, 0, len); read(buff, 0, len);
BigInteger b = new BigInteger(data); BigInteger b = new BigInteger(buff);
return ValueDecimal.get(new BigDecimal(b, scale)); return ValueDecimal.get(new BigDecimal(b, scale));
} }
case Value.DATE: { case Value.DATE: {
......
...@@ -397,9 +397,7 @@ public class DataPage { ...@@ -397,9 +397,7 @@ public class DataPage {
* @param v the value * @param v the value
*/ */
public void writeValue(Value v) throws SQLException { public void writeValue(Value v) throws SQLException {
if (SysProperties.CHECK) { checkCapacity(8);
checkCapacity(8);
}
// TODO text output: could be in the Value... classes // TODO text output: could be in the Value... classes
if (v == ValueNull.INSTANCE) { if (v == ValueNull.INSTANCE) {
data[pos++] = '-'; data[pos++] = '-';
......
...@@ -1164,14 +1164,14 @@ public class DiskFile implements CacheWriter { ...@@ -1164,14 +1164,14 @@ public class DiskFile implements CacheWriter {
System.arraycopy(all.getBytes(), 0, data, 0, all.length()); System.arraycopy(all.getBytes(), 0, data, 0, all.length());
} }
for (int i = 0; i < blockCount; i++) { for (int i = 0; i < blockCount; i++) {
RedoLogRecord log = new RedoLogRecord(); RedoLogRecord redo = new RedoLogRecord();
log.recordId = recordId + i; redo.recordId = recordId + i;
log.offset = i * BLOCK_SIZE; redo.offset = i * BLOCK_SIZE;
log.storage = storage; redo.storage = storage;
log.data = data; redo.data = data;
log.sequenceId = redoBuffer.size(); redo.sequenceId = redoBuffer.size();
redoBuffer.add(log); redoBuffer.add(redo);
redoBufferSize += log.getSize(); redoBufferSize += redo.getSize();
} }
if (redoBufferSize > SysProperties.REDO_BUFFER_SIZE) { if (redoBufferSize > SysProperties.REDO_BUFFER_SIZE) {
flushRedoLog(); flushRedoLog();
......
...@@ -73,7 +73,7 @@ public class FileLock { ...@@ -73,7 +73,7 @@ public class FileLock {
/** /**
* The server socket (only used when using the SOCKET mode). * The server socket (only used when using the SOCKET mode).
*/ */
volatile ServerSocket socket; volatile ServerSocket serverSocket;
/** /**
* The file system. * The file system.
...@@ -154,14 +154,14 @@ public class FileLock { ...@@ -154,14 +154,14 @@ public class FileLock {
fs.delete(fileName); fs.delete(fileName);
} }
} }
if (socket != null) { if (serverSocket != null) {
socket.close(); serverSocket.close();
} }
} catch (Exception e) { } catch (Exception e) {
trace.debug("unlock", e); trace.debug("unlock", e);
} finally { } finally {
fileName = null; fileName = null;
socket = null; serverSocket = null;
locked = false; locked = false;
} }
try { try {
...@@ -428,23 +428,23 @@ public class FileLock { ...@@ -428,23 +428,23 @@ public class FileLock {
} }
try { try {
// 0 to use any free port // 0 to use any free port
socket = NetUtils.createServerSocket(0, false); serverSocket = NetUtils.createServerSocket(0, false);
int port = socket.getLocalPort(); int port = serverSocket.getLocalPort();
properties.setProperty("ipAddress", ipAddress); properties.setProperty("ipAddress", ipAddress);
properties.setProperty("port", String.valueOf(port)); properties.setProperty("port", String.valueOf(port));
} catch (Exception e) { } catch (Exception e) {
trace.debug("lock", e); trace.debug("lock", e);
socket = null; serverSocket = null;
lockFile(); lockFile();
return; return;
} }
save(); save();
watchdog = new Thread(new Runnable() { watchdog = new Thread(new Runnable() {
public void run() { public void run() {
while (socket != null) { while (serverSocket != null) {
try { try {
trace.debug("watchdog accept"); trace.debug("watchdog accept");
Socket s = socket.accept(); Socket s = serverSocket.accept();
s.close(); s.close();
} catch (Exception e) { } catch (Exception e) {
trace.debug("watchdog", e); trace.debug("watchdog", e);
......
...@@ -21,7 +21,7 @@ public class PageInputStream extends InputStream { ...@@ -21,7 +21,7 @@ public class PageInputStream extends InputStream {
private PageStore store; private PageStore store;
private final Trace trace; private final Trace trace;
private int firstTrunkPage; private int firstTrunkPage;
private PageStreamTrunk.Iterator it; private PageStreamTrunk.Iterator trunkIterator;
private int dataPage; private int dataPage;
private PageStreamTrunk trunk; private PageStreamTrunk trunk;
private PageStreamData data; private PageStreamData data;
...@@ -36,7 +36,7 @@ public class PageInputStream extends InputStream { ...@@ -36,7 +36,7 @@ public class PageInputStream extends InputStream {
// minus one because we increment before comparing // minus one because we increment before comparing
this.logKey = logKey - 1; this.logKey = logKey - 1;
this.firstTrunkPage = firstTrunkPage; this.firstTrunkPage = firstTrunkPage;
it = new PageStreamTrunk.Iterator(store, firstTrunkPage); trunkIterator = new PageStreamTrunk.Iterator(store, firstTrunkPage);
this.dataPage = dataPage; this.dataPage = dataPage;
} }
...@@ -88,7 +88,7 @@ public class PageInputStream extends InputStream { ...@@ -88,7 +88,7 @@ public class PageInputStream extends InputStream {
int next; int next;
while (true) { while (true) {
if (trunk == null) { if (trunk == null) {
trunk = it.next(); trunk = trunkIterator.next();
logKey++; logKey++;
if (trunk == null || trunk.getLogKey() != logKey) { if (trunk == null || trunk.getLogKey() != logKey) {
endOfFile = true; endOfFile = true;
......
...@@ -116,16 +116,14 @@ public class PageLog { ...@@ -116,16 +116,14 @@ public class PageLog {
private static final boolean COMPRESS_UNDO = true; private static final boolean COMPRESS_UNDO = true;
private final PageStore store; private final PageStore store;
private int pos;
private Trace trace; private Trace trace;
private Data writeBuffer; private Data writeBuffer;
private PageInputStream pageIn; private PageInputStream pageIn;
private PageOutputStream pageOut; private PageOutputStream pageOut;
private DataReader in;
private int firstTrunkPage; private int firstTrunkPage;
private int firstDataPage; private int firstDataPage;
private Data data; private Data dataBuffer;
private int logKey; private int logKey;
private int logSectionId, logPos; private int logSectionId, logPos;
private int firstSectionId; private int firstSectionId;
...@@ -164,7 +162,7 @@ public class PageLog { ...@@ -164,7 +162,7 @@ public class PageLog {
PageLog(PageStore store) { PageLog(PageStore store) {
this.store = store; this.store = store;
data = store.createData(); dataBuffer = store.createData();
trace = store.getTrace(); trace = store.getTrace();
compress = new CompressLZF(); compress = new CompressLZF();
compressBuffer = new byte[store.getPageSize() * 2]; compressBuffer = new byte[store.getPageSize() * 2];
...@@ -174,17 +172,17 @@ public class PageLog { ...@@ -174,17 +172,17 @@ public class PageLog {
* Open the log for writing. For an existing database, the recovery * Open the log for writing. For an existing database, the recovery
* must be run first. * must be run first.
* *
* @param firstTrunkPage the first trunk page * @param newFirstTrunkPage the first trunk page
* @param atEnd whether only pages at the end of the file should be used * @param atEnd whether only pages at the end of the file should be used
*/ */
void openForWriting(int firstTrunkPage, boolean atEnd) throws SQLException { void openForWriting(int newFirstTrunkPage, boolean atEnd) throws SQLException {
trace.debug("log openForWriting firstPage:" + firstTrunkPage); trace.debug("log openForWriting firstPage:" + newFirstTrunkPage);
this.firstTrunkPage = firstTrunkPage; this.firstTrunkPage = newFirstTrunkPage;
logKey++; logKey++;
pageOut = new PageOutputStream(store, firstTrunkPage, undoAll, logKey, atEnd); pageOut = new PageOutputStream(store, newFirstTrunkPage, undoAll, logKey, atEnd);
pageOut.reserve(1); pageOut.reserve(1);
// pageBuffer = new BufferedOutputStream(pageOut, 8 * 1024); // pageBuffer = new BufferedOutputStream(pageOut, 8 * 1024);
store.setLogFirstPage(logKey, firstTrunkPage, pageOut.getCurrentDataPageId()); store.setLogFirstPage(logKey, newFirstTrunkPage, pageOut.getCurrentDataPageId());
writeBuffer = store.createData(); writeBuffer = store.createData();
} }
...@@ -212,14 +210,14 @@ public class PageLog { ...@@ -212,14 +210,14 @@ public class PageLog {
/** /**
* Open the log for reading. * Open the log for reading.
* *
* @param logKey the first expected log key * @param newLogKey the first expected log key
* @param firstTrunkPage the first trunk page * @param newFirstTrunkPage the first trunk page
* @param firstDataPage the index of the first data page * @param newFirstDataPage the index of the first data page
*/ */
void openForReading(int logKey, int firstTrunkPage, int firstDataPage) { void openForReading(int newLogKey, int newFirstTrunkPage, int newFirstDataPage) {
this.logKey = logKey; this.logKey = newLogKey;
this.firstTrunkPage = firstTrunkPage; this.firstTrunkPage = newFirstTrunkPage;
this.firstDataPage = firstDataPage; this.firstDataPage = newFirstDataPage;
} }
/** /**
...@@ -241,11 +239,11 @@ public class PageLog { ...@@ -241,11 +239,11 @@ public class PageLog {
return; return;
} }
pageIn = new PageInputStream(store, logKey, firstTrunkPage, firstDataPage); pageIn = new PageInputStream(store, logKey, firstTrunkPage, firstDataPage);
in = new DataReader(pageIn); DataReader in = new DataReader(pageIn);
int logId = 0; int logId = 0;
Data data = store.createData(); Data data = store.createData();
try { try {
pos = 0; int pos = 0;
while (true) { while (true) {
int x = in.read(); int x = in.read();
if (x < 0) { if (x < 0) {
...@@ -576,6 +574,7 @@ public class PageLog { ...@@ -576,6 +574,7 @@ public class PageLog {
session.addLogPos(logSectionId, logPos); session.addLogPos(logSectionId, logPos);
row.setLastLog(logSectionId, logPos); row.setLastLog(logSectionId, logPos);
logPos++; logPos++;
Data data = dataBuffer;
data.reset(); data.reset();
int columns = row.getColumnCount(); int columns = row.getColumnCount();
data.writeVarInt(columns); data.writeVarInt(columns);
...@@ -684,21 +683,21 @@ public class PageLog { ...@@ -684,21 +683,21 @@ public class PageLog {
/** /**
* Remove all pages until the given data page. * Remove all pages until the given data page.
* *
* @param firstTrunkPage the first trunk page * @param trunkPage the first trunk page
* @param firstDataPageToKeep the first data page to keep * @param firstDataPageToKeep the first data page to keep
* @return the trunk page of the data page to keep * @return the trunk page of the data page to keep
*/ */
private int removeUntil(int firstTrunkPage, int firstDataPageToKeep) throws SQLException { private int removeUntil(int trunkPage, int firstDataPageToKeep) throws SQLException {
trace.debug("log.removeUntil " + firstDataPageToKeep); trace.debug("log.removeUntil " + firstDataPageToKeep);
while (true) { while (true) {
Page p = store.getPage(firstTrunkPage); Page p = store.getPage(trunkPage);
PageStreamTrunk t = (PageStreamTrunk) p; PageStreamTrunk t = (PageStreamTrunk) p;
logKey = t.getLogKey(); logKey = t.getLogKey();
t.resetIndex(); t.resetIndex();
if (t.contains(firstDataPageToKeep)) { if (t.contains(firstDataPageToKeep)) {
return t.getPos(); return t.getPos();
} }
firstTrunkPage = t.getNextTrunk(); trunkPage = t.getNextTrunk();
IntArray list = new IntArray(); IntArray list = new IntArray();
list.add(t.getPos()); list.add(t.getPos());
while (true) { while (true) {
......
...@@ -33,7 +33,7 @@ public class PageOutputStream extends OutputStream { ...@@ -33,7 +33,7 @@ public class PageOutputStream extends OutputStream {
private byte[] buffer = new byte[1]; private byte[] buffer = new byte[1];
private boolean needFlush; private boolean needFlush;
private boolean writing; private boolean writing;
private int pages; private int pageCount;
private boolean atEnd; private boolean atEnd;
private int logKey; private int logKey;
...@@ -106,13 +106,13 @@ public class PageOutputStream extends OutputStream { ...@@ -106,13 +106,13 @@ public class PageOutputStream extends OutputStream {
trunkNext = reservedPages.get(len); trunkNext = reservedPages.get(len);
logKey++; logKey++;
trunk = PageStreamTrunk.create(store, parent, trunkPageId, trunkNext, logKey, pageIds); trunk = PageStreamTrunk.create(store, parent, trunkPageId, trunkNext, logKey, pageIds);
pages++; pageCount++;
trunk.write(null); trunk.write(null);
reservedPages.removeRange(0, len + 1); reservedPages.removeRange(0, len + 1);
nextData = trunk.getNextPageData(); nextData = trunk.getNextPageData();
} }
data = PageStreamData.create(store, nextData, trunk.getPos(), logKey); data = PageStreamData.create(store, nextData, trunk.getPos(), logKey);
pages++; pageCount++;
data.initWrite(); data.initWrite();
} }
...@@ -186,7 +186,7 @@ public class PageOutputStream extends OutputStream { ...@@ -186,7 +186,7 @@ public class PageOutputStream extends OutputStream {
} }
long getSize() { long getSize() {
return pages * store.getPageSize(); return pageCount * store.getPageSize();
} }
/** /**
...@@ -195,7 +195,7 @@ public class PageOutputStream extends OutputStream { ...@@ -195,7 +195,7 @@ public class PageOutputStream extends OutputStream {
* @param t the trunk page * @param t the trunk page
*/ */
void free(PageStreamTrunk t) throws SQLException { void free(PageStreamTrunk t) throws SQLException {
pages -= t.free(); pageCount -= t.free();
} }
int getCurrentLogKey() { int getCurrentLogKey() {
......
...@@ -555,10 +555,10 @@ public class PageStore implements CacheWriter { ...@@ -555,10 +555,10 @@ public class PageStore implements CacheWriter {
int firstUncommittedSection = log.getLogSectionId(); int firstUncommittedSection = log.getLogSectionId();
for (int i = 0; i < sessions.length; i++) { for (int i = 0; i < sessions.length; i++) {
Session session = sessions[i]; Session session = sessions[i];
int log = session.getFirstUncommittedLog(); int firstUncommitted = session.getFirstUncommittedLog();
if (log != LogSystem.LOG_WRITTEN) { if (firstUncommitted != LogSystem.LOG_WRITTEN) {
if (log < firstUncommittedSection) { if (firstUncommitted < firstUncommittedSection) {
firstUncommittedSection = log; firstUncommittedSection = firstUncommitted;
} }
} }
} }
......
...@@ -178,8 +178,8 @@ public class FileObjectMemory implements FileObject { ...@@ -178,8 +178,8 @@ public class FileObjectMemory implements FileObject {
} }
} }
public void seek(long pos) { public void seek(long newPos) {
this.pos = (int) pos; this.pos = (int) newPos;
} }
private void changeLength(long len) { private void changeLength(long len) {
......
...@@ -87,8 +87,8 @@ public class FileObjectZip implements FileObject { ...@@ -87,8 +87,8 @@ public class FileObjectZip implements FileObject {
inPos += len; inPos += len;
} }
public void seek(long pos) { public void seek(long newPos) {
this.pos = pos; this.pos = newPos;
} }
public void setFileLength(long newLength) throws IOException { public void setFileLength(long newLength) throws IOException {
......
...@@ -326,16 +326,16 @@ public class Column { ...@@ -326,16 +326,16 @@ public class Column {
private void updateSequenceIfRequired(Session session, Value value) throws SQLException { private void updateSequenceIfRequired(Session session, Value value) throws SQLException {
if (sequence != null) { if (sequence != null) {
long current = sequence.getCurrentValue(); long current = sequence.getCurrentValue();
long increment = sequence.getIncrement(); long inc = sequence.getIncrement();
long now = value.getLong(); long now = value.getLong();
boolean update = false; boolean update = false;
if (increment > 0 && now > current) { if (inc > 0 && now > current) {
update = true; update = true;
} else if (increment < 0 && now < current) { } else if (inc < 0 && now < current) {
update = true; update = true;
} }
if (update) { if (update) {
sequence.setStartValue(now + increment); sequence.setStartValue(now + inc);
session.setLastIdentity(ValueLong.get(now)); session.setLastIdentity(ValueLong.get(now));
sequence.flush(session); sequence.flush(session);
} }
...@@ -370,16 +370,16 @@ public class Column { ...@@ -370,16 +370,16 @@ public class Column {
break; break;
} }
} }
Sequence sequence = new Sequence(schema, id, sequenceName, true); Sequence seq = new Sequence(schema, id, sequenceName, true);
sequence.setStartValue(start); seq.setStartValue(start);
sequence.setIncrement(increment); seq.setIncrement(increment);
if (!temporary) { if (!temporary) {
session.getDatabase().addSchemaObject(session, sequence); session.getDatabase().addSchemaObject(session, seq);
} }
setAutoIncrement(false, 0, 0); setAutoIncrement(false, 0, 0);
SequenceValue seq = new SequenceValue(sequence); SequenceValue seqValue = new SequenceValue(seq);
setDefaultExpression(session, seq); setDefaultExpression(session, seqValue);
setSequence(sequence); setSequence(seq);
} }
/** /**
......
...@@ -92,7 +92,7 @@ public class FunctionTable extends Table { ...@@ -92,7 +92,7 @@ public class FunctionTable extends Table {
} }
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
int headPos, String comment) throws SQLException { int headPos, String indexComment) throws SQLException {
throw Message.getUnsupportedException("ALIAS"); throw Message.getUnsupportedException("ALIAS");
} }
......
...@@ -104,7 +104,7 @@ public class MetaTable extends Table { ...@@ -104,7 +104,7 @@ public class MetaTable extends Table {
private final int type; private final int type;
private final int indexColumn; private final int indexColumn;
private MetaIndex index; private MetaIndex metaIndex;
/** /**
* Create a new metadata table. * Create a new metadata table.
...@@ -513,7 +513,7 @@ public class MetaTable extends Table { ...@@ -513,7 +513,7 @@ public class MetaTable extends Table {
} else { } else {
indexColumn = getColumn(indexColumnName).getColumnId(); indexColumn = getColumn(indexColumnName).getColumnId();
IndexColumn[] indexCols = IndexColumn.wrap(new Column[] { cols[indexColumn] }); IndexColumn[] indexCols = IndexColumn.wrap(new Column[] { cols[indexColumn] });
index = new MetaIndex(this, indexCols, false); metaIndex = new MetaIndex(this, indexCols, false);
} }
} }
...@@ -522,16 +522,16 @@ public class MetaTable extends Table { ...@@ -522,16 +522,16 @@ public class MetaTable extends Table {
for (int i = 0; i < names.length; i++) { for (int i = 0; i < names.length; i++) {
String nameType = names[i]; String nameType = names[i];
int idx = nameType.indexOf(' '); int idx = nameType.indexOf(' ');
int type; int dataType;
String name; String name;
if (idx < 0) { if (idx < 0) {
type = Value.STRING; dataType = Value.STRING;
name = nameType; name = nameType;
} else { } else {
type = DataType.getTypeByName(nameType.substring(idx + 1)).type; dataType = DataType.getTypeByName(nameType.substring(idx + 1)).type;
name = nameType.substring(0, idx); name = nameType.substring(0, idx);
} }
cols[i] = new Column(name, type); cols[i] = new Column(name, dataType);
} }
return cols; return cols;
} }
...@@ -545,7 +545,7 @@ public class MetaTable extends Table { ...@@ -545,7 +545,7 @@ public class MetaTable extends Table {
} }
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
int headPos, String comment) throws SQLException { int headPos, String indexComment) throws SQLException {
throw Message.getUnsupportedException("META"); throw Message.getUnsupportedException("META");
} }
...@@ -1017,7 +1017,7 @@ public class MetaTable extends Table { ...@@ -1017,7 +1017,7 @@ public class MetaTable extends Table {
for (Right r : database.getAllRights()) { for (Right r : database.getAllRights()) {
Role role = r.getGrantedRole(); Role role = r.getGrantedRole();
DbObject grantee = r.getGrantee(); DbObject grantee = r.getGrantee();
String type = grantee.getType() == DbObject.USER ? "USER" : "ROLE"; String rightType = grantee.getType() == DbObject.USER ? "USER" : "ROLE";
if (role == null) { if (role == null) {
Table granted = r.getGrantedTable(); Table granted = r.getGrantedTable();
String tableName = identifier(granted.getName()); String tableName = identifier(granted.getName());
...@@ -1028,7 +1028,7 @@ public class MetaTable extends Table { ...@@ -1028,7 +1028,7 @@ public class MetaTable extends Table {
// GRANTEE // GRANTEE
identifier(grantee.getName()), identifier(grantee.getName()),
// GRANTEETYPE // GRANTEETYPE
type, rightType,
// GRANTEDROLE // GRANTEDROLE
"", "",
// RIGHTS // RIGHTS
...@@ -1045,7 +1045,7 @@ public class MetaTable extends Table { ...@@ -1045,7 +1045,7 @@ public class MetaTable extends Table {
// GRANTEE // GRANTEE
identifier(grantee.getName()), identifier(grantee.getName()),
// GRANTEETYPE // GRANTEETYPE
type, rightType,
// GRANTEDROLE // GRANTEDROLE
identifier(role.getName()), identifier(role.getName()),
// RIGHTS // RIGHTS
...@@ -1122,11 +1122,11 @@ public class MetaTable extends Table { ...@@ -1122,11 +1122,11 @@ public class MetaTable extends Table {
case FUNCTION_COLUMNS: { case FUNCTION_COLUMNS: {
for (FunctionAlias alias : database.getAllFunctionAliases()) { for (FunctionAlias alias : database.getAllFunctionAliases()) {
for (FunctionAlias.JavaMethod method : alias.getJavaMethods()) { for (FunctionAlias.JavaMethod method : alias.getJavaMethods()) {
Class< ? >[] columns = method.getColumnClasses(); Class< ? >[] columnList = method.getColumnClasses();
for (int k = 0; k < columns.length; k++) { for (int k = 0; k < columnList.length; k++) {
Class< ? > clazz = columns[k]; Class< ? > clazz = columnList[k];
int type = DataType.getTypeFromClass(clazz); int dataType = DataType.getTypeFromClass(clazz);
DataType dt = DataType.getDataType(type); DataType dt = DataType.getDataType(dataType);
int nullable = clazz.isPrimitive() ? DatabaseMetaData.columnNoNulls int nullable = clazz.isPrimitive() ? DatabaseMetaData.columnNoNulls
: DatabaseMetaData.columnNullable; : DatabaseMetaData.columnNullable;
add(rows, add(rows,
...@@ -1338,9 +1338,9 @@ public class MetaTable extends Table { ...@@ -1338,9 +1338,9 @@ public class MetaTable extends Table {
case CONSTRAINTS: { case CONSTRAINTS: {
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.CONSTRAINT)) { for (SchemaObject obj : database.getAllSchemaObjects(DbObject.CONSTRAINT)) {
Constraint constraint = (Constraint) obj; Constraint constraint = (Constraint) obj;
String type = constraint.getConstraintType(); String constraintType = constraint.getConstraintType();
String checkExpression = null; String checkExpression = null;
IndexColumn[] columns = null; IndexColumn[] indexColumns = null;
Table table = constraint.getTable(); Table table = constraint.getTable();
Index index = constraint.getUniqueIndex(); Index index = constraint.getUniqueIndex();
String uniqueIndexName = null; String uniqueIndexName = null;
...@@ -1351,17 +1351,17 @@ public class MetaTable extends Table { ...@@ -1351,17 +1351,17 @@ public class MetaTable extends Table {
if (!checkIndex(session, tableName, indexFrom, indexTo)) { if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue; continue;
} }
if (type.equals(Constraint.CHECK)) { if (constraintType.equals(Constraint.CHECK)) {
checkExpression = ((ConstraintCheck) constraint).getExpression().getSQL(); checkExpression = ((ConstraintCheck) constraint).getExpression().getSQL();
} else if (type.equals(Constraint.UNIQUE) || type.equals(Constraint.PRIMARY_KEY)) { } else if (constraintType.equals(Constraint.UNIQUE) || constraintType.equals(Constraint.PRIMARY_KEY)) {
columns = ((ConstraintUnique) constraint).getColumns(); indexColumns = ((ConstraintUnique) constraint).getColumns();
} else if (type.equals(Constraint.REFERENTIAL)) { } else if (constraintType.equals(Constraint.REFERENTIAL)) {
columns = ((ConstraintReferential) constraint).getColumns(); indexColumns = ((ConstraintReferential) constraint).getColumns();
} }
String columnList = null; String columnList = null;
if (columns != null) { if (indexColumns != null) {
StatementBuilder buff = new StatementBuilder(); StatementBuilder buff = new StatementBuilder();
for (IndexColumn col : columns) { for (IndexColumn col : indexColumns) {
buff.appendExceptFirst(","); buff.appendExceptFirst(",");
buff.append(col.column.getName()); buff.append(col.column.getName());
} }
...@@ -1375,7 +1375,7 @@ public class MetaTable extends Table { ...@@ -1375,7 +1375,7 @@ public class MetaTable extends Table {
// CONSTRAINT_NAME // CONSTRAINT_NAME
identifier(constraint.getName()), identifier(constraint.getName()),
// CONSTRAINT_TYPE // CONSTRAINT_TYPE
type, constraintType,
// TABLE_CATALOG // TABLE_CATALOG
catalog, catalog,
// TABLE_SCHEMA // TABLE_SCHEMA
...@@ -1731,13 +1731,13 @@ public class MetaTable extends Table { ...@@ -1731,13 +1731,13 @@ public class MetaTable extends Table {
} }
public ObjectArray<Index> getIndexes() { public ObjectArray<Index> getIndexes() {
if (index == null) { if (metaIndex == null) {
return null; return null;
} }
ObjectArray <Index>list = ObjectArray.newInstance(); ObjectArray <Index>list = ObjectArray.newInstance();
list.add(new MetaIndex(this, IndexColumn.wrap(columns), true)); list.add(new MetaIndex(this, IndexColumn.wrap(columns), true));
// TODO fixed scan index // TODO fixed scan index
list.add(index); list.add(metaIndex);
return list; return list;
} }
......
...@@ -78,7 +78,7 @@ public class RangeTable extends Table { ...@@ -78,7 +78,7 @@ public class RangeTable extends Table {
return false; return false;
} }
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, int headPos, String comment) throws SQLException { public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, int headPos, String indexComment) throws SQLException {
throw Message.getUnsupportedException("SYSTEM_RANGE"); throw Message.getUnsupportedException("SYSTEM_RANGE");
} }
......
...@@ -32,7 +32,7 @@ public class SingleColumnResolver implements ColumnResolver { ...@@ -32,7 +32,7 @@ public class SingleColumnResolver implements ColumnResolver {
this.value = value; this.value = value;
} }
public Value getValue(Column column) { public Value getValue(Column col) {
return value; return value;
} }
...@@ -56,7 +56,7 @@ public class SingleColumnResolver implements ColumnResolver { ...@@ -56,7 +56,7 @@ public class SingleColumnResolver implements ColumnResolver {
return null; return null;
} }
public Expression optimize(ExpressionColumn expressionColumn, Column column) { public Expression optimize(ExpressionColumn expressionColumn, Column col) {
return expressionColumn; return expressionColumn;
} }
......
...@@ -152,11 +152,11 @@ public abstract class Table extends SchemaObjectBase { ...@@ -152,11 +152,11 @@ public abstract class Table extends SchemaObjectBase {
* @param cols the index columns * @param cols the index columns
* @param indexType the index type * @param indexType the index type
* @param headPos the position of the head (if the index already exists) * @param headPos the position of the head (if the index already exists)
* @param comment the comment * @param indexComment the comment
* @return the index * @return the index
*/ */
public abstract Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, public abstract Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
int headPos, String comment) throws SQLException; int headPos, String indexComment) throws SQLException;
/** /**
* Remove a row from the table and all indexes. * Remove a row from the table and all indexes.
......
...@@ -111,30 +111,30 @@ public class TableFilter implements ColumnResolver { ...@@ -111,30 +111,30 @@ public class TableFilter implements ColumnResolver {
/** /**
* Lock the table. This will also lock joined tables. * Lock the table. This will also lock joined tables.
* *
* @param session the session * @param s the session
* @param exclusive true if an exclusive lock is required * @param exclusive true if an exclusive lock is required
* @param force lock even in the MVCC mode * @param force lock even in the MVCC mode
*/ */
public void lock(Session session, boolean exclusive, boolean force) throws SQLException { public void lock(Session s, boolean exclusive, boolean force) throws SQLException {
table.lock(session, exclusive, force); table.lock(s, exclusive, force);
if (join != null) { if (join != null) {
join.lock(session, exclusive, force); join.lock(s, exclusive, force);
} }
} }
/** /**
* Get the best plan item (index, cost) to use use for the current join order. * Get the best plan item (index, cost) to use use for the current join order.
* *
* @param session the session * @param s the session
* @param level 1 for the first table in a join, 2 for the second, and so on * @param level 1 for the first table in a join, 2 for the second, and so on
* @return the best plan item * @return the best plan item
*/ */
public PlanItem getBestPlanItem(Session session, int level) throws SQLException { public PlanItem getBestPlanItem(Session s, int level) throws SQLException {
PlanItem item; PlanItem item;
if (indexConditions.size() == 0) { if (indexConditions.size() == 0) {
item = new PlanItem(); item = new PlanItem();
item.setIndex(table.getScanIndex(session)); item.setIndex(table.getScanIndex(s));
item.cost = item.getIndex().getCost(session, null); item.cost = item.getIndex().getCost(s, null);
} else { } else {
int len = table.getColumns().length; int len = table.getColumns().length;
int[] masks = new int[len]; int[] masks = new int[len];
...@@ -148,7 +148,7 @@ public class TableFilter implements ColumnResolver { ...@@ -148,7 +148,7 @@ public class TableFilter implements ColumnResolver {
masks[id] |= condition.getMask(indexConditions.size()); masks[id] |= condition.getMask(indexConditions.size());
} }
} }
item = table.getBestPlanItem(session, masks); item = table.getBestPlanItem(s, masks);
// the more index conditions, the earlier the table // the more index conditions, the earlier the table
// to ensure joins without indexes are evaluated: // to ensure joins without indexes are evaluated:
// x (x.a=10); y (x.b=y.b) - see issue 113 // x (x.a=10); y (x.b=y.b) - see issue 113
...@@ -156,7 +156,7 @@ public class TableFilter implements ColumnResolver { ...@@ -156,7 +156,7 @@ public class TableFilter implements ColumnResolver {
} }
if (join != null) { if (join != null) {
setEvaluatable(join); setEvaluatable(join);
item.setJoinPlan(join.getBestPlanItem(session, level)); item.setJoinPlan(join.getBestPlanItem(s, level));
// TODO optimizer: calculate cost of a join: should use separate // TODO optimizer: calculate cost of a join: should use separate
// expected row number and lookup cost // expected row number and lookup cost
item.cost += item.cost * item.getJoinPlan().cost; item.cost += item.cost * item.getJoinPlan().cost;
...@@ -222,13 +222,13 @@ public class TableFilter implements ColumnResolver { ...@@ -222,13 +222,13 @@ public class TableFilter implements ColumnResolver {
/** /**
* Start the query. This will reset the scan counts. * Start the query. This will reset the scan counts.
* *
* @param session the session * @param s the session
*/ */
public void startQuery(Session session) { public void startQuery(Session s) {
this.session = session; this.session = s;
scanCount = 0; scanCount = 0;
if (join != null) { if (join != null) {
join.startQuery(session); join.startQuery(s);
} }
} }
...@@ -382,10 +382,10 @@ public class TableFilter implements ColumnResolver { ...@@ -382,10 +382,10 @@ public class TableFilter implements ColumnResolver {
* Add a filter condition. * Add a filter condition.
* *
* @param condition the condition * @param condition the condition
* @param join if this is in fact a join condition * @param isJoin if this is in fact a join condition
*/ */
public void addFilterCondition(Expression condition, boolean join) { public void addFilterCondition(Expression condition, boolean isJoin) {
if (join) { if (isJoin) {
if (joinCondition == null) { if (joinCondition == null) {
joinCondition = condition; joinCondition = condition;
} else { } else {
...@@ -460,12 +460,12 @@ public class TableFilter implements ColumnResolver { ...@@ -460,12 +460,12 @@ public class TableFilter implements ColumnResolver {
/** /**
* Get the query execution plan text to use for this table filter. * Get the query execution plan text to use for this table filter.
* *
* @param join if this is a joined table * @param isJoin if this is a joined table
* @return the SQL statement snippet * @return the SQL statement snippet
*/ */
public String getPlanSQL(boolean join) { public String getPlanSQL(boolean isJoin) {
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
if (join) { if (isJoin) {
if (outerJoin) { if (outerJoin) {
buff.append("LEFT OUTER JOIN "); buff.append("LEFT OUTER JOIN ");
} else { } else {
...@@ -490,7 +490,7 @@ public class TableFilter implements ColumnResolver { ...@@ -490,7 +490,7 @@ public class TableFilter implements ColumnResolver {
String plan = StringUtils.quoteRemarkSQL(planBuff.toString()); String plan = StringUtils.quoteRemarkSQL(planBuff.toString());
buff.append(plan).append(" */"); buff.append(plan).append(" */");
} }
if (join) { if (isJoin) {
buff.append(" ON "); buff.append(" ON ");
if (joinCondition == null) { if (joinCondition == null) {
// need to have a ON expression, otherwise the nesting is unclear // need to have a ON expression, otherwise the nesting is unclear
......
...@@ -23,7 +23,6 @@ import org.h2.index.LinkedIndex; ...@@ -23,7 +23,6 @@ import org.h2.index.LinkedIndex;
import org.h2.jdbc.JdbcSQLException; import org.h2.jdbc.JdbcSQLException;
import org.h2.log.UndoLogRecord; import org.h2.log.UndoLogRecord;
import org.h2.message.Message; import org.h2.message.Message;
import org.h2.message.Trace;
import org.h2.result.Row; import org.h2.result.Row;
import org.h2.result.RowList; import org.h2.result.RowList;
import org.h2.schema.Schema; import org.h2.schema.Schema;
...@@ -48,7 +47,7 @@ public class TableLink extends Table { ...@@ -48,7 +47,7 @@ public class TableLink extends Table {
private String driver, url, user, password, originalSchema, originalTable, qualifiedTableName; private String driver, url, user, password, originalSchema, originalTable, qualifiedTableName;
private TableLinkConnection conn; private TableLinkConnection conn;
private HashMap<String, PreparedStatement> prepared = New.hashMap(); private HashMap<String, PreparedStatement> preparedMap = New.hashMap();
private final ObjectArray<Index> indexes = ObjectArray.newInstance(); private final ObjectArray<Index> indexes = ObjectArray.newInstance();
private final boolean emitUpdates; private final boolean emitUpdates;
private LinkedIndex linkedIndex; private LinkedIndex linkedIndex;
...@@ -332,7 +331,7 @@ public class TableLink extends Table { ...@@ -332,7 +331,7 @@ public class TableLink extends Table {
} }
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
int headPos, String comment) throws SQLException { int headPos, String indexComment) throws SQLException {
throw Message.getUnsupportedException("LINK"); throw Message.getUnsupportedException("LINK");
} }
...@@ -413,20 +412,19 @@ public class TableLink extends Table { ...@@ -413,20 +412,19 @@ public class TableLink extends Table {
* @return the prepared statement * @return the prepared statement
*/ */
public PreparedStatement getPreparedStatement(String sql, boolean exclusive) throws SQLException { public PreparedStatement getPreparedStatement(String sql, boolean exclusive) throws SQLException {
Trace trace = database.getTrace(Trace.TABLE);
if (trace.isDebugEnabled()) { if (trace.isDebugEnabled()) {
trace.debug(getName() + ":\n" + sql); trace.debug(getName() + ":\n" + sql);
} }
if (conn == null) { if (conn == null) {
throw connectException; throw connectException;
} }
PreparedStatement prep = prepared.get(sql); PreparedStatement prep = preparedMap.get(sql);
if (prep == null) { if (prep == null) {
prep = conn.getConnection().prepareStatement(sql); prep = conn.getConnection().prepareStatement(sql);
prepared.put(sql, prep); preparedMap.put(sql, prep);
} }
if (exclusive) { if (exclusive) {
prepared.remove(sql); preparedMap.remove(sql);
} }
return prep; return prep;
} }
...@@ -465,7 +463,7 @@ public class TableLink extends Table { ...@@ -465,7 +463,7 @@ public class TableLink extends Table {
database.removeMeta(session, getId()); database.removeMeta(session, getId());
driver = null; driver = null;
url = user = password = originalTable = null; url = user = password = originalTable = null;
prepared = null; preparedMap = null;
invalidate(); invalidate();
} }
...@@ -536,7 +534,7 @@ public class TableLink extends Table { ...@@ -536,7 +534,7 @@ public class TableLink extends Table {
* @param sql the SQL statement * @param sql the SQL statement
*/ */
public void reusePreparedStatement(PreparedStatement prep, String sql) { public void reusePreparedStatement(PreparedStatement prep, String sql) {
prepared.put(sql, prep); preparedMap.put(sql, prep);
} }
public boolean isDeterministic() { public boolean isDeterministic() {
......
...@@ -200,7 +200,7 @@ public class TableView extends Table { ...@@ -200,7 +200,7 @@ public class TableView extends Table {
} }
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType, public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
int headPos, String comment) throws SQLException { int headPos, String indexComment) throws SQLException {
throw Message.getUnsupportedException("VIEW"); throw Message.getUnsupportedException("VIEW");
} }
...@@ -253,6 +253,10 @@ public class TableView extends Table { ...@@ -253,6 +253,10 @@ public class TableView extends Table {
return super.getSQL(); return super.getSQL();
} }
public String getQuery() {
return querySQL;
}
public Index getScanIndex(Session session) throws SQLException { public Index getScanIndex(Session session) throws SQLException {
if (createException != null) { if (createException != null) {
String msg = createException.getMessage(); String msg = createException.getMessage();
......
...@@ -25,8 +25,8 @@ import org.h2.util.Tool; ...@@ -25,8 +25,8 @@ import org.h2.util.Tool;
*/ */
public class ChangeFileEncryption extends Tool { public class ChangeFileEncryption extends Tool {
private String dir; private String directory;
private String cipher; private String cipherType;
private byte[] decrypt; private byte[] decrypt;
private byte[] encrypt; private byte[] encrypt;
...@@ -133,8 +133,8 @@ public class ChangeFileEncryption extends Tool { ...@@ -133,8 +133,8 @@ public class ChangeFileEncryption extends Tool {
} }
} }
change.out = out; change.out = out;
change.dir = dir; change.directory = dir;
change.cipher = cipher; change.cipherType = cipher;
change.decrypt = getFileEncryptionKey(decryptPassword); change.decrypt = getFileEncryptionKey(decryptPassword);
change.encrypt = getFileEncryptionKey(encryptPassword); change.encrypt = getFileEncryptionKey(encryptPassword);
...@@ -168,7 +168,7 @@ public class ChangeFileEncryption extends Tool { ...@@ -168,7 +168,7 @@ public class ChangeFileEncryption extends Tool {
if (decrypt == null) { if (decrypt == null) {
in = FileStore.open(null, fileName, "r"); in = FileStore.open(null, fileName, "r");
} else { } else {
in = FileStore.open(null, fileName, "r", cipher, decrypt); in = FileStore.open(null, fileName, "r", cipherType, decrypt);
} }
in.init(); in.init();
copy(fileName, in, encrypt); copy(fileName, in, encrypt);
...@@ -178,13 +178,13 @@ public class ChangeFileEncryption extends Tool { ...@@ -178,13 +178,13 @@ public class ChangeFileEncryption extends Tool {
if (FileUtils.isDirectory(fileName)) { if (FileUtils.isDirectory(fileName)) {
return; return;
} }
String temp = dir + "/temp.db"; String temp = directory + "/temp.db";
FileUtils.delete(temp); FileUtils.delete(temp);
FileStore fileOut; FileStore fileOut;
if (key == null) { if (key == null) {
fileOut = FileStore.open(null, temp, "rw"); fileOut = FileStore.open(null, temp, "rw");
} else { } else {
fileOut = FileStore.open(null, temp, "rw", cipher, key); fileOut = FileStore.open(null, temp, "rw", cipherType, key);
} }
fileOut.init(); fileOut.init();
byte[] buffer = new byte[4 * 1024]; byte[] buffer = new byte[4 * 1024];
......
...@@ -201,18 +201,18 @@ public class Recover extends Tool implements DataHandler { ...@@ -201,18 +201,18 @@ public class Recover extends Tool implements DataHandler {
return; return;
} }
setDatabaseName(fileName.substring(fileName.length() - Constants.SUFFIX_DATA_FILE.length())); setDatabaseName(fileName.substring(fileName.length() - Constants.SUFFIX_DATA_FILE.length()));
FileStore store = FileStore.open(null, fileName, "rw"); FileStore fileStore = FileStore.open(null, fileName, "rw");
long length = store.length(); long length = fileStore.length();
int offset = FileStore.HEADER_LENGTH; int offset = FileStore.HEADER_LENGTH;
int blockSize = DiskFile.BLOCK_SIZE; int blockSize = DiskFile.BLOCK_SIZE;
int blocks = (int) (length / blockSize); int blocks = (int) (length / blockSize);
blockCount = 1; blockCount = 1;
for (int block = 0; block < blocks; block += blockCount) { for (int b = 0; b < blocks; b += blockCount) {
store.seek(offset + (long) block * blockSize); fileStore.seek(offset + (long) b * blockSize);
byte[] bytes = new byte[blockSize]; byte[] bytes = new byte[blockSize];
DataPage s = DataPage.create(this, bytes); DataPage s = DataPage.create(this, bytes);
long start = store.getFilePointer(); long start = fileStore.getFilePointer();
store.readFully(bytes, 0, blockSize); fileStore.readFully(bytes, 0, blockSize);
blockCount = s.readInt(); blockCount = s.readInt();
setStorage(-1); setStorage(-1);
recordLength = -1; recordLength = -1;
...@@ -232,7 +232,7 @@ public class Recover extends Tool implements DataHandler { ...@@ -232,7 +232,7 @@ public class Recover extends Tool implements DataHandler {
continue; continue;
} }
if (blockCount > 1) { if (blockCount > 1) {
store.readFully(s.getBytes(), blockSize, blockCount * blockSize - blockSize); fileStore.readFully(s.getBytes(), blockSize, blockCount * blockSize - blockSize);
} }
try { try {
s.check(blockCount * blockSize); s.check(blockCount * blockSize);
...@@ -297,8 +297,8 @@ public class Recover extends Tool implements DataHandler { ...@@ -297,8 +297,8 @@ public class Recover extends Tool implements DataHandler {
System.arraycopy(replacement, 0, s.getBytes(), at, replacement.length); System.arraycopy(replacement, 0, s.getBytes(), at, replacement.length);
s.fill(blockCount * blockSize); s.fill(blockCount * blockSize);
s.updateChecksum(); s.updateChecksum();
store.seek(start); fileStore.seek(start);
store.write(s.getBytes(), 0, s.length()); fileStore.write(s.getBytes(), 0, s.length());
if (trace) { if (trace) {
out.println("User: " + userName); out.println("User: " + userName);
} }
...@@ -308,7 +308,7 @@ public class Recover extends Tool implements DataHandler { ...@@ -308,7 +308,7 @@ public class Recover extends Tool implements DataHandler {
} }
} }
} }
closeSilently(store); closeSilently(fileStore);
} }
/** /**
...@@ -377,15 +377,15 @@ public class Recover extends Tool implements DataHandler { ...@@ -377,15 +377,15 @@ public class Recover extends Tool implements DataHandler {
private void dumpLob(String fileName, boolean lobCompression) { private void dumpLob(String fileName, boolean lobCompression) {
OutputStream fileOut = null; OutputStream fileOut = null;
FileStore store = null; FileStore fileStore = null;
int size = 0; int size = 0;
String n = fileName + (lobCompression ? ".comp" : "") + ".txt"; String n = fileName + (lobCompression ? ".comp" : "") + ".txt";
InputStream in = null; InputStream in = null;
try { try {
fileOut = FileUtils.openFileOutputStream(n, false); fileOut = FileUtils.openFileOutputStream(n, false);
store = FileStore.open(null, fileName, "r"); fileStore = FileStore.open(null, fileName, "r");
store.init(); fileStore.init();
in = new BufferedInputStream(new FileStoreInputStream(store, this, lobCompression, false)); in = new BufferedInputStream(new FileStoreInputStream(fileStore, this, lobCompression, false));
byte[] buffer = new byte[Constants.IO_BUFFER_SIZE]; byte[] buffer = new byte[Constants.IO_BUFFER_SIZE];
while (true) { while (true) {
int l = in.read(buffer); int l = in.read(buffer);
...@@ -402,7 +402,7 @@ public class Recover extends Tool implements DataHandler { ...@@ -402,7 +402,7 @@ public class Recover extends Tool implements DataHandler {
} finally { } finally {
IOUtils.closeSilently(fileOut); IOUtils.closeSilently(fileOut);
IOUtils.closeSilently(in); IOUtils.closeSilently(in);
closeSilently(store); closeSilently(fileStore);
} }
if (size == 0) { if (size == 0) {
try { try {
...@@ -488,7 +488,7 @@ public class Recover extends Tool implements DataHandler { ...@@ -488,7 +488,7 @@ public class Recover extends Tool implements DataHandler {
private void dumpLog(String fileName, boolean onlySetSessionState) { private void dumpLog(String fileName, boolean onlySetSessionState) {
PrintWriter writer = null; PrintWriter writer = null;
FileStore store = null; FileStore fileStore = null;
boolean containsUncommitted = false; boolean containsUncommitted = false;
try { try {
if (onlySetSessionState) { if (onlySetSessionState) {
...@@ -498,8 +498,8 @@ public class Recover extends Tool implements DataHandler { ...@@ -498,8 +498,8 @@ public class Recover extends Tool implements DataHandler {
if (!onlySetSessionState) { if (!onlySetSessionState) {
writer = getWriter(fileName, ".txt"); writer = getWriter(fileName, ".txt");
} }
store = FileStore.open(null, fileName, "r"); fileStore = FileStore.open(null, fileName, "r");
long length = store.length(); long length = fileStore.length();
if (!onlySetSessionState) { if (!onlySetSessionState) {
writer.println("// length: " + length); writer.println("// length: " + length);
} }
...@@ -518,8 +518,8 @@ public class Recover extends Tool implements DataHandler { ...@@ -518,8 +518,8 @@ public class Recover extends Tool implements DataHandler {
} }
return; return;
} }
store.seek(offset); fileStore.seek(offset);
store.readFully(s.getBytes(), 0, len); fileStore.readFully(s.getBytes(), 0, len);
int id = s.readInt(); int id = s.readInt();
int firstUncommittedPos = s.readInt(); int firstUncommittedPos = s.readInt();
int firstUnwrittenPos = s.readInt(); int firstUnwrittenPos = s.readInt();
...@@ -531,12 +531,12 @@ public class Recover extends Tool implements DataHandler { ...@@ -531,12 +531,12 @@ public class Recover extends Tool implements DataHandler {
writer.println("// max: " + max); writer.println("// max: " + max);
} }
while (true) { while (true) {
int pos = (int) (store.getFilePointer() / blockSize); int pos = (int) (fileStore.getFilePointer() / blockSize);
if ((long) pos * blockSize >= length) { if ((long) pos * blockSize >= length) {
break; break;
} }
buff = new byte[blockSize]; buff = new byte[blockSize];
store.readFully(buff, 0, blockSize); fileStore.readFully(buff, 0, blockSize);
s = DataPage.create(this, buff); s = DataPage.create(this, buff);
// Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE // Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
blocks = MathUtils.convertLongToInt(Math.abs(s.readInt())); blocks = MathUtils.convertLongToInt(Math.abs(s.readInt()));
...@@ -545,7 +545,7 @@ public class Recover extends Tool implements DataHandler { ...@@ -545,7 +545,7 @@ public class Recover extends Tool implements DataHandler {
System.arraycopy(buff, 0, b2, 0, blockSize); System.arraycopy(buff, 0, b2, 0, blockSize);
buff = b2; buff = b2;
try { try {
store.readFully(buff, blockSize, blocks * blockSize - blockSize); fileStore.readFully(buff, blockSize, blocks * blockSize - blockSize);
} catch (SQLException e) { } catch (SQLException e) {
break; break;
} }
...@@ -656,7 +656,7 @@ public class Recover extends Tool implements DataHandler { ...@@ -656,7 +656,7 @@ public class Recover extends Tool implements DataHandler {
writeError(writer, e); writeError(writer, e);
} finally { } finally {
IOUtils.closeSilently(writer); IOUtils.closeSilently(writer);
closeSilently(store); closeSilently(fileStore);
} }
} }
...@@ -1554,25 +1554,25 @@ public class Recover extends Tool implements DataHandler { ...@@ -1554,25 +1554,25 @@ public class Recover extends Tool implements DataHandler {
private void dumpData(String fileName, String outputName, int offset) { private void dumpData(String fileName, String outputName, int offset) {
PrintWriter writer = null; PrintWriter writer = null;
FileStore store = null; FileStore fileStore = null;
try { try {
writer = getWriter(outputName, ".sql"); writer = getWriter(outputName, ".sql");
writer.println("CREATE ALIAS IF NOT EXISTS READ_CLOB FOR \"" + this.getClass().getName() + ".readClob\";"); writer.println("CREATE ALIAS IF NOT EXISTS READ_CLOB FOR \"" + this.getClass().getName() + ".readClob\";");
writer.println("CREATE ALIAS IF NOT EXISTS READ_BLOB FOR \"" + this.getClass().getName() + ".readBlob\";"); writer.println("CREATE ALIAS IF NOT EXISTS READ_BLOB FOR \"" + this.getClass().getName() + ".readBlob\";");
resetSchema(); resetSchema();
store = FileStore.open(null, fileName, "r"); fileStore = FileStore.open(null, fileName, "r");
long length = store.length(); long length = fileStore.length();
int blockSize = DiskFile.BLOCK_SIZE; int blockSize = DiskFile.BLOCK_SIZE;
int blocks = (int) (length / blockSize); int blocks = (int) (length / blockSize);
blockCount = 1; blockCount = 1;
int pageCount = blocks / DiskFile.BLOCKS_PER_PAGE; int pageCount = blocks / DiskFile.BLOCKS_PER_PAGE;
int[] pageOwners = new int[pageCount + 1]; int[] pageOwners = new int[pageCount + 1];
for (block = 0; block < blocks; block += blockCount) { for (block = 0; block < blocks; block += blockCount) {
store.seek(offset + (long) block * blockSize); fileStore.seek(offset + (long) block * blockSize);
byte[] buff = new byte[blockSize]; byte[] buff = new byte[blockSize];
DataPage s = DataPage.create(this, buff); DataPage s = DataPage.create(this, buff);
try { try {
store.readFully(buff, 0, blockSize); fileStore.readFully(buff, 0, blockSize);
} catch (SQLException e) { } catch (SQLException e) {
writer.println("-- ERROR: can not read: " + e); writer.println("-- ERROR: can not read: " + e);
break; break;
...@@ -1609,11 +1609,11 @@ public class Recover extends Tool implements DataHandler { ...@@ -1609,11 +1609,11 @@ public class Recover extends Tool implements DataHandler {
continue; continue;
} }
try { try {
store.readFully(s.getBytes(), blockSize, blockCount * blockSize - blockSize); fileStore.readFully(s.getBytes(), blockSize, blockCount * blockSize - blockSize);
} catch (Throwable e) { } catch (Throwable e) {
writeDataError(writer, "eof", s.getBytes(), 1); writeDataError(writer, "eof", s.getBytes(), 1);
blockCount = 1; blockCount = 1;
store = FileStore.open(null, fileName, "r"); fileStore = FileStore.open(null, fileName, "r");
continue; continue;
} }
} }
...@@ -1648,7 +1648,7 @@ public class Recover extends Tool implements DataHandler { ...@@ -1648,7 +1648,7 @@ public class Recover extends Tool implements DataHandler {
writeError(writer, e); writeError(writer, e);
} finally { } finally {
IOUtils.closeSilently(writer); IOUtils.closeSilently(writer);
closeSilently(store); closeSilently(fileStore);
} }
} }
...@@ -1730,9 +1730,9 @@ public class Recover extends Tool implements DataHandler { ...@@ -1730,9 +1730,9 @@ public class Recover extends Tool implements DataHandler {
} }
private void closeSilently(FileStore store) { private void closeSilently(FileStore fileStore) {
if (store != null) { if (fileStore != null) {
store.closeSilently(); fileStore.closeSilently();
} }
} }
......
...@@ -174,13 +174,13 @@ public class Restore extends Tool { ...@@ -174,13 +174,13 @@ public class Restore extends Tool {
copy = true; copy = true;
} }
if (copy) { if (copy) {
OutputStream out = null; OutputStream o = null;
try { try {
out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); o = FileUtils.openFileOutputStream(directory + File.separator + fileName, false);
IOUtils.copy(zipIn, out); IOUtils.copy(zipIn, o);
out.close(); o.close();
} finally { } finally {
IOUtils.closeSilently(out); IOUtils.closeSilently(o);
} }
} }
zipIn.closeEntry(); zipIn.closeEntry();
......
...@@ -150,12 +150,12 @@ public class Script extends Tool { ...@@ -150,12 +150,12 @@ public class Script extends Tool {
* @param fileName the script file * @param fileName the script file
*/ */
void process(String url, String user, String password, String fileName) throws SQLException { void process(String url, String user, String password, String fileName) throws SQLException {
OutputStream out = null; OutputStream o = null;
try { try {
out = FileUtils.openFileOutputStream(fileName, false); o = FileUtils.openFileOutputStream(fileName, false);
process(url, user, password, out); process(url, user, password, o);
} finally { } finally {
IOUtils.closeSilently(out); IOUtils.closeSilently(o);
} }
} }
...@@ -165,16 +165,16 @@ public class Script extends Tool { ...@@ -165,16 +165,16 @@ public class Script extends Tool {
* @param url the database URL * @param url the database URL
* @param user the user name * @param user the user name
* @param password the password * @param password the password
* @param out the output stream * @param o the output stream
*/ */
void process(String url, String user, String password, OutputStream out) throws SQLException { void process(String url, String user, String password, OutputStream o) throws SQLException {
Connection conn = null; Connection conn = null;
Statement stat = null; Statement stat = null;
try { try {
org.h2.Driver.load(); org.h2.Driver.load();
conn = DriverManager.getConnection(url, user, password); conn = DriverManager.getConnection(url, user, password);
stat = conn.createStatement(); stat = conn.createStatement();
PrintWriter writer = new PrintWriter(IOUtils.getWriter(out)); PrintWriter writer = new PrintWriter(IOUtils.getWriter(o));
ResultSet rs = stat.executeQuery("SCRIPT"); ResultSet rs = stat.executeQuery("SCRIPT");
while (rs.next()) { while (rs.next()) {
String s = rs.getString(1); String s = rs.getString(1);
......
...@@ -476,7 +476,7 @@ public class Shell extends Tool { ...@@ -476,7 +476,7 @@ public class Shell extends Tool {
} }
} }
private int printResult(ResultSet rs, boolean listMode) throws SQLException { private int printResult(ResultSet rs, boolean asList) throws SQLException {
ResultSetMetaData meta = rs.getMetaData(); ResultSetMetaData meta = rs.getMetaData();
int longest = 0; int longest = 0;
int len = meta.getColumnCount(); int len = meta.getColumnCount();
...@@ -486,7 +486,7 @@ public class Shell extends Tool { ...@@ -486,7 +486,7 @@ public class Shell extends Tool {
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
String s = meta.getColumnLabel(i + 1); String s = meta.getColumnLabel(i + 1);
int l = s.length(); int l = s.length();
if (!listMode) { if (!asList) {
l = Math.max(l, meta.getColumnDisplaySize(i + 1)); l = Math.max(l, meta.getColumnDisplaySize(i + 1));
l = Math.min(maxColumnSize, l); l = Math.min(maxColumnSize, l);
} }
...@@ -499,7 +499,7 @@ public class Shell extends Tool { ...@@ -499,7 +499,7 @@ public class Shell extends Tool {
total += l; total += l;
} }
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
if (!listMode) { if (!asList) {
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
if (i > 0) { if (i > 0) {
buff.append(boxVertical); buff.append(boxVertical);
...@@ -519,7 +519,7 @@ public class Shell extends Tool { ...@@ -519,7 +519,7 @@ public class Shell extends Tool {
while (rs.next()) { while (rs.next()) {
rowCount++; rowCount++;
buff.setLength(0); buff.setLength(0);
if (listMode) { if (asList) {
if (rowCount > 1) { if (rowCount > 1) {
println(""); println("");
} }
...@@ -545,7 +545,7 @@ public class Shell extends Tool { ...@@ -545,7 +545,7 @@ public class Shell extends Tool {
} }
int m = columnSizes[i]; int m = columnSizes[i];
// only truncate if more than once column // only truncate if more than once column
if (len > 1 && !listMode && s.length() > m) { if (len > 1 && !asList && s.length() > m) {
s = s.substring(0, m); s = s.substring(0, m);
truncated = true; truncated = true;
} }
...@@ -559,7 +559,7 @@ public class Shell extends Tool { ...@@ -559,7 +559,7 @@ public class Shell extends Tool {
} }
println(buff.toString()); println(buff.toString());
} }
if (rowCount == 0 && listMode) { if (rowCount == 0 && asList) {
for (String label : columns) { for (String label : columns) {
buff.append(label).append('\n'); buff.append(label).append('\n');
} }
......
...@@ -1101,7 +1101,7 @@ public class SimpleResultSet implements ResultSet, ResultSetMetaData { ...@@ -1101,7 +1101,7 @@ public class SimpleResultSet implements ResultSet, ResultSetMetaData {
/** /**
* INTERNAL * INTERNAL
*/ */
public boolean relative(int rows) throws SQLException { public boolean relative(int offset) throws SQLException {
throw getUnsupportedException(); throw getUnsupportedException();
} }
......
...@@ -75,7 +75,7 @@ public class CacheLRU implements Cache { ...@@ -75,7 +75,7 @@ public class CacheLRU implements Cache {
} }
public void clear() { public void clear() {
head.next = head.previous = head; head.cacheNext = head.cachePrevious = head;
// first set to null - avoiding out of memory // first set to null - avoiding out of memory
values = null; values = null;
values = new CacheObject[len]; values = new CacheObject[len];
...@@ -94,7 +94,7 @@ public class CacheLRU implements Cache { ...@@ -94,7 +94,7 @@ public class CacheLRU implements Cache {
} }
} }
int index = rec.getPos() & mask; int index = rec.getPos() & mask;
rec.chained = values[index]; rec.cacheChained = values[index];
values[index] = rec; values[index] = rec;
recordCount++; recordCount++;
sizeMemory += rec.getMemorySize(); sizeMemory += rec.getMemorySize();
...@@ -131,10 +131,10 @@ public class CacheLRU implements Cache { ...@@ -131,10 +131,10 @@ public class CacheLRU implements Cache {
int mem = sizeMemory; int mem = sizeMemory;
int rc = recordCount; int rc = recordCount;
boolean flushed = false; boolean flushed = false;
CacheObject next = head.next; CacheObject next = head.cacheNext;
while (mem * 4 > maxSize * 3 && rc > Constants.CACHE_MIN_RECORDS) { while (mem * 4 > maxSize * 3 && rc > Constants.CACHE_MIN_RECORDS) {
CacheObject check = next; CacheObject check = next;
next = check.next; next = check.cacheNext;
i++; i++;
if (i >= recordCount) { if (i >= recordCount) {
if (!flushed) { if (!flushed) {
...@@ -185,7 +185,7 @@ public class CacheLRU implements Cache { ...@@ -185,7 +185,7 @@ public class CacheLRU implements Cache {
CacheObject rec = changed.get(i); CacheObject rec = changed.get(i);
remove(rec.getPos()); remove(rec.getPos());
if (SysProperties.CHECK) { if (SysProperties.CHECK) {
if (rec.next != null) { if (rec.cacheNext != null) {
throw Message.throwInternalError(); throw Message.throwInternalError();
} }
} }
...@@ -197,22 +197,22 @@ public class CacheLRU implements Cache { ...@@ -197,22 +197,22 @@ public class CacheLRU implements Cache {
if (SysProperties.CHECK && rec == head) { if (SysProperties.CHECK && rec == head) {
Message.throwInternalError("try to move head"); Message.throwInternalError("try to move head");
} }
rec.next = head; rec.cacheNext = head;
rec.previous = head.previous; rec.cachePrevious = head.cachePrevious;
rec.previous.next = rec; rec.cachePrevious.cacheNext = rec;
head.previous = rec; head.cachePrevious = rec;
} }
private void removeFromLinkedList(CacheObject rec) { private void removeFromLinkedList(CacheObject rec) {
if (SysProperties.CHECK && rec == head) { if (SysProperties.CHECK && rec == head) {
Message.throwInternalError("try to remove head"); Message.throwInternalError("try to remove head");
} }
rec.previous.next = rec.next; rec.cachePrevious.cacheNext = rec.cacheNext;
rec.next.previous = rec.previous; rec.cacheNext.cachePrevious = rec.cachePrevious;
// TODO cache: mystery: why is this required? needs more memory if we // TODO cache: mystery: why is this required? needs more memory if we
// don't do this // don't do this
rec.next = null; rec.cacheNext = null;
rec.previous = null; rec.cachePrevious = null;
} }
public void remove(int pos) { public void remove(int pos) {
...@@ -222,23 +222,23 @@ public class CacheLRU implements Cache { ...@@ -222,23 +222,23 @@ public class CacheLRU implements Cache {
return; return;
} }
if (rec.getPos() == pos) { if (rec.getPos() == pos) {
values[index] = rec.chained; values[index] = rec.cacheChained;
} else { } else {
CacheObject last; CacheObject last;
do { do {
last = rec; last = rec;
rec = rec.chained; rec = rec.cacheChained;
if (rec == null) { if (rec == null) {
return; return;
} }
} while (rec.getPos() != pos); } while (rec.getPos() != pos);
last.chained = rec.chained; last.cacheChained = rec.cacheChained;
} }
recordCount--; recordCount--;
sizeMemory -= rec.getMemorySize(); sizeMemory -= rec.getMemorySize();
removeFromLinkedList(rec); removeFromLinkedList(rec);
if (SysProperties.CHECK) { if (SysProperties.CHECK) {
rec.chained = null; rec.cacheChained = null;
CacheObject o = find(pos); CacheObject o = find(pos);
if (o != null) { if (o != null) {
Message.throwInternalError("not removed: " + o); Message.throwInternalError("not removed: " + o);
...@@ -249,7 +249,7 @@ public class CacheLRU implements Cache { ...@@ -249,7 +249,7 @@ public class CacheLRU implements Cache {
public CacheObject find(int pos) { public CacheObject find(int pos) {
CacheObject rec = values[pos & mask]; CacheObject rec = values[pos & mask];
while (rec != null && rec.getPos() != pos) { while (rec != null && rec.getPos() != pos) {
rec = rec.chained; rec = rec.cacheChained;
} }
return rec; return rec;
} }
...@@ -297,12 +297,12 @@ public class CacheLRU implements Cache { ...@@ -297,12 +297,12 @@ public class CacheLRU implements Cache {
// testConsistency(); // testConsistency();
// } // }
ObjectArray<CacheObject> list = ObjectArray.newInstance(); ObjectArray<CacheObject> list = ObjectArray.newInstance();
CacheObject rec = head.next; CacheObject rec = head.cacheNext;
while (rec != head) { while (rec != head) {
if (rec.isChanged()) { if (rec.isChanged()) {
list.add(rec); list.add(rec);
} }
rec = rec.next; rec = rec.cacheNext;
} }
return list; return list;
} }
......
...@@ -39,18 +39,18 @@ public abstract class CacheObject { ...@@ -39,18 +39,18 @@ public abstract class CacheObject {
* The previous element in the LRU linked list. If the previous element is * The previous element in the LRU linked list. If the previous element is
* the head, then this element is the most recently used object. * the head, then this element is the most recently used object.
*/ */
public CacheObject previous; public CacheObject cachePrevious;
/** /**
* The next element in the LRU linked list. If the next element is the head, * The next element in the LRU linked list. If the next element is the head,
* then this element is the least recently used object. * then this element is the least recently used object.
*/ */
public CacheObject next; public CacheObject cacheNext;
/** /**
* The next element in the hash chain. * The next element in the hash chain.
*/ */
public CacheObject chained; public CacheObject cacheChained;
/** /**
* The cache queue identifier. This field is only used for the 2Q cache * The cache queue identifier. This field is only used for the 2Q cache
...@@ -92,7 +92,7 @@ public abstract class CacheObject { ...@@ -92,7 +92,7 @@ public abstract class CacheObject {
} }
public void setPos(int pos) { public void setPos(int pos) {
if (SysProperties.CHECK && (previous != null || next != null || chained != null)) { if (SysProperties.CHECK && (cachePrevious != null || cacheNext != null || cacheChained != null)) {
Message.throwInternalError("setPos too late"); Message.throwInternalError("setPos too late");
} }
this.pos = pos; this.pos = pos;
......
...@@ -27,7 +27,7 @@ import org.h2.security.SecureSocketFactory; ...@@ -27,7 +27,7 @@ import org.h2.security.SecureSocketFactory;
public class NetUtils { public class NetUtils {
private static final int CACHE_MILLIS = 1000; private static final int CACHE_MILLIS = 1000;
private static InetAddress bindAddress; private static InetAddress cachedBindAddress;
private static String cachedLocalAddress; private static String cachedLocalAddress;
private static long cachedLocalAddressTime; private static long cachedLocalAddressTime;
...@@ -140,11 +140,11 @@ public class NetUtils { ...@@ -140,11 +140,11 @@ public class NetUtils {
return null; return null;
} }
synchronized (NetUtils.class) { synchronized (NetUtils.class) {
if (bindAddress == null) { if (cachedBindAddress == null) {
bindAddress = InetAddress.getByName(host); cachedBindAddress = InetAddress.getByName(host);
} }
} }
return bindAddress; return cachedBindAddress;
} }
private static ServerSocket createServerSocketTry(int port, boolean ssl) throws SQLException { private static ServerSocket createServerSocketTry(int port, boolean ssl) throws SQLException {
......
...@@ -66,20 +66,20 @@ public class SourceCompiler { ...@@ -66,20 +66,20 @@ public class SourceCompiler {
/** /**
* Get the class object for the given name. * Get the class object for the given name.
* *
* @param name the class name * @param packageAndClassName the class name
* @return the class * @return the class
*/ */
private Class< ? > getClass(String name) throws ClassNotFoundException { private Class< ? > getClass(String packageAndClassName) throws ClassNotFoundException {
Class< ? > clazz = compiled.get(name); Class< ? > compiledClass = compiled.get(packageAndClassName);
if (clazz != null) { if (compiledClass != null) {
return clazz; return compiledClass;
} }
ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) { ClassLoader classLoader = new ClassLoader(getClass().getClassLoader()) {
public Class< ? > findClass(String name) throws ClassNotFoundException { public Class< ? > findClass(String name) throws ClassNotFoundException {
Class< ? > clazz = compiled.get(name); Class< ? > classInstance = compiled.get(name);
if (clazz == null) { if (classInstance == null) {
String source = sources.get(name); String source = sources.get(name);
String packageName = null; String packageName = null;
int idx = name.lastIndexOf('.'); int idx = name.lastIndexOf('.');
...@@ -92,16 +92,16 @@ public class SourceCompiler { ...@@ -92,16 +92,16 @@ public class SourceCompiler {
} }
byte[] data = javacCompile(packageName, className, source); byte[] data = javacCompile(packageName, className, source);
if (data == null) { if (data == null) {
clazz = findSystemClass(name); classInstance = findSystemClass(name);
} else { } else {
clazz = defineClass(name, data, 0, data.length); classInstance = defineClass(name, data, 0, data.length);
compiled.put(name, clazz); compiled.put(name, classInstance);
} }
} }
return clazz; return classInstance;
} }
}; };
return classLoader.loadClass(name); return classLoader.loadClass(packageAndClassName);
} }
/** /**
......
...@@ -12,7 +12,6 @@ import java.io.BufferedWriter; ...@@ -12,7 +12,6 @@ import java.io.BufferedWriter;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
...@@ -25,7 +24,6 @@ import java.sql.ResultSetMetaData; ...@@ -25,7 +24,6 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Time; import java.sql.Time;
import java.sql.Timestamp; import java.sql.Timestamp;
import org.h2.constant.ErrorCode; import org.h2.constant.ErrorCode;
import org.h2.engine.Constants; import org.h2.engine.Constants;
import org.h2.engine.SessionInterface; import org.h2.engine.SessionInterface;
...@@ -364,8 +362,7 @@ public class Transfer { ...@@ -364,8 +362,7 @@ public class Transfer {
throw Message.getSQLException(ErrorCode.CONNECTION_BROKEN_1, "length=" + length); throw Message.getSQLException(ErrorCode.CONNECTION_BROKEN_1, "length=" + length);
} }
writeLong(length); writeLong(length);
InputStream in = v.getInputStream(); long written = IOUtils.copyAndCloseInput(v.getInputStream(), out);
long written = IOUtils.copyAndCloseInput(in, out);
if (written != length) { if (written != length) {
throw Message.getSQLException(ErrorCode.CONNECTION_BROKEN_1, "length:" + length + " written:" + written); throw Message.getSQLException(ErrorCode.CONNECTION_BROKEN_1, "length:" + length + " written:" + written);
} }
...@@ -564,9 +561,9 @@ public class Transfer { ...@@ -564,9 +561,9 @@ public class Transfer {
public Transfer openNewConnection() throws IOException { public Transfer openNewConnection() throws IOException {
InetAddress address = socket.getInetAddress(); InetAddress address = socket.getInetAddress();
int port = socket.getPort(); int port = socket.getPort();
Socket socket = NetUtils.createSocket(address, port, ssl); Socket s2 = NetUtils.createSocket(address, port, ssl);
Transfer trans = new Transfer(null); Transfer trans = new Transfer(null);
trans.setSocket(socket); trans.setSocket(s2);
trans.setSSL(ssl); trans.setSSL(ssl);
return trans; return trans;
} }
......
...@@ -43,11 +43,11 @@ public class ValueByte extends Value { ...@@ -43,11 +43,11 @@ public class ValueByte extends Value {
return ValueByte.get((byte) (value + other.value)); return ValueByte.get((byte) (value + other.value));
} }
private ValueByte checkRange(int value) throws SQLException { private ValueByte checkRange(int x) throws SQLException {
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { if (x < Byte.MIN_VALUE || x > Byte.MAX_VALUE) {
throw Message.getSQLException(ErrorCode.OVERFLOW_FOR_TYPE_1, DataType.getDataType(Value.BYTE).name); throw Message.getSQLException(ErrorCode.OVERFLOW_FOR_TYPE_1, DataType.getDataType(Value.BYTE).name);
} }
return ValueByte.get((byte) value); return ValueByte.get((byte) x);
} }
public int getSignum() { public int getSignum() {
......
...@@ -140,11 +140,11 @@ public class ValueDecimal extends Value { ...@@ -140,11 +140,11 @@ public class ValueDecimal extends Value {
return precision; return precision;
} }
public boolean checkPrecision(long precision) { public boolean checkPrecision(long prec) {
if (precision == DEFAULT_PRECISION) { if (prec == DEFAULT_PRECISION) {
return true; return true;
} }
return getPrecision() <= precision; return getPrecision() <= prec;
} }
public int getScale() { public int getScale() {
...@@ -176,11 +176,11 @@ public class ValueDecimal extends Value { ...@@ -176,11 +176,11 @@ public class ValueDecimal extends Value {
return ValueDecimal.get(bd); return ValueDecimal.get(bd);
} }
public Value convertPrecision(long precision) throws SQLException { public Value convertPrecision(long newPrecision) throws SQLException {
if (getPrecision() <= precision) { if (getPrecision() <= newPrecision) {
return this; return this;
} }
throw Message.getSQLException(ErrorCode.VALUE_TOO_LARGE_FOR_PRECISION_1, "" + precision); throw Message.getSQLException(ErrorCode.VALUE_TOO_LARGE_FOR_PRECISION_1, "" + newPrecision);
} }
/** /**
......
...@@ -73,11 +73,11 @@ public class ValueInt extends Value { ...@@ -73,11 +73,11 @@ public class ValueInt extends Value {
return ValueInt.get(value + other.value); return ValueInt.get(value + other.value);
} }
private ValueInt checkRange(long value) throws SQLException { private ValueInt checkRange(long x) throws SQLException {
if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { if (x < Integer.MIN_VALUE || x > Integer.MAX_VALUE) {
throw Message.getSQLException(ErrorCode.OVERFLOW_FOR_TYPE_1, DataType.getDataType(Value.INT).name); throw Message.getSQLException(ErrorCode.OVERFLOW_FOR_TYPE_1, DataType.getDataType(Value.INT).name);
} }
return ValueInt.get((int) value); return ValueInt.get((int) x);
} }
public int getSignum() { public int getSignum() {
......
...@@ -205,10 +205,10 @@ public class ValueLob extends Value { ...@@ -205,10 +205,10 @@ public class ValueLob extends Value {
return (int) m; return (int) m;
} }
private void createFromReader(char[] buff, int len, Reader in, long remaining, DataHandler handler) throws SQLException { private void createFromReader(char[] buff, int len, Reader in, long remaining, DataHandler h) throws SQLException {
try { try {
FileStoreOutputStream out = initLarge(handler); FileStoreOutputStream out = initLarge(h);
boolean compress = handler.getLobCompressionAlgorithm(Value.CLOB) != null; boolean compress = h.getLobCompressionAlgorithm(Value.CLOB) != null;
try { try {
while (true) { while (true) {
precision += len; precision += len;
...@@ -218,7 +218,7 @@ public class ValueLob extends Value { ...@@ -218,7 +218,7 @@ public class ValueLob extends Value {
if (remaining <= 0) { if (remaining <= 0) {
break; break;
} }
len = getBufferSize(handler, compress, remaining); len = getBufferSize(h, compress, remaining);
len = IOUtils.readFully(in, buff, len); len = IOUtils.readFully(in, buff, len);
if (len <= 0) { if (len <= 0) {
break; break;
...@@ -250,13 +250,13 @@ public class ValueLob extends Value { ...@@ -250,13 +250,13 @@ public class ValueLob extends Value {
return name; return name;
} }
private int getNewObjectId(DataHandler handler) throws SQLException { private int getNewObjectId(DataHandler h) throws SQLException {
String path = handler.getDatabasePath(); String path = h.getDatabasePath();
int objectId = 0; int newId = 0;
int lobsPerDir = SysProperties.LOB_FILES_PER_DIRECTORY; int lobsPerDir = SysProperties.LOB_FILES_PER_DIRECTORY;
while (true) { while (true) {
String dir = getFileNamePrefix(path, objectId); String dir = getFileNamePrefix(path, newId);
String[] list = getFileList(handler, dir); String[] list = getFileList(h, dir);
int fileCount = 0; int fileCount = 0;
boolean[] used = new boolean[lobsPerDir]; boolean[] used = new boolean[lobsPerDir];
for (String name : list) { for (String name : list) {
...@@ -285,13 +285,13 @@ public class ValueLob extends Value { ...@@ -285,13 +285,13 @@ public class ValueLob extends Value {
} }
} }
if (fileId > 0) { if (fileId > 0) {
objectId += fileId; newId += fileId;
invalidateFileList(handler, dir); invalidateFileList(h, dir);
break; break;
} }
if (objectId > Integer.MAX_VALUE / lobsPerDir) { if (newId > Integer.MAX_VALUE / lobsPerDir) {
// this directory path is full: start from zero // this directory path is full: start from zero
objectId = 0; newId = 0;
dirCounter = RandomUtils.nextInt(lobsPerDir - 1) * lobsPerDir; dirCounter = RandomUtils.nextInt(lobsPerDir - 1) * lobsPerDir;
} else { } else {
// calculate the directory // calculate the directory
...@@ -300,11 +300,11 @@ public class ValueLob extends Value { ...@@ -300,11 +300,11 @@ public class ValueLob extends Value {
// (but that would generate more directories): // (but that would generate more directories):
// int dirId = RandomUtils.nextInt(lobsPerDir - 1) + 1; // int dirId = RandomUtils.nextInt(lobsPerDir - 1) + 1;
int dirId = (dirCounter++ / (lobsPerDir - 1)) + 1; int dirId = (dirCounter++ / (lobsPerDir - 1)) + 1;
objectId = objectId * lobsPerDir; newId = newId * lobsPerDir;
objectId += dirId * lobsPerDir; newId += dirId * lobsPerDir;
} }
} }
return objectId; return newId;
} }
/** /**
...@@ -315,8 +315,8 @@ public class ValueLob extends Value { ...@@ -315,8 +315,8 @@ public class ValueLob extends Value {
dirCounter = 0; dirCounter = 0;
} }
private void invalidateFileList(DataHandler handler, String dir) { private void invalidateFileList(DataHandler h, String dir) {
SmallLRUCache<String, String[]> cache = handler.getLobFileListCache(); SmallLRUCache<String, String[]> cache = h.getLobFileListCache();
if (cache != null) { if (cache != null) {
synchronized (cache) { synchronized (cache) {
cache.remove(dir); cache.remove(dir);
...@@ -324,8 +324,8 @@ public class ValueLob extends Value { ...@@ -324,8 +324,8 @@ public class ValueLob extends Value {
} }
} }
private String[] getFileList(DataHandler handler, String dir) throws SQLException { private String[] getFileList(DataHandler h, String dir) throws SQLException {
SmallLRUCache<String, String[]> cache = handler.getLobFileListCache(); SmallLRUCache<String, String[]> cache = h.getLobFileListCache();
String[] list; String[] list;
if (cache == null) { if (cache == null) {
list = FileUtils.listFiles(dir); list = FileUtils.listFiles(dir);
...@@ -378,35 +378,35 @@ public class ValueLob extends Value { ...@@ -378,35 +378,35 @@ public class ValueLob extends Value {
} }
} }
private FileStoreOutputStream initLarge(DataHandler handler) throws SQLException { private FileStoreOutputStream initLarge(DataHandler h) throws SQLException {
this.handler = handler; this.handler = h;
this.tableId = 0; this.tableId = 0;
this.linked = false; this.linked = false;
this.precision = 0; this.precision = 0;
this.small = null; this.small = null;
this.hash = 0; this.hash = 0;
String compressionAlgorithm = handler.getLobCompressionAlgorithm(type); String compressionAlgorithm = h.getLobCompressionAlgorithm(type);
this.compression = compressionAlgorithm != null; this.compression = compressionAlgorithm != null;
synchronized (handler) { synchronized (h) {
if (handler.getLobFilesInDirectories()) { if (h.getLobFilesInDirectories()) {
objectId = getNewObjectId(handler); objectId = getNewObjectId(h);
fileName = getFileNamePrefix(handler.getDatabasePath(), objectId) + Constants.SUFFIX_TEMP_FILE; fileName = getFileNamePrefix(h.getDatabasePath(), objectId) + Constants.SUFFIX_TEMP_FILE;
} else { } else {
objectId = handler.allocateObjectId(false, true); objectId = h.allocateObjectId(false, true);
fileName = handler.createTempFile(); fileName = h.createTempFile();
} }
tempFile = handler.openFile(fileName, "rw", false); tempFile = h.openFile(fileName, "rw", false);
tempFile.autoDelete(); tempFile.autoDelete();
} }
FileStoreOutputStream out = new FileStoreOutputStream(tempFile, handler, compressionAlgorithm); FileStoreOutputStream out = new FileStoreOutputStream(tempFile, h, compressionAlgorithm);
return out; return out;
} }
private void createFromStream(byte[] buff, int len, InputStream in, long remaining, DataHandler handler) private void createFromStream(byte[] buff, int len, InputStream in, long remaining, DataHandler h)
throws SQLException { throws SQLException {
try { try {
FileStoreOutputStream out = initLarge(handler); FileStoreOutputStream out = initLarge(h);
boolean compress = handler.getLobCompressionAlgorithm(Value.BLOB) != null; boolean compress = h.getLobCompressionAlgorithm(Value.BLOB) != null;
try { try {
while (true) { while (true) {
precision += len; precision += len;
...@@ -415,7 +415,7 @@ public class ValueLob extends Value { ...@@ -415,7 +415,7 @@ public class ValueLob extends Value {
if (remaining <= 0) { if (remaining <= 0) {
break; break;
} }
len = getBufferSize(handler, compress, remaining); len = getBufferSize(h, compress, remaining);
len = IOUtils.readFully(in, buff, 0, len); len = IOUtils.readFully(in, buff, 0, len);
if (len <= 0) { if (len <= 0) {
break; break;
...@@ -494,33 +494,33 @@ public class ValueLob extends Value { ...@@ -494,33 +494,33 @@ public class ValueLob extends Value {
} }
} }
public Value link(DataHandler handler, int tabId) throws SQLException { public Value link(DataHandler h, int tabId) throws SQLException {
if (fileName == null) { if (fileName == null) {
this.tableId = tabId; this.tableId = tabId;
return this; return this;
} }
if (linked) { if (linked) {
ValueLob copy = ValueLob.copy(this); ValueLob copy = ValueLob.copy(this);
if (handler.getLobFilesInDirectories()) { if (h.getLobFilesInDirectories()) {
copy.objectId = getNewObjectId(handler); copy.objectId = getNewObjectId(h);
} else { } else {
copy.objectId = handler.allocateObjectId(false, true); copy.objectId = h.allocateObjectId(false, true);
} }
copy.tableId = tabId; copy.tableId = tabId;
String live = getFileName(handler, copy.tableId, copy.objectId); String live = getFileName(h, copy.tableId, copy.objectId);
copyFile(handler, fileName, live); copyFileTo(h, fileName, live);
copy.fileName = live; copy.fileName = live;
copy.linked = true; copy.linked = true;
return copy; return copy;
} }
if (!linked) { if (!linked) {
this.tableId = tabId; this.tableId = tabId;
String live = getFileName(handler, tableId, objectId); String live = getFileName(h, tableId, objectId);
if (tempFile != null) { if (tempFile != null) {
tempFile.stopAutoDelete(); tempFile.stopAutoDelete();
tempFile = null; tempFile = null;
} }
renameFile(handler, fileName, live); renameFile(h, fileName, live);
fileName = live; fileName = live;
linked = true; linked = true;
} }
...@@ -723,19 +723,19 @@ public class ValueLob extends Value { ...@@ -723,19 +723,19 @@ public class ValueLob extends Value {
* Store the lob data to a file if the size of the buffer it larger than the * Store the lob data to a file if the size of the buffer it larger than the
* maximum size for an in-place lob. * maximum size for an in-place lob.
* *
* @param handler the data handler * @param h the data handler
*/ */
public void convertToFileIfRequired(DataHandler handler) throws SQLException { public void convertToFileIfRequired(DataHandler h) throws SQLException {
if (Constants.AUTO_CONVERT_LOB_TO_FILES && small != null && small.length > handler.getMaxLengthInplaceLob()) { if (Constants.AUTO_CONVERT_LOB_TO_FILES && small != null && small.length > h.getMaxLengthInplaceLob()) {
boolean compress = handler.getLobCompressionAlgorithm(type) != null; boolean compress = h.getLobCompressionAlgorithm(type) != null;
int len = getBufferSize(handler, compress, Long.MAX_VALUE); int len = getBufferSize(h, compress, Long.MAX_VALUE);
int tabId = tableId; int tabId = tableId;
if (type == Value.BLOB) { if (type == Value.BLOB) {
createFromStream(MemoryUtils.newBytes(len), 0, getInputStream(), Long.MAX_VALUE, handler); createFromStream(MemoryUtils.newBytes(len), 0, getInputStream(), Long.MAX_VALUE, h);
} else { } else {
createFromReader(new char[len], 0, getReader(), Long.MAX_VALUE, handler); createFromReader(new char[len], 0, getReader(), Long.MAX_VALUE, h);
} }
Value v2 = link(handler, tabId); Value v2 = link(h, tabId);
if (SysProperties.CHECK && v2 != this) { if (SysProperties.CHECK && v2 != this) {
Message.throwInternalError(); Message.throwInternalError();
} }
...@@ -821,9 +821,9 @@ public class ValueLob extends Value { ...@@ -821,9 +821,9 @@ public class ValueLob extends Value {
} }
} }
private void copyFile(DataHandler handler, String fileName, String live) throws SQLException { private void copyFileTo(DataHandler h, String sourceFileName, String targetFileName) throws SQLException {
synchronized (handler.getLobSyncObject()) { synchronized (h.getLobSyncObject()) {
FileSystem.getInstance(fileName).copy(fileName, live); FileSystem.getInstance(sourceFileName).copy(sourceFileName, targetFileName);
} }
} }
......
...@@ -43,11 +43,11 @@ public class ValueShort extends Value { ...@@ -43,11 +43,11 @@ public class ValueShort extends Value {
return ValueShort.get((short) (value + other.value)); return ValueShort.get((short) (value + other.value));
} }
private ValueShort checkRange(int value) throws SQLException { private ValueShort checkRange(int x) throws SQLException {
if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { if (x < Short.MIN_VALUE || x > Short.MAX_VALUE) {
throw Message.getSQLException(ErrorCode.OVERFLOW_FOR_TYPE_1, DataType.getDataType(Value.SHORT).name); throw Message.getSQLException(ErrorCode.OVERFLOW_FOR_TYPE_1, DataType.getDataType(Value.SHORT).name);
} }
return ValueShort.get((short) value); return ValueShort.get((short) x);
} }
public int getSignum() { public int getSignum() {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论