提交 8753a6b0 authored 作者: Andrei Tokar's avatar Andrei Tokar

Merge remote-tracking branch 'h2database/master' into undo-log-split

...@@ -21,6 +21,66 @@ Change Log ...@@ -21,6 +21,66 @@ Change Log
<h2>Next Version (unreleased)</h2> <h2>Next Version (unreleased)</h2>
<ul> <ul>
<li>Issue #1177: Resource leak in Recover tool
</li>
<li>PR #1183: Improve concurrency of connection pool with wait-free implement
</li>
<li>Issue #1073: H2 v1.4.197 fails to open an existing database with the error [Unique index or primary key violation: "PRIMARY KEY ON """".PAGE_INDEX"]
</li>
<li>PR #1179: Drop TransactionMap.readLogId
</li>
<li>PR #1181: Improve CURRENT_TIMESTAMP and add LOCALTIME and LOCALTIMESTAMP
</li>
<li>PR #1176: Magic value replacement with constant
</li>
<li>PR #1171: Introduce last commited value into a VersionedValue
</li>
<li>PR #1175: tighten test conditions - do not ignore any exceptions
</li>
<li>PR #1174: Remove mapid
</li>
<li>PR #1173: protect first background exception encountered and relate it to clients
</li>
<li>PR #1172: Yet another attempt to tighten that testing loop
</li>
<li>PR #1170: Add support of CONTINUE | RESTART IDENTITY to TRUNCATE TABLE
</li>
<li>Issue #1168: ARRAY_CONTAINS() returning incorrect results when inside subquery with Long elements.
</li>
<li>PR #1167: MVStore: Undo log synchronization removal
</li>
<li>PR #1166: Add SRID support to EWKT format
</li>
<li>PR #1165: Optimize isTargetRowFound() and buildColumnListFromOnCondition() in MergeUsing
</li>
<li>PR #1164: More fixes for parsing of MERGE USING and other changes in Parser
</li>
<li>PR #1154: Support for external authentication
</li>
<li>PR #1162: Reduce allocation of temporary strings
</li>
<li>PR #1158: make fields final
</li>
<li>Issue #1129: TestCrashAPI / TestFuzzOptimizations throw OOME on Travis in PageStore mode
</li>
<li>PR #1156: Add support for SQL:2003 WITH [NO] DATA to CREATE TABLE AS
</li>
<li>PR #1149: fix deadlock between OnExitDatabaseCloser.DATABASES and Engine.DATABASES
</li>
<li>PR #1152: skip intermediate DbException object when creating SQLException
</li>
<li>PR #1144: Add missing schema name with recursive view
</li>
<li>Issue #1091: get rid of the "New" class
</li>
<li>PR #1147: Assorted minor optimizations
</li>
<li>PR #1145: Reduce code duplication
</li>
<li>PR #1142: Misc small fixes
</li>
<li>PR #1141: Assorted optimizations and fixes
</li>
<li>PR #1138, #1139: Fix a memory leak caused by DatabaseCloser objects <li>PR #1138, #1139: Fix a memory leak caused by DatabaseCloser objects
</li> </li>
<li>PR #1137: Step toward making transaction commit atomic <li>PR #1137: Step toward making transaction commit atomic
......
...@@ -54,7 +54,12 @@ public abstract class Prepared { ...@@ -54,7 +54,12 @@ public abstract class Prepared {
private long modificationMetaId; private long modificationMetaId;
private Command command; private Command command;
private int objectId; /**
* Used to preserve object identities on database startup. {@code 0} if
* object is not stored, {@code -1} if object is stored and its ID is
* already read, {@code >0} if object is stored and its id is not yet read.
*/
private int persistedObjectId;
private int currentRowNumber; private int currentRowNumber;
private int rowScanCount; private int rowScanCount;
/** /**
...@@ -239,28 +244,31 @@ public abstract class Prepared { ...@@ -239,28 +244,31 @@ public abstract class Prepared {
/** /**
* Get the object id to use for the database object that is created in this * Get the object id to use for the database object that is created in this
* statement. This id is only set when the object is persistent. * statement. This id is only set when the object is already persisted.
* If not set, this method returns 0. * If not set, this method returns 0.
* *
* @return the object id or 0 if not set * @return the object id or 0 if not set
*/ */
protected int getCurrentObjectId() { protected int getPersistedObjectId() {
return objectId; int id = persistedObjectId;
return id >= 0 ? id : 0;
} }
/** /**
* Get the current object id, or get a new id from the database. The object * Get the current object id, or get a new id from the database. The object
* id is used when creating new database object (CREATE statement). * id is used when creating new database object (CREATE statement). This
* method may be called only once.
* *
* @return the object id * @return the object id
*/ */
protected int getObjectId() { protected int getObjectId() {
int id = objectId; int id = persistedObjectId;
if (id == 0) { if (id == 0) {
id = session.getDatabase().allocateObjectId(); id = session.getDatabase().allocateObjectId();
} else { } else if (id < 0) {
objectId = 0; throw DbException.throwInternalError("Prepared.getObjectId() was called before");
} }
persistedObjectId = -1;
return id; return id;
} }
...@@ -287,12 +295,12 @@ public abstract class Prepared { ...@@ -287,12 +295,12 @@ public abstract class Prepared {
} }
/** /**
* Set the object id for this statement. * Set the persisted object id for this statement.
* *
* @param i the object id * @param i the object id
*/ */
public void setObjectId(int i) { public void setPersistedObjectId(int i) {
this.objectId = i; this.persistedObjectId = i;
this.create = false; this.create = false;
} }
......
...@@ -137,25 +137,24 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -137,25 +137,24 @@ public class AlterTableAddConstraint extends SchemaCommand {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY); throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
} }
} }
} } else {
if (index == null) {
IndexType indexType = IndexType.createPrimaryKey( IndexType indexType = IndexType.createPrimaryKey(
table.isPersistIndexes(), primaryKeyHash); table.isPersistIndexes(), primaryKeyHash);
String indexName = table.getSchema().getUniqueIndexName( String indexName = table.getSchema().getUniqueIndexName(
session, table, Constants.PREFIX_PRIMARY_KEY); session, table, Constants.PREFIX_PRIMARY_KEY);
int id = getObjectId(); int indexId = session.getDatabase().allocateObjectId();
try { try {
index = table.addIndex(session, indexName, id, index = table.addIndex(session, indexName, indexId,
indexColumns, indexType, true, null); indexColumns, indexType, true, null);
} finally { } finally {
getSchema().freeUniqueName(indexName); getSchema().freeUniqueName(indexName);
} }
} }
index.getIndexType().setBelongsToConstraint(true); index.getIndexType().setBelongsToConstraint(true);
int constraintId = getObjectId(); int id = getObjectId();
String name = generateConstraintName(table); String name = generateConstraintName(table);
ConstraintUnique pk = new ConstraintUnique(getSchema(), ConstraintUnique pk = new ConstraintUnique(getSchema(),
constraintId, name, table, true); id, name, table, true);
pk.setColumns(indexColumns); pk.setColumns(indexColumns);
pk.setIndex(index, true); pk.setIndex(index, true);
constraint = pk; constraint = pk;
...@@ -277,7 +276,7 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -277,7 +276,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
} }
private Index createIndex(Table t, IndexColumn[] cols, boolean unique) { private Index createIndex(Table t, IndexColumn[] cols, boolean unique) {
int indexId = getObjectId(); int indexId = session.getDatabase().allocateObjectId();
IndexType indexType; IndexType indexType;
if (unique) { if (unique) {
// for unique constraints // for unique constraints
......
...@@ -103,7 +103,7 @@ public abstract class CommandWithColumns extends SchemaCommand { ...@@ -103,7 +103,7 @@ public abstract class CommandWithColumns extends SchemaCommand {
if (columns != null) { if (columns != null) {
for (Column c : columns) { for (Column c : columns) {
if (c.isAutoIncrement()) { if (c.isAutoIncrement()) {
int objId = getObjectId(); int objId = session.getDatabase().allocateObjectId();
c.convertAutoIncrementToSequence(session, getSchema(), objId, temporary); c.convertAutoIncrementToSequence(session, getSchema(), objId, temporary);
if (!Constants.CLUSTERING_DISABLED.equals(session.getDatabase().getCluster())) { if (!Constants.CLUSTERING_DISABLED.equals(session.getDatabase().getCluster())) {
throw DbException.getUnsupportedException("CLUSTERING && auto-increment columns"); throw DbException.getUnsupportedException("CLUSTERING && auto-increment columns");
......
...@@ -418,7 +418,7 @@ public class Set extends Prepared { ...@@ -418,7 +418,7 @@ public class Set extends Prepared {
} }
case SetTypes.TRACE_LEVEL_FILE: case SetTypes.TRACE_LEVEL_FILE:
session.getUser().checkAdmin(); session.getUser().checkAdmin();
if (getCurrentObjectId() == 0) { if (getPersistedObjectId() == 0) {
// don't set the property when opening the database // don't set the property when opening the database
// this is for compatibility with older versions, because // this is for compatibility with older versions, because
// this setting was persistent // this setting was persistent
...@@ -427,7 +427,7 @@ public class Set extends Prepared { ...@@ -427,7 +427,7 @@ public class Set extends Prepared {
break; break;
case SetTypes.TRACE_LEVEL_SYSTEM_OUT: case SetTypes.TRACE_LEVEL_SYSTEM_OUT:
session.getUser().checkAdmin(); session.getUser().checkAdmin();
if (getCurrentObjectId() == 0) { if (getPersistedObjectId() == 0) {
// don't set the property when opening the database // don't set the property when opening the database
// this is for compatibility with older versions, because // this is for compatibility with older versions, because
// this setting was persistent // this setting was persistent
...@@ -552,7 +552,7 @@ public class Set extends Prepared { ...@@ -552,7 +552,7 @@ public class Set extends Prepared {
} }
addOrUpdateSetting(name,expression.getValue(session).getString(),0); addOrUpdateSetting(name,expression.getValue(session).getString(),0);
} catch (Exception e) { } catch (Exception e) {
//Errors during start are ignored to allow to open the database //Errors during start are ignored to allow to open the database
if (database.isStarting()) { if (database.isStarting()) {
database.getTrace(Trace.DATABASE).error(e, "{0}: failed to set authenticator during database start ",expression.toString()); database.getTrace(Trace.DATABASE).error(e, "{0}: failed to set authenticator during database start ",expression.toString());
} else { } else {
......
...@@ -54,7 +54,7 @@ public class MetaRecord implements Comparable<MetaRecord> { ...@@ -54,7 +54,7 @@ public class MetaRecord implements Comparable<MetaRecord> {
DatabaseEventListener listener) { DatabaseEventListener listener) {
try { try {
Prepared command = systemSession.prepare(sql); Prepared command = systemSession.prepare(sql);
command.setObjectId(id); command.setPersistedObjectId(id);
command.update(); command.update();
} catch (DbException e) { } catch (DbException e) {
e = e.addSQL(sql); e = e.addSQL(sql);
......
...@@ -22,8 +22,11 @@ package org.h2.jdbcx; ...@@ -22,8 +22,11 @@ package org.h2.jdbcx;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.sql.ConnectionEvent; import javax.sql.ConnectionEvent;
...@@ -33,7 +36,6 @@ import javax.sql.DataSource; ...@@ -33,7 +36,6 @@ import javax.sql.DataSource;
import javax.sql.PooledConnection; import javax.sql.PooledConnection;
import org.h2.message.DbException; import org.h2.message.DbException;
import org.h2.util.Utils;
/** /**
* A simple standalone JDBC connection pool. * A simple standalone JDBC connection pool.
...@@ -69,12 +71,12 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -69,12 +71,12 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
private static final int DEFAULT_MAX_CONNECTIONS = 10; private static final int DEFAULT_MAX_CONNECTIONS = 10;
private final ConnectionPoolDataSource dataSource; private final ConnectionPoolDataSource dataSource;
private final ArrayList<PooledConnection> recycledConnections = Utils.newSmallArrayList(); private final Queue<PooledConnection> recycledConnections = new ConcurrentLinkedQueue<>();
private PrintWriter logWriter; private PrintWriter logWriter;
private int maxConnections = DEFAULT_MAX_CONNECTIONS; private volatile int maxConnections = DEFAULT_MAX_CONNECTIONS;
private int timeout = DEFAULT_TIMEOUT; private volatile int timeout = DEFAULT_TIMEOUT;
private int activeConnections; private AtomicInteger activeConnections = new AtomicInteger(0);
private boolean isDisposed; private AtomicBoolean isDisposed = new AtomicBoolean(false);
protected JdbcConnectionPool(ConnectionPoolDataSource dataSource) { protected JdbcConnectionPool(ConnectionPoolDataSource dataSource) {
this.dataSource = dataSource; this.dataSource = dataSource;
...@@ -120,13 +122,11 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -120,13 +122,11 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
* *
* @param max the maximum number of connections * @param max the maximum number of connections
*/ */
public synchronized void setMaxConnections(int max) { public void setMaxConnections(int max) {
if (max < 1) { if (max < 1) {
throw new IllegalArgumentException("Invalid maxConnections value: " + max); throw new IllegalArgumentException("Invalid maxConnections value: " + max);
} }
this.maxConnections = max; this.maxConnections = max;
// notify waiting threads if the value was increased
notifyAll();
} }
/** /**
...@@ -134,7 +134,7 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -134,7 +134,7 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
* *
* @return the max the maximum number of connections * @return the max the maximum number of connections
*/ */
public synchronized int getMaxConnections() { public int getMaxConnections() {
return maxConnections; return maxConnections;
} }
...@@ -144,7 +144,7 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -144,7 +144,7 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
* @return the timeout in seconds * @return the timeout in seconds
*/ */
@Override @Override
public synchronized int getLoginTimeout() { public int getLoginTimeout() {
return timeout; return timeout;
} }
...@@ -156,7 +156,7 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -156,7 +156,7 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
* @param seconds the timeout, 0 meaning the default * @param seconds the timeout, 0 meaning the default
*/ */
@Override @Override
public synchronized void setLoginTimeout(int seconds) { public void setLoginTimeout(int seconds) {
if (seconds == 0) { if (seconds == 0) {
seconds = DEFAULT_TIMEOUT; seconds = DEFAULT_TIMEOUT;
} }
...@@ -167,13 +167,12 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -167,13 +167,12 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
* Closes all unused pooled connections. * Closes all unused pooled connections.
* Exceptions while closing are written to the log stream (if set). * Exceptions while closing are written to the log stream (if set).
*/ */
public synchronized void dispose() { public void dispose() {
if (isDisposed) { isDisposed.set(true);
return;
} PooledConnection pc;
isDisposed = true; while ((pc = recycledConnections.poll()) != null) {
for (PooledConnection aList : recycledConnections) { closeConnection(pc);
closeConnection(aList);
} }
} }
...@@ -193,18 +192,28 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -193,18 +192,28 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
@Override @Override
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
long max = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeout); long max = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeout);
int spin = 0;
do { do {
synchronized (this) { if (activeConnections.incrementAndGet() <= maxConnections) {
if (activeConnections < maxConnections) {
return getConnectionNow();
}
try { try {
wait(1000); return getConnectionNow();
} catch (InterruptedException e) { } catch (Throwable t) {
// ignore activeConnections.decrementAndGet();
throw t;
} }
} else {
activeConnections.decrementAndGet();
} }
} while (System.nanoTime() <= max); if (--spin >= 0) {
continue;
}
try {
spin = 3;
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} while (System.nanoTime() - max <= 0);
throw new SQLException("Login timeout", "08001", 8001); throw new SQLException("Login timeout", "08001", 8001);
} }
...@@ -217,17 +226,14 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -217,17 +226,14 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
} }
private Connection getConnectionNow() throws SQLException { private Connection getConnectionNow() throws SQLException {
if (isDisposed) { if (isDisposed.get()) {
throw new IllegalStateException("Connection pool has been disposed."); throw new IllegalStateException("Connection pool has been disposed.");
} }
PooledConnection pc; PooledConnection pc = recycledConnections.poll();
if (!recycledConnections.isEmpty()) { if (pc == null) {
pc = recycledConnections.remove(recycledConnections.size() - 1);
} else {
pc = dataSource.getPooledConnection(); pc = dataSource.getPooledConnection();
} }
Connection conn = pc.getConnection(); Connection conn = pc.getConnection();
activeConnections++;
pc.addConnectionEventListener(this); pc.addConnectionEventListener(this);
return conn; return conn;
} }
...@@ -239,19 +245,20 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -239,19 +245,20 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
* *
* @param pc the pooled connection * @param pc the pooled connection
*/ */
synchronized void recycleConnection(PooledConnection pc) { private void recycleConnection(PooledConnection pc) {
if (activeConnections <= 0) { int active = activeConnections.decrementAndGet();
if (active < 0) {
activeConnections.incrementAndGet();
throw new AssertionError(); throw new AssertionError();
} }
activeConnections--; if (!isDisposed.get() && active < maxConnections) {
if (!isDisposed && activeConnections < maxConnections) {
recycledConnections.add(pc); recycledConnections.add(pc);
if (isDisposed.get()) {
dispose();
}
} else { } else {
closeConnection(pc); closeConnection(pc);
} }
if (activeConnections >= maxConnections - 1) {
notifyAll();
}
} }
private void closeConnection(PooledConnection pc) { private void closeConnection(PooledConnection pc) {
...@@ -290,8 +297,8 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener, ...@@ -290,8 +297,8 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
* *
* @return the number of active connections. * @return the number of active connections.
*/ */
public synchronized int getActiveConnections() { public int getActiveConnections() {
return activeConnections; return activeConnections.get();
} }
/** /**
......
...@@ -340,14 +340,13 @@ public class Recover extends Tool implements DataHandler { ...@@ -340,14 +340,13 @@ public class Recover extends Tool implements DataHandler {
} else if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) { } else if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) {
String f = fileName.substring(0, fileName.length() - String f = fileName.substring(0, fileName.length() -
Constants.SUFFIX_PAGE_FILE.length()); Constants.SUFFIX_PAGE_FILE.length());
PrintWriter writer; try (PrintWriter writer = getWriter(fileName, ".txt")) {
writer = getWriter(fileName, ".txt"); MVStoreTool.dump(fileName, writer, true);
MVStoreTool.dump(fileName, writer, true); MVStoreTool.info(fileName, writer);
MVStoreTool.info(fileName, writer); }
writer.close(); try (PrintWriter writer = getWriter(f + ".h2.db", ".sql")) {
writer = getWriter(f + ".h2.db", ".sql"); dumpMVStoreFile(writer, fileName);
dumpMVStoreFile(writer, fileName); }
writer.close();
} }
} }
} }
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论