first commit

This commit is contained in:
MaddoScientisto 2026-03-14 20:04:39 +01:00
commit cf97b64877
27585 changed files with 3281780 additions and 0 deletions

View file

@ -0,0 +1,17 @@
package com.mysql.fabric;
public class FabricCommunicationException extends Exception {
private static final long serialVersionUID = 1L;
public FabricCommunicationException(Throwable cause) {
super(cause);
}
public FabricCommunicationException(String message) {
super(message);
}
public FabricCommunicationException(String message, Throwable cause) {
super(message, cause);
}
}

View file

@ -0,0 +1,73 @@
package com.mysql.fabric;
import com.mysql.fabric.proto.xmlrpc.XmlRpcClient;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FabricConnection {
private XmlRpcClient client;
private Map<String, ShardMapping> shardMappingsByTableName = new HashMap<String, ShardMapping>();
private Map<String, ServerGroup> serverGroupsByName = new HashMap<String, ServerGroup>();
private long shardMappingsExpiration;
private long serverGroupsExpiration;
public FabricConnection(String url, String username, String password) throws FabricCommunicationException {
this.client = new XmlRpcClient(url, username, password);
refreshState();
}
public FabricConnection(Set<String> urls, String username, String password) throws FabricCommunicationException {
throw new UnsupportedOperationException("Multiple connections not supported.");
}
public String getInstanceUuid() {
return null;
}
public int getVersion() {
return 0;
}
public int refreshState() throws FabricCommunicationException {
FabricStateResponse<Set<ServerGroup>> serverGroups = this.client.getServerGroups();
FabricStateResponse<Set<ShardMapping>> shardMappings = this.client.getShardMappings();
this.serverGroupsExpiration = serverGroups.getExpireTimeMillis();
this.shardMappingsExpiration = shardMappings.getExpireTimeMillis();
for (ServerGroup g : serverGroups.getData())
this.serverGroupsByName.put(g.getName(), g);
for (ShardMapping m : shardMappings.getData()) {
for (ShardTable t : m.getShardTables())
this.shardMappingsByTableName.put(t.getDatabase() + "." + t.getTable(), m);
}
return 0;
}
public ServerGroup getServerGroup(String serverGroupName) throws FabricCommunicationException {
if (isStateExpired())
refreshState();
return this.serverGroupsByName.get(serverGroupName);
}
public ShardMapping getShardMapping(String database, String table) throws FabricCommunicationException {
if (isStateExpired())
refreshState();
return this.shardMappingsByTableName.get(database + "." + table);
}
public boolean isStateExpired() {
return (System.currentTimeMillis() > this.shardMappingsExpiration || System.currentTimeMillis() > this.serverGroupsExpiration);
}
public Set<String> getFabricHosts() {
return null;
}
public XmlRpcClient getClient() {
return this.client;
}
}

View file

@ -0,0 +1,25 @@
package com.mysql.fabric;
public class FabricStateResponse<T> {
private T data;
private long expireTimeMillis;
public FabricStateResponse(T data, int secsTtl) {
this.data = data;
this.expireTimeMillis = System.currentTimeMillis() + (long)(1000 * secsTtl);
}
public FabricStateResponse(T data, long expireTimeMillis) {
this.data = data;
this.expireTimeMillis = expireTimeMillis;
}
public T getData() {
return this.data;
}
public long getExpireTimeMillis() {
return this.expireTimeMillis;
}
}

View file

@ -0,0 +1,44 @@
package com.mysql.fabric;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class HashShardMapping extends ShardMapping {
private static final MessageDigest md5Hasher;
private static class ReverseShardIndexSorter implements Comparator<ShardIndex> {
public int compare(ShardIndex i1, ShardIndex i2) {
return i2.getBound().compareTo(i1.getBound());
}
public static final ReverseShardIndexSorter instance = new ReverseShardIndexSorter();
}
static {
try {
md5Hasher = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
throw new ExceptionInInitializerError(ex);
}
}
public HashShardMapping(int mappingId, ShardingType shardingType, String globalGroupName, Set<ShardTable> shardTables, Set<ShardIndex> shardIndices) {
super(mappingId, shardingType, globalGroupName, shardTables, new TreeSet<ShardIndex>(ReverseShardIndexSorter.instance));
this.shardIndices.addAll(shardIndices);
}
protected ShardIndex getShardIndexForKey(String stringKey) {
String hashedKey = new BigInteger(1, md5Hasher.digest(stringKey.getBytes())).toString(16).toUpperCase();
for (int i = 0; i < 32 - hashedKey.length(); i++)
hashedKey = "0" + hashedKey;
for (ShardIndex shardIndex : this.shardIndices) {
if (shardIndex.getBound().compareTo(hashedKey) <= 0)
return shardIndex;
}
return this.shardIndices.iterator().next();
}
}

View file

@ -0,0 +1,33 @@
package com.mysql.fabric;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class RangeShardMapping extends ShardMapping {
private static class RangeShardIndexSorter implements Comparator<ShardIndex> {
public int compare(ShardIndex i1, ShardIndex i2) {
Integer bound1 = Integer.parseInt(i1.getBound());
Integer bound2 = Integer.parseInt(i2.getBound());
return bound2.compareTo(bound1);
}
public static final RangeShardIndexSorter instance = new RangeShardIndexSorter();
}
public RangeShardMapping(int mappingId, ShardingType shardingType, String globalGroupName, Set<ShardTable> shardTables, Set<ShardIndex> shardIndices) {
super(mappingId, shardingType, globalGroupName, shardTables, new TreeSet<ShardIndex>(RangeShardIndexSorter.instance));
this.shardIndices.addAll(shardIndices);
}
protected ShardIndex getShardIndexForKey(String stringKey) {
Integer key = -1;
key = Integer.parseInt(stringKey);
for (ShardIndex i : this.shardIndices) {
Integer lowerBound = Integer.valueOf(i.getBound());
if (key >= lowerBound)
return i;
}
return null;
}
}

View file

@ -0,0 +1,53 @@
package com.mysql.fabric;
import com.mysql.fabric.proto.xmlrpc.ResultSetParser;
import java.util.List;
import java.util.Map;
public class Response {
private int protocolVersion;
private String fabricUuid;
private int ttl;
private String errorMessage;
private List<Map> resultSet;
public Response(List responseData) throws FabricCommunicationException {
this.protocolVersion = responseData.get(0);
if (this.protocolVersion != 1)
throw new FabricCommunicationException("Unknown protocol version: " + this.protocolVersion);
this.fabricUuid = responseData.get(1);
this.ttl = responseData.get(2);
this.errorMessage = responseData.get(3);
if ("".equals(this.errorMessage))
this.errorMessage = null;
List<Map<String, ?>> resultSets = responseData.get(4);
if (resultSets.size() > 0) {
Map<String, ?> resultData = resultSets.get(0);
this.resultSet = new ResultSetParser().parse((Map)resultData.get("info"), (List<List>)resultData.get("rows"));
}
}
public int getProtocolVersion() {
return this.protocolVersion;
}
public String getFabricUuid() {
return this.fabricUuid;
}
public int getTtl() {
return this.ttl;
}
public String getErrorMessage() {
return this.errorMessage;
}
public List<Map> getResultSet() {
return this.resultSet;
}
}

View file

@ -0,0 +1,80 @@
package com.mysql.fabric;
public class Server implements Comparable<Server> {
private String groupName;
private String uuid;
private String hostname;
private int port;
private ServerMode mode;
private ServerRole role;
private double weight;
public Server(String groupName, String uuid, String hostname, int port, ServerMode mode, ServerRole role, double weight) {
this.groupName = groupName;
this.uuid = uuid;
this.hostname = hostname;
this.port = port;
this.mode = mode;
this.role = role;
this.weight = weight;
assert uuid != null && !"".equals(uuid);
assert hostname != null && !"".equals(hostname);
assert port > 0;
assert mode != null;
assert role != null;
assert weight > 0.0D;
}
public String getGroupName() {
return this.groupName;
}
public String getUuid() {
return this.uuid;
}
public String getHostname() {
return this.hostname;
}
public int getPort() {
return this.port;
}
public ServerMode getMode() {
return this.mode;
}
public ServerRole getRole() {
return this.role;
}
public double getWeight() {
return this.weight;
}
public String toString() {
return String.format("Server[%s, %s:%d, %s, %s, weight=%s]", this.uuid, this.hostname, this.port, this.mode, this.role, this.weight);
}
public boolean equals(Object o) {
if (!(o instanceof Server))
return false;
Server s = (Server)o;
return s.getUuid().equals(getUuid());
}
public int hashCode() {
return getUuid().hashCode();
}
public int compareTo(Server other) {
return getUuid().compareTo(other.getUuid());
}
}

View file

@ -0,0 +1,26 @@
package com.mysql.fabric;
import java.util.Set;
public class ServerGroup {
private String name;
private Set<Server> servers;
public ServerGroup(String name, Set<Server> servers) {
this.name = name;
this.servers = servers;
}
public String getName() {
return this.name;
}
public Set<Server> getServers() {
return this.servers;
}
public String toString() {
return String.format("Group[name=%s, servers=%s]", this.name, this.servers);
}
}

View file

@ -0,0 +1,9 @@
package com.mysql.fabric;
public enum ServerMode {
OFFLINE, READ_ONLY, WRITE_ONLY, READ_WRITE;
public static ServerMode getFromConstant(Integer constant) {
return values()[constant];
}
}

View file

@ -0,0 +1,9 @@
package com.mysql.fabric;
public enum ServerRole {
FAULTY, SPARE, SECONDARY, PRIMARY;
public static ServerRole getFromConstant(Integer constant) {
return values()[constant];
}
}

View file

@ -0,0 +1,27 @@
package com.mysql.fabric;
public class ShardIndex {
private String bound;
private Integer shardId;
private String groupName;
public ShardIndex(String bound, Integer shardId, String groupName) {
this.bound = bound;
this.shardId = shardId;
this.groupName = groupName;
}
public String getBound() {
return this.bound;
}
public Integer getShardId() {
return this.shardId;
}
public String getGroupName() {
return this.groupName;
}
}

View file

@ -0,0 +1,50 @@
package com.mysql.fabric;
import java.util.Collections;
import java.util.Set;
public abstract class ShardMapping {
private int mappingId;
private ShardingType shardingType;
private String globalGroupName;
protected Set<ShardTable> shardTables;
protected Set<ShardIndex> shardIndices;
public ShardMapping(int mappingId, ShardingType shardingType, String globalGroupName, Set<ShardTable> shardTables, Set<ShardIndex> shardIndices) {
this.mappingId = mappingId;
this.shardingType = shardingType;
this.globalGroupName = globalGroupName;
this.shardTables = shardTables;
this.shardIndices = shardIndices;
}
public String getGroupNameForKey(String key) {
return getShardIndexForKey(key).getGroupName();
}
protected abstract ShardIndex getShardIndexForKey(String paramString);
public int getMappingId() {
return this.mappingId;
}
public ShardingType getShardingType() {
return this.shardingType;
}
public String getGlobalGroupName() {
return this.globalGroupName;
}
public Set<ShardTable> getShardTables() {
return Collections.<ShardTable>unmodifiableSet(this.shardTables);
}
public Set<ShardIndex> getShardIndices() {
return Collections.<ShardIndex>unmodifiableSet(this.shardIndices);
}
}

View file

@ -0,0 +1,20 @@
package com.mysql.fabric;
import java.util.Set;
public class ShardMappingFactory {
public ShardMapping createShardMapping(int mappingId, ShardingType shardingType, String globalGroupName, Set<ShardTable> shardTables, Set<ShardIndex> shardIndices) {
ShardMapping sm = null;
switch (shardingType) {
case RANGE:
sm = new RangeShardMapping(mappingId, shardingType, globalGroupName, shardTables, shardIndices);
break;
case HASH:
sm = new HashShardMapping(mappingId, shardingType, globalGroupName, shardTables, shardIndices);
break;
default:
throw new IllegalArgumentException("Invalid ShardingType");
}
return sm;
}
}

View file

@ -0,0 +1,27 @@
package com.mysql.fabric;
public class ShardTable {
private String database;
private String table;
private String column;
public ShardTable(String database, String table, String column) {
this.database = database;
this.table = table;
this.column = column;
}
public String getDatabase() {
return this.database;
}
public String getTable() {
return this.table;
}
public String getColumn() {
return this.column;
}
}

View file

@ -0,0 +1,5 @@
package com.mysql.fabric;
public enum ShardingType {
LIST, RANGE, HASH;
}

View file

@ -0,0 +1,92 @@
package com.mysql.fabric.hibernate;
import com.mysql.fabric.FabricCommunicationException;
import com.mysql.fabric.FabricConnection;
import com.mysql.fabric.Server;
import com.mysql.fabric.ServerGroup;
import com.mysql.fabric.ServerMode;
import com.mysql.fabric.ShardMapping;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider;
public class FabricMultiTenantConnectionProvider implements MultiTenantConnectionProvider {
private static final long serialVersionUID = 1L;
private FabricConnection fabricConnection;
private String database;
private String table;
private String user;
private String password;
private ShardMapping shardMapping;
private ServerGroup globalGroup;
public FabricMultiTenantConnectionProvider(String fabricUrl, String database, String table, String user, String password, String fabricUser, String fabricPassword) {
try {
this.fabricConnection = new FabricConnection(fabricUrl, fabricUser, fabricPassword);
this.database = database;
this.table = table;
this.user = user;
this.password = password;
this.shardMapping = this.fabricConnection.getShardMapping(this.database, this.table);
this.globalGroup = this.fabricConnection.getServerGroup(this.shardMapping.getGlobalGroupName());
} catch (FabricCommunicationException ex) {
throw new RuntimeException(ex);
}
}
private Connection getReadWriteConnectionFromServerGroup(ServerGroup serverGroup) throws SQLException {
for (Server s : serverGroup.getServers()) {
if (ServerMode.READ_WRITE.equals(s.getMode())) {
String jdbcUrl = String.format("jdbc:mysql://%s:%s/%s", s.getHostname(), s.getPort(), this.database);
return DriverManager.getConnection(jdbcUrl, this.user, this.password);
}
}
throw new SQLException("Unable to find r/w server for chosen shard mapping in group " + serverGroup.getName());
}
public Connection getAnyConnection() throws SQLException {
return getReadWriteConnectionFromServerGroup(this.globalGroup);
}
public Connection getConnection(String tenantIdentifier) throws SQLException {
String serverGroupName = this.shardMapping.getGroupNameForKey(tenantIdentifier);
try {
ServerGroup serverGroup = this.fabricConnection.getServerGroup(serverGroupName);
return getReadWriteConnectionFromServerGroup(serverGroup);
} catch (FabricCommunicationException ex) {
throw new RuntimeException(ex);
}
}
public void releaseAnyConnection(Connection connection) throws SQLException {
try {
connection.close();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
releaseAnyConnection(connection);
}
public boolean supportsAggressiveRelease() {
return false;
}
public boolean isUnwrappableAs(Class unwrapType) {
return false;
}
public <T> T unwrap(Class<T> unwrapType) {
return null;
}
}

View file

@ -0,0 +1,39 @@
package com.mysql.fabric.jdbc;
import com.mysql.fabric.FabricCommunicationException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ConnectionImpl;
import com.mysql.jdbc.ExceptionInterceptor;
import com.mysql.jdbc.MySQLConnection;
import com.mysql.jdbc.SQLError;
import java.sql.SQLException;
import java.util.Properties;
public class ErrorReportingExceptionInterceptor implements ExceptionInterceptor {
private String hostname;
private String port;
private String fabricHaGroup;
public SQLException interceptException(SQLException sqlEx, Connection conn) {
MySQLConnection mysqlConn = (MySQLConnection)conn;
if (ConnectionImpl.class.isAssignableFrom(mysqlConn.getLoadBalanceSafeProxy().getClass()))
return null;
FabricMySQLConnectionProxy fabricProxy = (FabricMySQLConnectionProxy)mysqlConn.getLoadBalanceSafeProxy();
try {
return fabricProxy.interceptException(sqlEx, conn, this.fabricHaGroup, this.hostname, this.port);
} catch (FabricCommunicationException ex) {
return SQLError.createSQLException("Failed to report error to Fabric.", "08S01", ex, conn.getExceptionInterceptor(), conn);
}
}
public void init(Connection conn, Properties props) throws SQLException {
this.hostname = props.getProperty("HOST");
this.port = props.getProperty("PORT");
String connectionAttributes = props.getProperty("connectionAttributes");
this.fabricHaGroup = connectionAttributes.replaceAll("^.*\\bfabricHaGroup:(.+)\\b.*$", "$1");
}
public void destroy() {}
}

View file

@ -0,0 +1,30 @@
package com.mysql.fabric.jdbc;
import com.mysql.fabric.ServerGroup;
import com.mysql.jdbc.MySQLConnection;
import java.sql.SQLException;
import java.util.Set;
public interface FabricMySQLConnection extends MySQLConnection {
void clearServerSelectionCriteria() throws SQLException;
void setShardKey(String paramString) throws SQLException;
String getShardKey();
void setShardTable(String paramString) throws SQLException;
String getShardTable();
void setServerGroupName(String paramString) throws SQLException;
String getServerGroupName();
ServerGroup getCurrentServerGroup();
void clearQueryTables() throws SQLException;
void addQueryTable(String paramString) throws SQLException;
Set<String> getQueryTables();
}

View file

@ -0,0 +1,33 @@
package com.mysql.fabric.jdbc;
import com.mysql.jdbc.ConnectionProperties;
public interface FabricMySQLConnectionProperties extends ConnectionProperties {
void setFabricShardKey(String paramString);
String getFabricShardKey();
void setFabricShardTable(String paramString);
String getFabricShardTable();
void setFabricServerGroup(String paramString);
String getFabricServerGroup();
void setFabricProtocol(String paramString);
String getFabricProtocol();
void setFabricUsername(String paramString);
String getFabricUsername();
void setFabricPassword(String paramString);
String getFabricPassword();
void setFabricReportErrors(boolean paramBoolean);
boolean getFabricReportErrors();
}

View file

@ -0,0 +1,131 @@
package com.mysql.fabric.jdbc;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Properties;
public class FabricMySQLDataSource extends MysqlDataSource implements FabricMySQLConnectionProperties {
private static final long serialVersionUID = 1L;
private static final Driver driver;
private String fabricShardKey;
private String fabricShardTable;
private String fabricServerGroup;
static {
try {
driver = new FabricMySQLDriver();
} catch (Exception ex) {
throw new RuntimeException("Can create driver", ex);
}
}
protected Connection getConnection(Properties props) throws SQLException {
String jdbcUrlToUse = null;
if (!this.explicitUrl) {
StringBuffer jdbcUrl = new StringBuffer("jdbc:mysql:fabric://");
if (this.hostName != null)
jdbcUrl.append(this.hostName);
jdbcUrl.append(":");
jdbcUrl.append(this.port);
jdbcUrl.append("/");
if (this.databaseName != null)
jdbcUrl.append(this.databaseName);
jdbcUrlToUse = jdbcUrl.toString();
} else {
jdbcUrlToUse = this.url;
}
Properties urlProps = ((FabricMySQLDriver)driver).parseFabricURL(jdbcUrlToUse, null);
urlProps.remove("DBNAME");
urlProps.remove("HOST");
urlProps.remove("PORT");
Iterator<Object> keys = urlProps.keySet().iterator();
while (keys.hasNext()) {
String key = (String)keys.next();
props.setProperty(key, urlProps.getProperty(key));
}
if (this.fabricShardKey != null)
props.setProperty("fabricShardKey", this.fabricShardKey);
if (this.fabricShardTable != null)
props.setProperty("fabricShardTable", this.fabricShardTable);
if (this.fabricServerGroup != null)
props.setProperty("fabricServerGroup", this.fabricServerGroup);
props.setProperty("fabricProtocol", this.fabricProtocol);
if (this.fabricUsername != null)
props.setProperty("fabricUsername", this.fabricUsername);
if (this.fabricPassword != null)
props.setProperty("fabricPassword", this.fabricPassword);
props.setProperty("fabricReportErrors", Boolean.toString(this.fabricReportErrors));
return driver.connect(jdbcUrlToUse, props);
}
private String fabricProtocol = "http";
private String fabricUsername;
private String fabricPassword;
private boolean fabricReportErrors = false;
public void setFabricShardKey(String value) {
this.fabricShardKey = value;
}
public String getFabricShardKey() {
return this.fabricShardKey;
}
public void setFabricShardTable(String value) {
this.fabricShardTable = value;
}
public String getFabricShardTable() {
return this.fabricShardTable;
}
public void setFabricServerGroup(String value) {
this.fabricServerGroup = value;
}
public String getFabricServerGroup() {
return this.fabricServerGroup;
}
public void setFabricProtocol(String value) {
this.fabricProtocol = value;
}
public String getFabricProtocol() {
return this.fabricProtocol;
}
public void setFabricUsername(String value) {
this.fabricUsername = value;
}
public String getFabricUsername() {
return this.fabricUsername;
}
public void setFabricPassword(String value) {
this.fabricPassword = value;
}
public String getFabricPassword() {
return this.fabricPassword;
}
public void setFabricReportErrors(boolean value) {
this.fabricReportErrors = value;
}
public boolean getFabricReportErrors() {
return this.fabricReportErrors;
}
}

View file

@ -0,0 +1,66 @@
package com.mysql.fabric.jdbc;
import com.mysql.jdbc.NonRegisteringDriver;
import com.mysql.jdbc.Util;
import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Logger;
public class FabricMySQLDriver extends NonRegisteringDriver implements Driver {
public static final String FABRIC_URL_PREFIX = "jdbc:mysql:fabric://";
public static final String FABRIC_SHARD_KEY_PROPERTY_KEY = "fabricShardKey";
public static final String FABRIC_SHARD_TABLE_PROPERTY_KEY = "fabricShardTable";
public static final String FABRIC_SERVER_GROUP_PROPERTY_KEY = "fabricServerGroup";
public static final String FABRIC_PROTOCOL_PROPERTY_KEY = "fabricProtocol";
public static final String FABRIC_USERNAME_PROPERTY_KEY = "fabricUsername";
public static final String FABRIC_PASSWORD_PROPERTY_KEY = "fabricPassword";
public static final String FABRIC_REPORT_ERRORS_PROPERTY_KEY = "fabricReportErrors";
static {
try {
DriverManager.registerDriver(new FabricMySQLDriver());
} catch (SQLException ex) {
throw new RuntimeException("Can't register driver", ex);
}
}
public Connection connect(String url, Properties info) throws SQLException {
Properties parsedProps = parseFabricURL(url, info);
if (parsedProps == null)
return null;
parsedProps.setProperty("fabricProtocol", "http");
if (Util.isJdbc4())
try {
Constructor<?> jdbc4proxy = Class.forName("com.mysql.fabric.jdbc.JDBC4FabricMySQLConnectionProxy").getConstructor(Properties.class);
return (Connection)Util.handleNewInstance(jdbc4proxy, new Object[] { parsedProps }, null);
} catch (Exception e) {
throw (SQLException)new SQLException(e.getMessage()).initCause(e);
}
return new FabricMySQLConnectionProxy(parsedProps);
}
public boolean acceptsURL(String url) throws SQLException {
return (parseFabricURL(url, null) != null);
}
Properties parseFabricURL(String url, Properties defaults) throws SQLException {
if (!url.startsWith("jdbc:mysql:fabric://"))
return null;
return parseURL(url.replaceAll("fabric:", ""), defaults);
}
public Logger getParentLogger() throws SQLException {
throw new SQLException("no logging");
}
}

View file

@ -0,0 +1,30 @@
package com.mysql.fabric.jdbc;
import com.mysql.fabric.ServerGroup;
import com.mysql.jdbc.JDBC4MySQLConnection;
import java.sql.SQLException;
import java.util.Set;
public interface JDBC4FabricMySQLConnection extends JDBC4MySQLConnection {
void clearServerSelectionCriteria() throws SQLException;
void setShardKey(String paramString) throws SQLException;
String getShardKey();
void setShardTable(String paramString) throws SQLException;
String getShardTable();
void setServerGroupName(String paramString) throws SQLException;
String getServerGroupName();
ServerGroup getCurrentServerGroup();
void clearQueryTables() throws SQLException;
void addQueryTable(String paramString) throws SQLException;
Set<String> getQueryTables();
}

View file

@ -0,0 +1,72 @@
package com.mysql.fabric.jdbc;
import com.mysql.fabric.FabricConnection;
import com.mysql.jdbc.Connection;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.NClob;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Struct;
import java.util.Properties;
public class JDBC4FabricMySQLConnectionProxy extends FabricMySQLConnectionProxy implements JDBC4FabricMySQLConnection, FabricMySQLConnectionProperties {
private FabricConnection fabricConnection;
public JDBC4FabricMySQLConnectionProxy(Properties props) throws SQLException {
super(props);
}
public Blob createBlob() {
try {
transactionBegun();
return getActiveConnection().createBlob();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public Clob createClob() {
try {
transactionBegun();
return getActiveConnection().createClob();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public NClob createNClob() {
try {
transactionBegun();
return getActiveConnection().createNClob();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public SQLXML createSQLXML() throws SQLException {
transactionBegun();
return getActiveConnection().createSQLXML();
}
public void setClientInfo(Properties properties) throws SQLClientInfoException {
for (Connection c : this.serverConnections.values())
c.setClientInfo(properties);
}
public void setClientInfo(String name, String value) throws SQLClientInfoException {
for (Connection c : this.serverConnections.values())
c.setClientInfo(name, value);
}
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return getActiveConnection().createArrayOf(typeName, elements);
}
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
transactionBegun();
return getActiveConnection().createStruct(typeName, attributes);
}
}

View file

@ -0,0 +1,44 @@
package com.mysql.fabric.proto.xmlrpc;
import com.mysql.fabric.FabricCommunicationException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class AuthenticatedXmlRpcMethodCaller implements XmlRpcMethodCaller {
private XmlRpcMethodCaller underlyingCaller;
private String url;
private String username;
private String password;
public AuthenticatedXmlRpcMethodCaller(XmlRpcMethodCaller underlyingCaller, String url, String username, String password) {
this.underlyingCaller = underlyingCaller;
this.url = url;
this.username = username;
this.password = password;
}
public void setHeader(String name, String value) {
this.underlyingCaller.setHeader(name, value);
}
public void clearHeader(String name) {
this.underlyingCaller.clearHeader(name);
}
public List<?> call(String methodName, Object[] args) throws FabricCommunicationException {
String authenticateHeader;
try {
authenticateHeader = DigestAuthentication.getChallengeHeader(this.url);
} catch (IOException ex) {
throw new FabricCommunicationException("Unable to obtain challenge header for authentication", ex);
}
Map<String, String> digestChallenge = DigestAuthentication.parseDigestChallenge(authenticateHeader);
String authorizationHeader = DigestAuthentication.generateAuthorizationHeader(digestChallenge, this.username, this.password);
this.underlyingCaller.setHeader("Authorization", authorizationHeader);
return this.underlyingCaller.call(methodName, args);
}
}

View file

@ -0,0 +1,131 @@
package com.mysql.fabric.proto.xmlrpc;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class DigestAuthentication {
public static String getChallengeHeader(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoOutput(true);
conn.getOutputStream().close();
try {
conn.getInputStream().close();
} catch (IOException ex) {
if (401 != conn.getResponseCode())
throw ex;
String hdr = conn.getHeaderField("WWW-Authenticate");
if (hdr != null && !"".equals(hdr))
return hdr;
}
return null;
}
public static String calculateMD5RequestDigest(String uri, String username, String password, String realm, String nonce, String nc, String cnonce, String qop) {
String reqA1 = username + ":" + realm + ":" + password;
String reqA2 = "POST:" + uri;
String hashA1 = checksumMD5(reqA1);
String hashA2 = checksumMD5(reqA2);
String requestDigest = digestMD5(hashA1, nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + hashA2);
return requestDigest;
}
private static String checksumMD5(String data) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException("Unable to create MD5 instance", ex);
}
return hexEncode(md5.digest(data.getBytes()));
}
private static String digestMD5(String secret, String data) {
return checksumMD5(secret + ":" + data);
}
private static String hexEncode(byte[] data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; i++)
sb.append(String.format("%02x", data[i]));
return sb.toString();
}
public static String serializeDigestResponse(Map<String, String> paramMap) {
StringBuffer sb = new StringBuffer("Digest ");
boolean prefixComma = false;
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
if (!prefixComma) {
prefixComma = true;
} else {
sb.append(", ");
}
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
}
return sb.toString();
}
public static Map<String, String> parseDigestChallenge(String headerValue) {
if (!headerValue.startsWith("Digest "))
throw new IllegalArgumentException("Header is not a digest challenge");
String params = headerValue.substring(7);
Map<String, String> paramMap = new HashMap<String, String>();
for (String param : params.split(",\\s*")) {
String[] pieces = param.split("=");
paramMap.put(pieces[0], pieces[1].replaceAll("^\"(.*)\"$", "$1"));
}
return paramMap;
}
public static String generateCnonce(String nonce, String nc) {
byte[] buf = new byte[8];
new Random().nextBytes(buf);
for (int i = 0; i < 8; i++)
buf[i] = (byte)(32 + buf[i] % 95);
String combo = String.format("%s:%s:%s:%s", nonce, nc, new Date().toGMTString(), new String(buf));
MessageDigest sha1 = null;
try {
sha1 = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException("Unable to create SHA-1 instance", ex);
}
return hexEncode(sha1.digest(combo.getBytes()));
}
private static String quoteParam(String param) {
if (param.contains("\"") || param.contains("'"))
throw new IllegalArgumentException("Invalid character in parameter");
return "\"" + param + "\"";
}
public static String generateAuthorizationHeader(Map<String, String> digestChallenge, String username, String password) {
String nonce = digestChallenge.get("nonce");
String nc = "00000001";
String cnonce = generateCnonce(nonce, nc);
String qop = "auth";
String uri = "/RPC2";
String realm = digestChallenge.get("realm");
String opaque = digestChallenge.get("opaque");
String requestDigest = calculateMD5RequestDigest(uri, username, password, realm, nonce, nc, cnonce, qop);
Map<String, String> digestResponseMap = new HashMap<String, String>();
digestResponseMap.put("algorithm", "MD5");
digestResponseMap.put("username", quoteParam(username));
digestResponseMap.put("realm", quoteParam(realm));
digestResponseMap.put("nonce", quoteParam(nonce));
digestResponseMap.put("uri", quoteParam(uri));
digestResponseMap.put("qop", qop);
digestResponseMap.put("nc", nc);
digestResponseMap.put("cnonce", quoteParam(cnonce));
digestResponseMap.put("response", quoteParam(requestDigest));
digestResponseMap.put("opaque", quoteParam(opaque));
return serializeDigestResponse(digestResponseMap);
}
}

View file

@ -0,0 +1,84 @@
package com.mysql.fabric.proto.xmlrpc;
import com.mysql.fabric.FabricCommunicationException;
import com.mysql.fabric.xmlrpc.Client;
import com.mysql.fabric.xmlrpc.base.Array;
import com.mysql.fabric.xmlrpc.base.Member;
import com.mysql.fabric.xmlrpc.base.MethodCall;
import com.mysql.fabric.xmlrpc.base.MethodResponse;
import com.mysql.fabric.xmlrpc.base.Param;
import com.mysql.fabric.xmlrpc.base.Params;
import com.mysql.fabric.xmlrpc.base.Struct;
import com.mysql.fabric.xmlrpc.base.Value;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class InternalXmlRpcMethodCaller implements XmlRpcMethodCaller {
private Client xmlRpcClient;
public InternalXmlRpcMethodCaller(String url) throws FabricCommunicationException {
try {
this.xmlRpcClient = new Client(url);
} catch (MalformedURLException ex) {
throw new FabricCommunicationException(ex);
}
}
private Object unwrapValue(Value v) {
if (v.getType() == 8)
return methodResponseArrayToList((Array)v.getValue());
if (v.getType() == 7) {
Map<String, Object> s = new HashMap<String, Object>();
for (Member m : ((Struct)v.getValue()).getMember())
s.put(m.getName(), unwrapValue(m.getValue()));
return s;
}
return v.getValue();
}
private List methodResponseArrayToList(Array array) {
List result = new ArrayList();
for (Value v : array.getData().getValue())
result.add(unwrapValue(v));
return result;
}
public void setHeader(String name, String value) {
this.xmlRpcClient.setHeader(name, value);
}
public void clearHeader(String name) {
this.xmlRpcClient.clearHeader(name);
}
public List call(String methodName, Object[] args) throws FabricCommunicationException {
MethodCall methodCall = new MethodCall();
Params p = new Params();
if (args == null)
args = new Object[0];
for (int i = 0; i < args.length; i++) {
if (args[i] == null)
throw new NullPointerException("nil args unsupported");
if (String.class.isAssignableFrom(args[i].getClass())) {
p.addParam(new Param(new Value((String)args[i])));
} else if (Double.class.isAssignableFrom(args[i].getClass())) {
p.addParam(new Param(new Value((Double)args[i])));
} else if (Integer.class.isAssignableFrom(args[i].getClass())) {
p.addParam(new Param(new Value((Integer)args[i])));
} else {
throw new IllegalArgumentException("Unknown argument type: " + args[i].getClass());
}
}
methodCall.setMethodName(methodName);
methodCall.setParams(p);
try {
MethodResponse resp = this.xmlRpcClient.execute(methodCall);
return methodResponseArrayToList((Array)resp.getParams().getParam().get(0).getValue().getValue());
} catch (Exception ex) {
throw new FabricCommunicationException("Error during call to `" + methodName + "' (args=" + args + ")", ex);
}
}
}

View file

@ -0,0 +1,23 @@
package com.mysql.fabric.proto.xmlrpc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ResultSetParser {
public List<Map> parse(Map info, List<List> rows) {
List<String> fieldNames = (List<String>)info.get("names");
Map<String, Integer> fieldNameIndexes = new HashMap<String, Integer>();
for (int i = 0; i < fieldNames.size(); i++)
fieldNameIndexes.put(fieldNames.get(i), Integer.valueOf(i));
List<Map> result = new ArrayList<Map>(rows.size());
for (List r : rows) {
Map<String, Object> resultRow = new HashMap<String, Object>();
for (Map.Entry<String, Integer> f : fieldNameIndexes.entrySet())
resultRow.put(f.getKey(), r.get(f.getValue().intValue()));
result.add(resultRow);
}
return result;
}
}

View file

@ -0,0 +1,286 @@
package com.mysql.fabric.proto.xmlrpc;
import com.mysql.fabric.FabricCommunicationException;
import com.mysql.fabric.FabricStateResponse;
import com.mysql.fabric.Response;
import com.mysql.fabric.Server;
import com.mysql.fabric.ServerGroup;
import com.mysql.fabric.ServerMode;
import com.mysql.fabric.ServerRole;
import com.mysql.fabric.ShardIndex;
import com.mysql.fabric.ShardMapping;
import com.mysql.fabric.ShardMappingFactory;
import com.mysql.fabric.ShardTable;
import com.mysql.fabric.ShardingType;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class XmlRpcClient {
private static final String THREAT_REPORTER_NAME = "MySQL Connector/J";
private static final String METHOD_DUMP_FABRIC_NODES = "dump.fabric_nodes";
private static final String METHOD_DUMP_SERVERS = "dump.servers";
private static final String METHOD_DUMP_SHARD_TABLES = "dump.shard_tables";
private static final String METHOD_DUMP_SHARD_INDEX = "dump.shard_index";
private static final String METHOD_DUMP_SHARD_MAPS = "dump.shard_maps";
private static final String METHOD_SHARDING_LOOKUP_SERVERS = "sharding.lookup_servers";
private static final String METHOD_SHARDING_CREATE_DEFINITION = "sharding.create_definition";
private static final String METHOD_SHARDING_ADD_TABLE = "sharding.add_table";
private static final String METHOD_SHARDING_ADD_SHARD = "sharding.add_shard";
private static final String METHOD_GROUP_LOOKUP_GROUPS = "group.lookup_groups";
private static final String METHOD_GROUP_CREATE = "group.create";
private static final String METHOD_GROUP_ADD = "group.add";
private static final String METHOD_GROUP_PROMOTE = "group.promote";
private static final String METHOD_GROUP_DESTROY = "group.destroy";
private static final String METHOD_THREAT_REPORT_ERROR = "threat.report_error";
private static final String METHOD_THREAT_REPORT_FAILURE = "threat.report_failure";
private static final String FIELD_MODE = "mode";
private static final String FIELD_STATUS = "status";
private static final String FIELD_HOST = "host";
private static final String FIELD_PORT = "port";
private static final String FIELD_ADDRESS = "address";
private static final String FIELD_GROUP_ID = "group_id";
private static final String FIELD_SERVER_UUID = "server_uuid";
private static final String FIELD_WEIGHT = "weight";
private static final String FIELD_SCHEMA_NAME = "schema_name";
private static final String FIELD_TABLE_NAME = "table_name";
private static final String FIELD_COLUMN_NAME = "column_name";
private static final String FIELD_LOWER_BOUND = "lower_bound";
private static final String FIELD_SHARD_ID = "shard_id";
private static final String FIELD_MAPPING_ID = "mapping_id";
private static final String FIELD_GLOBAL_GROUP_ID = "global_group_id";
private static final String FIELD_TYPE_NAME = "type_name";
private static final String FIELD_RESULT = "result";
private XmlRpcMethodCaller methodCaller;
public XmlRpcClient(String url, String username, String password) throws FabricCommunicationException {
this.methodCaller = new InternalXmlRpcMethodCaller(url);
if (username != null && !"".equals(username) && password != null)
this.methodCaller = new AuthenticatedXmlRpcMethodCaller(this.methodCaller, url, username, password);
}
private static Server unmarshallServer(Map serverData) throws FabricCommunicationException {
try {
ServerMode mode;
ServerRole role;
String host;
int port;
if (Integer.class.equals(serverData.get("mode").getClass())) {
mode = ServerMode.getFromConstant((Integer)serverData.get("mode"));
role = ServerRole.getFromConstant((Integer)serverData.get("status"));
host = (String)serverData.get("host");
port = (Integer)serverData.get("port");
} else {
mode = ServerMode.valueOf((String)serverData.get("mode"));
role = ServerRole.valueOf((String)serverData.get("status"));
String[] hostnameAndPort = ((String)serverData.get("address")).split(":");
host = hostnameAndPort[0];
port = Integer.valueOf(hostnameAndPort[1]);
}
Server s = new Server((String)serverData.get("group_id"), (String)serverData.get("server_uuid"), host, port, mode, role, (Double)serverData.get("weight"));
return s;
} catch (Exception ex) {
throw new FabricCommunicationException("Unable to parse server definition", ex);
}
}
private static Set<Server> toServerSet(List<Map> l) throws FabricCommunicationException {
Set<Server> servers = new HashSet<Server>();
for (Map serverData : l)
servers.add(unmarshallServer(serverData));
return servers;
}
private Response errorSafeCallMethod(String methodName, Object[] args) throws FabricCommunicationException {
List<?> responseData = this.methodCaller.call(methodName, args);
Response response = new Response(responseData);
if (response.getErrorMessage() != null)
throw new FabricCommunicationException("Call failed to method `" + methodName + "':\n" + response.getErrorMessage());
return response;
}
public Set<String> getFabricNames() throws FabricCommunicationException {
Response resp = errorSafeCallMethod("dump.fabric_nodes", new Object[0]);
Set<String> names = new HashSet<String>();
for (Map node : resp.getResultSet())
names.add(new StringBuilder().append(node.get("host")).append(":").append(node.get("port")).toString());
return names;
}
public Set<String> getGroupNames() throws FabricCommunicationException {
Set<String> groupNames = new HashSet<String>();
for (Map row : errorSafeCallMethod("group.lookup_groups", null).getResultSet())
groupNames.add((String)row.get("group_id"));
return groupNames;
}
public ServerGroup getServerGroup(String groupName) throws FabricCommunicationException {
Set<ServerGroup> groups = getServerGroups(groupName).getData();
if (groups.size() == 1)
return groups.iterator().next();
return null;
}
public Set<Server> getServersForKey(String tableName, int key) throws FabricCommunicationException {
Response r = errorSafeCallMethod("sharding.lookup_servers", new Object[] { tableName, key });
return toServerSet(r.getResultSet());
}
public FabricStateResponse<Set<ServerGroup>> getServerGroups(String groupPattern) throws FabricCommunicationException {
int version = 0;
Response response = errorSafeCallMethod("dump.servers", new Object[] { version, groupPattern });
Map<String, Set<Server>> serversByGroupName = new HashMap<String, Set<Server>>();
for (Map server : response.getResultSet()) {
Server s = unmarshallServer(server);
if (serversByGroupName.get(s.getGroupName()) == null)
serversByGroupName.put(s.getGroupName(), new HashSet<Server>());
serversByGroupName.get(s.getGroupName()).add(s);
}
Set<ServerGroup> serverGroups = new HashSet<ServerGroup>();
for (Map.Entry<String, Set<Server>> entry : serversByGroupName.entrySet()) {
ServerGroup g = new ServerGroup(entry.getKey(), entry.getValue());
serverGroups.add(g);
}
return new FabricStateResponse<Set<ServerGroup>>(serverGroups, response.getTtl());
}
public FabricStateResponse<Set<ServerGroup>> getServerGroups() throws FabricCommunicationException {
return getServerGroups("");
}
private FabricStateResponse<Set<ShardTable>> getShardTables(int shardMappingId) throws FabricCommunicationException {
int version = 0;
Object[] args = { version, String.valueOf(shardMappingId) };
Response tablesResponse = errorSafeCallMethod("dump.shard_tables", args);
Set<ShardTable> tables = new HashSet<ShardTable>();
for (Map rawTable : tablesResponse.getResultSet()) {
String database = (String)rawTable.get("schema_name");
String table = (String)rawTable.get("table_name");
String column = (String)rawTable.get("column_name");
ShardTable st = new ShardTable(database, table, column);
tables.add(st);
}
return new FabricStateResponse<Set<ShardTable>>(tables, tablesResponse.getTtl());
}
private FabricStateResponse<Set<ShardIndex>> getShardIndices(int shardMappingId) throws FabricCommunicationException {
int version = 0;
Object[] args = { version, String.valueOf(shardMappingId) };
Response indexResponse = errorSafeCallMethod("dump.shard_index", args);
Set<ShardIndex> indices = new HashSet<ShardIndex>();
for (Map rawIndexEntry : indexResponse.getResultSet()) {
String bound = (String)rawIndexEntry.get("lower_bound");
int shardId = (Integer)rawIndexEntry.get("shard_id");
String groupName = (String)rawIndexEntry.get("group_id");
ShardIndex si = new ShardIndex(bound, shardId, groupName);
indices.add(si);
}
return new FabricStateResponse<Set<ShardIndex>>(indices, indexResponse.getTtl());
}
public FabricStateResponse<Set<ShardMapping>> getShardMappings(String shardMappingIdPattern) throws FabricCommunicationException {
int version = 0;
Object[] args = { version, shardMappingIdPattern };
Response mapsResponse = errorSafeCallMethod("dump.shard_maps", args);
long minExpireTimeMillis = System.currentTimeMillis() + (long)(1000 * mapsResponse.getTtl());
Set<ShardMapping> mappings = new HashSet<ShardMapping>();
for (Map rawMapping : mapsResponse.getResultSet()) {
int mappingId = (Integer)rawMapping.get("mapping_id");
ShardingType shardingType = ShardingType.valueOf((String)rawMapping.get("type_name"));
String globalGroupName = (String)rawMapping.get("global_group_id");
FabricStateResponse<Set<ShardTable>> tables = getShardTables(mappingId);
FabricStateResponse<Set<ShardIndex>> indices = getShardIndices(mappingId);
if (tables.getExpireTimeMillis() < minExpireTimeMillis)
minExpireTimeMillis = tables.getExpireTimeMillis();
if (indices.getExpireTimeMillis() < minExpireTimeMillis)
minExpireTimeMillis = indices.getExpireTimeMillis();
ShardMapping m = new ShardMappingFactory().createShardMapping(mappingId, shardingType, globalGroupName, tables.getData(), indices.getData());
mappings.add(m);
}
return new FabricStateResponse<Set<ShardMapping>>(mappings, minExpireTimeMillis);
}
public FabricStateResponse<Set<ShardMapping>> getShardMappings() throws FabricCommunicationException {
return getShardMappings("");
}
public void createGroup(String groupName) throws FabricCommunicationException {
errorSafeCallMethod("group.create", new Object[] { groupName });
}
public void createServerInGroup(String groupName, String hostname, int port) throws FabricCommunicationException {
errorSafeCallMethod("group.add", new Object[] { groupName, hostname + ":" + port });
}
public int createShardMapping(ShardingType type, String globalGroupName) throws FabricCommunicationException {
Response r = errorSafeCallMethod("sharding.create_definition", new Object[] { type.toString(), globalGroupName });
return (Integer)r.getResultSet().get(0).get("result");
}
public void createShardTable(int shardMappingId, String database, String table, String column) throws FabricCommunicationException {
errorSafeCallMethod("sharding.add_table", new Object[] { shardMappingId, database + "." + table, column });
}
public void createShardIndex(int shardMappingId, String groupNameLowerBoundList) throws FabricCommunicationException {
String status = "ENABLED";
errorSafeCallMethod("sharding.add_shard", new Object[] { shardMappingId, groupNameLowerBoundList, status });
}
public void addServerToGroup(String groupName, String hostname, int port) throws FabricCommunicationException {
errorSafeCallMethod("group.add", new Object[] { groupName, hostname + ":" + port });
}
public void promoteServerInGroup(String groupName, String hostname, int port) throws FabricCommunicationException {
ServerGroup serverGroup = getServerGroup(groupName);
for (Server s : serverGroup.getServers()) {
if (s.getHostname().equals(hostname) && s.getPort() == port) {
errorSafeCallMethod("group.promote", new Object[] { groupName, s.getUuid() });
break;
}
}
}
public void reportServerError(Server server, String errorDescription, boolean forceFaulty) throws FabricCommunicationException {
String reporter = "MySQL Connector/J";
String command = "threat.report_error";
if (forceFaulty)
command = "threat.report_failure";
errorSafeCallMethod(command, new Object[] { server.getUuid(), reporter, errorDescription });
}
}

View file

@ -0,0 +1,12 @@
package com.mysql.fabric.proto.xmlrpc;
import com.mysql.fabric.FabricCommunicationException;
import java.util.List;
public interface XmlRpcMethodCaller {
List<?> call(String paramString, Object[] paramArrayOfObject) throws FabricCommunicationException;
void setHeader(String paramString1, String paramString2);
void clearHeader(String paramString);
}

View file

@ -0,0 +1,69 @@
package com.mysql.fabric.xmlrpc;
import com.mysql.fabric.xmlrpc.base.MethodCall;
import com.mysql.fabric.xmlrpc.base.MethodResponse;
import com.mysql.fabric.xmlrpc.base.ResponseParser;
import com.mysql.fabric.xmlrpc.exceptions.MySQLFabricException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class Client {
private URL url;
private Map<String, String> headers = new HashMap<String, String>();
public Client(String url) throws MalformedURLException {
this.url = new URL(url);
}
public void setHeader(String name, String value) {
this.headers.put(name, value);
}
public void clearHeader(String name) {
this.headers.remove(name);
}
public MethodResponse execute(MethodCall methodCall) throws IOException, ParserConfigurationException, SAXException, MySQLFabricException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection)this.url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("User-Agent", "MySQL XML-RPC");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
for (Map.Entry<String, String> entry : this.headers.entrySet())
connection.setRequestProperty(entry.getKey(), entry.getValue());
String out = methodCall.toString();
OutputStream os = connection.getOutputStream();
os.write(out.getBytes());
os.flush();
os.close();
InputStream is = connection.getInputStream();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
ResponseParser saxp = new ResponseParser();
parser.parse(is, saxp);
is.close();
MethodResponse resp = saxp.getMethodResponse();
if (resp.getFault() != null)
throw new MySQLFabricException(resp.getFault());
return resp;
} finally {
if (connection != null)
connection.disconnect();
}
}
}

View file

@ -0,0 +1,27 @@
package com.mysql.fabric.xmlrpc.base;
public class Array {
protected Data data;
public Data getData() {
return this.data;
}
public void setData(Data value) {
this.data = value;
}
public void addValue(Value v) {
if (this.data == null)
this.data = new Data();
this.data.addValue(v);
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<array>");
sb.append(this.data.toString());
sb.append("</array>");
return sb.toString();
}
}

View file

@ -0,0 +1,29 @@
package com.mysql.fabric.xmlrpc.base;
import java.util.ArrayList;
import java.util.List;
public class Data {
protected List<Value> value;
public List<Value> getValue() {
if (this.value == null)
this.value = new ArrayList<Value>();
return this.value;
}
public void addValue(Value v) {
getValue().add(v);
}
public String toString() {
StringBuffer sb = new StringBuffer();
if (this.value != null) {
sb.append("<data>");
for (int i = 0; i < this.value.size(); i++)
sb.append(this.value.get(i).toString());
sb.append("</data>");
}
return sb.toString();
}
}

View file

@ -0,0 +1,23 @@
package com.mysql.fabric.xmlrpc.base;
public class Fault {
protected Value value;
public Value getValue() {
return this.value;
}
public void setValue(Value value) {
this.value = value;
}
public String toString() {
StringBuffer sb = new StringBuffer();
if (this.value != null) {
sb.append("<fault>");
sb.append(this.value.toString());
sb.append("</fault>");
}
return sb.toString();
}
}

View file

@ -0,0 +1,39 @@
package com.mysql.fabric.xmlrpc.base;
public class Member {
protected String name;
protected Value value;
public Member() {}
public Member(String name, Value value) {
setName(name);
setValue(value);
}
public String getName() {
return this.name;
}
public void setName(String value) {
this.name = value;
}
public Value getValue() {
return this.value;
}
public void setValue(Value value) {
this.value = value;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<member>");
sb.append("<name>" + this.name + "</name>");
sb.append(this.value.toString());
sb.append("</member>");
return sb.toString();
}
}

View file

@ -0,0 +1,34 @@
package com.mysql.fabric.xmlrpc.base;
public class MethodCall {
protected String methodName;
protected Params params;
public String getMethodName() {
return this.methodName;
}
public void setMethodName(String value) {
this.methodName = value;
}
public Params getParams() {
return this.params;
}
public void setParams(Params value) {
this.params = value;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<methodCall>");
sb.append("\t<methodName>" + this.methodName + "</methodName>");
if (this.params != null)
sb.append(this.params.toString());
sb.append("</methodCall>");
return sb.toString();
}
}

View file

@ -0,0 +1,35 @@
package com.mysql.fabric.xmlrpc.base;
public class MethodResponse {
protected Params params;
protected Fault fault;
public Params getParams() {
return this.params;
}
public void setParams(Params value) {
this.params = value;
}
public Fault getFault() {
return this.fault;
}
public void setFault(Fault value) {
this.fault = value;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<methodResponse>");
if (this.params != null)
sb.append(this.params.toString());
if (this.fault != null)
sb.append(this.fault.toString());
sb.append("</methodResponse>");
return sb.toString();
}
}

View file

@ -0,0 +1,27 @@
package com.mysql.fabric.xmlrpc.base;
public class Param {
protected Value value;
public Param() {}
public Param(Value value) {
this.value = value;
}
public Value getValue() {
return this.value;
}
public void setValue(Value value) {
this.value = value;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<param>");
sb.append(this.value.toString());
sb.append("</param>");
return sb.toString();
}
}

View file

@ -0,0 +1,29 @@
package com.mysql.fabric.xmlrpc.base;
import java.util.ArrayList;
import java.util.List;
public class Params {
protected List<Param> param;
public List<Param> getParam() {
if (this.param == null)
this.param = new ArrayList<Param>();
return this.param;
}
public void addParam(Param p) {
getParam().add(p);
}
public String toString() {
StringBuffer sb = new StringBuffer();
if (this.param != null) {
sb.append("<params>");
for (int i = 0; i < this.param.size(); i++)
sb.append(this.param.get(i).toString());
sb.append("</params>");
}
return sb.toString();
}
}

View file

@ -0,0 +1,119 @@
package com.mysql.fabric.xmlrpc.base;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class ResponseParser extends DefaultHandler {
private MethodResponse resp = null;
public MethodResponse getMethodResponse() {
return this.resp;
}
Stack<Object> elNames = new Stack();
Stack<Object> objects = new Stack();
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
String thisElement = qName;
if (thisElement != null) {
this.elNames.push(thisElement);
if (thisElement.equals("methodResponse")) {
this.objects.push(new MethodResponse());
} else if (thisElement.equals("params")) {
this.objects.push(new Params());
} else if (thisElement.equals("param")) {
this.objects.push(new Param());
} else if (thisElement.equals("value")) {
this.objects.push(new Value());
} else if (thisElement.equals("array")) {
this.objects.push(new Array());
} else if (thisElement.equals("data")) {
this.objects.push(new Data());
} else if (thisElement.equals("struct")) {
this.objects.push(new Struct());
} else if (thisElement.equals("member")) {
this.objects.push(new Member());
} else if (thisElement.equals("fault")) {
this.objects.push(new Fault());
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
String thisElement = (String)this.elNames.pop();
if (thisElement != null)
if (thisElement.equals("methodResponse")) {
this.resp = (MethodResponse)this.objects.pop();
} else if (thisElement.equals("params")) {
Params pms = (Params)this.objects.pop();
MethodResponse parent = (MethodResponse)this.objects.peek();
parent.setParams(pms);
} else if (thisElement.equals("param")) {
Param p = (Param)this.objects.pop();
Params parent = (Params)this.objects.peek();
parent.addParam(p);
} else if (thisElement.equals("value")) {
Value v = (Value)this.objects.pop();
Object parent = this.objects.peek();
if (parent instanceof Data) {
((Data)parent).addValue(v);
} else if (parent instanceof Param) {
((Param)parent).setValue(v);
} else if (parent instanceof Member) {
((Member)parent).setValue(v);
} else if (parent instanceof Fault) {
((Fault)parent).setValue(v);
}
} else if (thisElement.equals("array")) {
Array a = (Array)this.objects.pop();
Value parent = (Value)this.objects.peek();
parent.setArray(a);
} else if (thisElement.equals("data")) {
Data d = (Data)this.objects.pop();
Array parent = (Array)this.objects.peek();
parent.setData(d);
} else if (thisElement.equals("struct")) {
Struct s = (Struct)this.objects.pop();
Value parent = (Value)this.objects.peek();
parent.setStruct(s);
} else if (thisElement.equals("member")) {
Member m = (Member)this.objects.pop();
Struct parent = (Struct)this.objects.peek();
parent.addMember(m);
} else if (thisElement.equals("fault")) {
Fault f = (Fault)this.objects.pop();
MethodResponse parent = (MethodResponse)this.objects.peek();
parent.setFault(f);
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
try {
String thisElement = (String)this.elNames.peek();
if (thisElement != null)
if (thisElement.equals("name")) {
((Member)this.objects.peek()).setName(new String(ch, start, length));
} else if (thisElement.equals("value")) {
((Value)this.objects.peek()).appendString(new String(ch, start, length));
} else if (thisElement.equals("i4") || thisElement.equals("int")) {
((Value)this.objects.peek()).setInt(new String(ch, start, length));
} else if (thisElement.equals("boolean")) {
((Value)this.objects.peek()).setBoolean(new String(ch, start, length));
} else if (thisElement.equals("string")) {
((Value)this.objects.peek()).appendString(new String(ch, start, length));
} else if (thisElement.equals("double")) {
((Value)this.objects.peek()).setDouble(new String(ch, start, length));
} else if (thisElement.equals("dateTime.iso8601")) {
((Value)this.objects.peek()).setDateTime(new String(ch, start, length));
} else if (thisElement.equals("base64")) {
((Value)this.objects.peek()).setBase64(new String(ch, start, length).getBytes());
}
} catch (Exception e) {
throw new SAXParseException(e.getMessage(), null, e);
}
}
}

View file

@ -0,0 +1,29 @@
package com.mysql.fabric.xmlrpc.base;
import java.util.ArrayList;
import java.util.List;
public class Struct {
protected List<Member> member;
public List<Member> getMember() {
if (this.member == null)
this.member = new ArrayList<Member>();
return this.member;
}
public void addMember(Member m) {
getMember().add(m);
}
public String toString() {
StringBuffer sb = new StringBuffer();
if (this.member != null) {
sb.append("<struct>");
for (int i = 0; i < this.member.size(); i++)
sb.append(this.member.get(i).toString());
sb.append("</struct>");
}
return sb.toString();
}
}

View file

@ -0,0 +1,205 @@
package com.mysql.fabric.xmlrpc.base;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Value {
public static final byte TYPE_i4 = 0;
public static final byte TYPE_int = 1;
public static final byte TYPE_boolean = 2;
public static final byte TYPE_string = 3;
public static final byte TYPE_double = 4;
public static final byte TYPE_dateTime_iso8601 = 5;
public static final byte TYPE_base64 = 6;
public static final byte TYPE_struct = 7;
public static final byte TYPE_array = 8;
protected Object objValue = "";
protected byte objType = 3;
private DatatypeFactory dtf = null;
public Value() {}
public Value(int value) {
setInt(value);
}
public Value(String value) {
setString(value);
}
public Value(boolean value) {
setBoolean(value);
}
public Value(double value) {
setDouble(value);
}
public Value(GregorianCalendar value) throws DatatypeConfigurationException {
setDateTime(value);
}
public Value(byte[] value) {
setBase64(value);
}
public Value(Struct value) {
setStruct(value);
}
public Value(Array value) {
setArray(value);
}
public Object getValue() {
return this.objValue;
}
public byte getType() {
return this.objType;
}
public void setInt(int value) {
this.objValue = value;
this.objType = 1;
}
public void setInt(String value) {
this.objValue = Integer.valueOf(value);
this.objType = 1;
}
public void setString(String value) {
this.objValue = value;
this.objType = 3;
}
public void appendString(String value) {
this.objValue = (this.objValue != null) ? (this.objValue + value) : value;
this.objType = 3;
}
public void setBoolean(boolean value) {
this.objValue = value;
this.objType = 2;
}
public void setBoolean(String value) {
if (value.trim().equals("1") || value.trim().equalsIgnoreCase("true")) {
this.objValue = true;
} else {
this.objValue = false;
}
this.objType = 2;
}
public void setDouble(double value) {
this.objValue = value;
this.objType = 4;
}
public void setDouble(String value) {
this.objValue = Double.valueOf(value);
this.objType = 4;
}
public void setDateTime(GregorianCalendar value) throws DatatypeConfigurationException {
if (this.dtf == null)
this.dtf = DatatypeFactory.newInstance();
this.objValue = this.dtf.newXMLGregorianCalendar(value);
this.objType = 5;
}
public void setDateTime(String value) throws DatatypeConfigurationException {
if (this.dtf == null)
this.dtf = DatatypeFactory.newInstance();
this.objValue = this.dtf.newXMLGregorianCalendar(value);
this.objType = 5;
}
public void setBase64(byte[] value) {
this.objValue = value;
this.objType = 6;
}
public void setStruct(Struct value) {
this.objValue = value;
this.objType = 7;
}
public void setArray(Array value) {
this.objValue = value;
this.objType = 8;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<value>");
switch (this.objType) {
case 0:
sb.append("<i4>" + ((Integer)this.objValue).toString() + "</i4>");
break;
case 1:
sb.append("<int>" + ((Integer)this.objValue).toString() + "</int>");
break;
case 2:
sb.append("<boolean>" + ((Boolean)this.objValue ? true : false) + "</boolean>");
break;
case 4:
sb.append("<double>" + ((Double)this.objValue).toString() + "</double>");
break;
case 5:
sb.append("<dateTime.iso8601>" + ((XMLGregorianCalendar)this.objValue).toString() + "</dateTime.iso8601>");
break;
case 6:
sb.append("<base64>" + ((byte[])this.objValue).toString() + "</base64>");
break;
case 7:
sb.append(((Struct)this.objValue).toString());
break;
case 8:
sb.append(((Array)this.objValue).toString());
break;
default:
sb.append("<string>" + escapeXMLChars(this.objValue.toString()) + "</string>");
break;
}
sb.append("</value>");
return sb.toString();
}
private String escapeXMLChars(String s) {
StringBuffer sb = new StringBuffer(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '&':
sb.append("&amp;");
break;
case '<':
sb.append("&lt;");
break;
case '>':
sb.append("&gt;");
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
}

View file

@ -0,0 +1,27 @@
package com.mysql.fabric.xmlrpc.exceptions;
import com.mysql.fabric.xmlrpc.base.Fault;
import com.mysql.fabric.xmlrpc.base.Struct;
import java.sql.SQLException;
public class MySQLFabricException extends SQLException {
static final long serialVersionUID = -8776763137552613517L;
public MySQLFabricException() {}
public MySQLFabricException(Fault fault) {
super((String)((Struct)fault.getValue().getValue()).getMember().get(1).getValue().getValue(), "", (Integer)((Struct)fault.getValue().getValue()).getMember().get(0).getValue().getValue());
}
public MySQLFabricException(String reason, String SQLState, int vendorCode) {
super(reason, SQLState, vendorCode);
}
public MySQLFabricException(String reason, String SQLState) {
super(reason, SQLState);
}
public MySQLFabricException(String reason) {
super(reason);
}
}

View file

@ -0,0 +1,37 @@
package com.mysql.jdbc;
import java.lang.ref.Reference;
public class AbandonedConnectionCleanupThread extends Thread {
private static boolean running = true;
private static Thread threadRef = null;
public AbandonedConnectionCleanupThread() {
super("Abandoned connection cleanup thread");
}
public void run() {
threadRef = this;
while (running) {
try {
Reference<? extends ConnectionImpl> ref = NonRegisteringDriver.refQueue.remove(100L);
if (ref != null)
try {
((NonRegisteringDriver.ConnectionPhantomReference)ref).cleanup();
} finally {
NonRegisteringDriver.connectionPhantomRefs.remove(ref);
}
} catch (Exception ex) {}
}
}
public static void shutdown() throws InterruptedException {
running = false;
if (threadRef != null) {
threadRef.interrupt();
threadRef.join();
threadRef = null;
}
}
}

View file

@ -0,0 +1,13 @@
package com.mysql.jdbc;
public class AssertionFailedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public static void shouldNotHappen(Exception ex) throws AssertionFailedException {
throw new AssertionFailedException(ex);
}
public AssertionFailedException(Exception ex) {
super(Messages.getString("AssertionFailedException.0") + ex.toString() + Messages.getString("AssertionFailedException.1"));
}
}

View file

@ -0,0 +1,16 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.List;
public interface AuthenticationPlugin extends Extension {
String getProtocolPluginName();
boolean requiresConfidentiality();
boolean isReusable();
void setAuthenticationParameters(String paramString1, String paramString2);
boolean nextAuthenticationStep(Buffer paramBuffer, List<Buffer> paramList) throws SQLException;
}

View file

@ -0,0 +1,9 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public interface BalanceStrategy extends Extension {
ConnectionImpl pickConnection(LoadBalancingConnectionProxy paramLoadBalancingConnectionProxy, List<String> paramList, Map<String, ConnectionImpl> paramMap, long[] paramArrayOflong, int paramInt) throws SQLException;
}

View file

@ -0,0 +1,59 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class BestResponseTimeBalanceStrategy implements BalanceStrategy {
public void destroy() {}
public void init(Connection conn, Properties props) throws SQLException {}
public ConnectionImpl pickConnection(LoadBalancingConnectionProxy proxy, List<String> configuredHosts, Map<String, ConnectionImpl> liveConnections, long[] responseTimes, int numRetries) throws SQLException {
Map<String, Long> blackList = proxy.getGlobalBlacklist();
SQLException ex = null;
for (int attempts = 0; attempts < numRetries; ) {
long minResponseTime = Long.MAX_VALUE;
int bestHostIndex = 0;
if (blackList.size() == configuredHosts.size())
blackList = proxy.getGlobalBlacklist();
for (int i = 0; i < responseTimes.length; i++) {
long candidateResponseTime = responseTimes[i];
if (candidateResponseTime < minResponseTime && !blackList.containsKey(configuredHosts.get(i))) {
if (candidateResponseTime == 0L) {
bestHostIndex = i;
break;
}
bestHostIndex = i;
minResponseTime = candidateResponseTime;
}
}
String bestHost = configuredHosts.get(bestHostIndex);
ConnectionImpl conn = liveConnections.get(bestHost);
if (conn == null)
try {
conn = proxy.createConnectionForHost(bestHost);
} catch (SQLException sqlEx) {
ex = sqlEx;
if (proxy.shouldExceptionTriggerFailover(sqlEx)) {
proxy.addToGlobalBlacklist(bestHost);
blackList.put(bestHost, null);
if (blackList.size() == configuredHosts.size()) {
attempts++;
try {
Thread.sleep(250L);
} catch (InterruptedException e) {}
blackList = proxy.getGlobalBlacklist();
}
continue;
}
throw sqlEx;
}
return conn;
}
if (ex != null)
throw ex;
return null;
}
}

View file

@ -0,0 +1,147 @@
package com.mysql.jdbc;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
public class Blob implements java.sql.Blob, OutputStreamWatcher {
private byte[] binaryData = null;
private boolean isClosed = false;
private ExceptionInterceptor exceptionInterceptor;
Blob(ExceptionInterceptor exceptionInterceptor) {
setBinaryData(Constants.EMPTY_BYTE_ARRAY);
this.exceptionInterceptor = exceptionInterceptor;
}
Blob(byte[] data, ExceptionInterceptor exceptionInterceptor) {
setBinaryData(data);
this.exceptionInterceptor = exceptionInterceptor;
}
Blob(byte[] data, ResultSetInternalMethods creatorResultSetToSet, int columnIndexToSet) {
setBinaryData(data);
}
private synchronized byte[] getBinaryData() {
return this.binaryData;
}
public synchronized InputStream getBinaryStream() throws SQLException {
checkClosed();
return new ByteArrayInputStream(getBinaryData());
}
public synchronized byte[] getBytes(long pos, int length) throws SQLException {
checkClosed();
if (pos < 1L)
throw SQLError.createSQLException(Messages.getString("Blob.2"), "S1009", this.exceptionInterceptor);
pos--;
if (pos > (long)this.binaryData.length)
throw SQLError.createSQLException("\"pos\" argument can not be larger than the BLOB's length.", "S1009", this.exceptionInterceptor);
if (pos + (long)length > (long)this.binaryData.length)
throw SQLError.createSQLException("\"pos\" + \"length\" arguments can not be larger than the BLOB's length.", "S1009", this.exceptionInterceptor);
byte[] newData = new byte[length];
System.arraycopy(getBinaryData(), (int)pos, newData, 0, length);
return newData;
}
public synchronized long length() throws SQLException {
checkClosed();
return (long)(getBinaryData()).length;
}
public synchronized long position(byte[] pattern, long start) throws SQLException {
throw SQLError.createSQLException("Not implemented", this.exceptionInterceptor);
}
public synchronized long position(java.sql.Blob pattern, long start) throws SQLException {
checkClosed();
return position(pattern.getBytes(0L, (int)pattern.length()), start);
}
private synchronized void setBinaryData(byte[] newBinaryData) {
this.binaryData = newBinaryData;
}
public synchronized OutputStream setBinaryStream(long indexToWriteAt) throws SQLException {
checkClosed();
if (indexToWriteAt < 1L)
throw SQLError.createSQLException(Messages.getString("Blob.0"), "S1009", this.exceptionInterceptor);
WatchableOutputStream bytesOut = new WatchableOutputStream();
bytesOut.setWatcher(this);
if (indexToWriteAt > 0L)
bytesOut.write(this.binaryData, 0, (int)(indexToWriteAt - 1L));
return bytesOut;
}
public synchronized int setBytes(long writeAt, byte[] bytes) throws SQLException {
checkClosed();
return setBytes(writeAt, bytes, 0, bytes.length);
}
public synchronized int setBytes(long writeAt, byte[] bytes, int offset, int length) throws SQLException {
checkClosed();
OutputStream bytesOut = setBinaryStream(writeAt);
try {
bytesOut.write(bytes, offset, length);
} catch (IOException ioEx) {
SQLException sqlEx = SQLError.createSQLException(Messages.getString("Blob.1"), "S1000", this.exceptionInterceptor);
sqlEx.initCause(ioEx);
throw sqlEx;
} finally {
try {
bytesOut.close();
} catch (IOException doNothing) {}
}
return length;
}
public synchronized void streamClosed(byte[] byteData) {
this.binaryData = byteData;
}
public synchronized void streamClosed(WatchableOutputStream out) {
int streamSize = out.size();
if (streamSize < this.binaryData.length)
out.write(this.binaryData, streamSize, this.binaryData.length - streamSize);
this.binaryData = out.toByteArray();
}
public synchronized void truncate(long len) throws SQLException {
checkClosed();
if (len < 0L)
throw SQLError.createSQLException("\"len\" argument can not be < 1.", "S1009", this.exceptionInterceptor);
if (len > (long)this.binaryData.length)
throw SQLError.createSQLException("\"len\" argument can not be larger than the BLOB's length.", "S1009", this.exceptionInterceptor);
byte[] newData = new byte[(int)len];
System.arraycopy(getBinaryData(), 0, newData, 0, (int)len);
this.binaryData = newData;
}
public synchronized void free() throws SQLException {
this.binaryData = null;
this.isClosed = true;
}
public synchronized InputStream getBinaryStream(long pos, long length) throws SQLException {
checkClosed();
if (pos < 1L)
throw SQLError.createSQLException("\"pos\" argument can not be < 1.", "S1009", this.exceptionInterceptor);
pos--;
if (pos > (long)this.binaryData.length)
throw SQLError.createSQLException("\"pos\" argument can not be larger than the BLOB's length.", "S1009", this.exceptionInterceptor);
if (pos + length > (long)this.binaryData.length)
throw SQLError.createSQLException("\"pos\" + \"length\" arguments can not be larger than the BLOB's length.", "S1009", this.exceptionInterceptor);
return new ByteArrayInputStream(getBinaryData(), (int)pos, (int)length);
}
private synchronized void checkClosed() throws SQLException {
if (this.isClosed)
throw SQLError.createSQLException("Invalid operation on closed BLOB", "S1009", this.exceptionInterceptor);
}
}

View file

@ -0,0 +1,406 @@
package com.mysql.jdbc;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class BlobFromLocator implements java.sql.Blob {
private List<String> primaryKeyColumns = null;
private List<String> primaryKeyValues = null;
private ResultSetImpl creatorResultSet;
private String blobColumnName = null;
private String tableName = null;
private int numColsInResultSet = 0;
private int numPrimaryKeys = 0;
private String quotedId;
private ExceptionInterceptor exceptionInterceptor;
BlobFromLocator(ResultSetImpl creatorResultSetToSet, int blobColumnIndex, ExceptionInterceptor exceptionInterceptor) throws SQLException {
this.exceptionInterceptor = exceptionInterceptor;
this.creatorResultSet = creatorResultSetToSet;
this.numColsInResultSet = this.creatorResultSet.fields.length;
this.quotedId = this.creatorResultSet.connection.getMetaData().getIdentifierQuoteString();
if (this.numColsInResultSet > 1) {
this.primaryKeyColumns = new ArrayList<String>();
this.primaryKeyValues = new ArrayList<String>();
for (int i = 0; i < this.numColsInResultSet; i++) {
if (this.creatorResultSet.fields[i].isPrimaryKey()) {
StringBuffer keyName = new StringBuffer();
keyName.append(this.quotedId);
String originalColumnName = this.creatorResultSet.fields[i].getOriginalName();
if (originalColumnName != null && originalColumnName.length() > 0) {
keyName.append(originalColumnName);
} else {
keyName.append(this.creatorResultSet.fields[i].getName());
}
keyName.append(this.quotedId);
this.primaryKeyColumns.add(keyName.toString());
this.primaryKeyValues.add(this.creatorResultSet.getString(i + 1));
}
}
} else {
notEnoughInformationInQuery();
}
this.numPrimaryKeys = this.primaryKeyColumns.size();
if (this.numPrimaryKeys == 0)
notEnoughInformationInQuery();
if (this.creatorResultSet.fields[0].getOriginalTableName() != null) {
StringBuffer tableNameBuffer = new StringBuffer();
String databaseName = this.creatorResultSet.fields[0].getDatabaseName();
if (databaseName != null && databaseName.length() > 0) {
tableNameBuffer.append(this.quotedId);
tableNameBuffer.append(databaseName);
tableNameBuffer.append(this.quotedId);
tableNameBuffer.append('.');
}
tableNameBuffer.append(this.quotedId);
tableNameBuffer.append(this.creatorResultSet.fields[0].getOriginalTableName());
tableNameBuffer.append(this.quotedId);
this.tableName = tableNameBuffer.toString();
} else {
StringBuffer tableNameBuffer = new StringBuffer();
tableNameBuffer.append(this.quotedId);
tableNameBuffer.append(this.creatorResultSet.fields[0].getTableName());
tableNameBuffer.append(this.quotedId);
this.tableName = tableNameBuffer.toString();
}
this.blobColumnName = this.quotedId + this.creatorResultSet.getString(blobColumnIndex) + this.quotedId;
}
private void notEnoughInformationInQuery() throws SQLException {
throw SQLError.createSQLException("Emulated BLOB locators must come from a ResultSet with only one table selected, and all primary keys selected", "S1000", this.exceptionInterceptor);
}
public OutputStream setBinaryStream(long indexToWriteAt) throws SQLException {
throw SQLError.notImplemented();
}
public InputStream getBinaryStream() throws SQLException {
return new BufferedInputStream(new LocatorInputStream(), this.creatorResultSet.connection.getLocatorFetchBufferSize());
}
public int setBytes(long writeAt, byte[] bytes, int offset, int length) throws SQLException {
java.sql.PreparedStatement pStmt = null;
if (offset + length > bytes.length)
length = bytes.length - offset;
byte[] bytesToWrite = new byte[length];
System.arraycopy(bytes, offset, bytesToWrite, 0, length);
StringBuffer query = new StringBuffer("UPDATE ");
query.append(this.tableName);
query.append(" SET ");
query.append(this.blobColumnName);
query.append(" = INSERT(");
query.append(this.blobColumnName);
query.append(", ");
query.append(writeAt);
query.append(", ");
query.append(length);
query.append(", ?) WHERE ");
query.append(this.primaryKeyColumns.get(0));
query.append(" = ?");
for (int i = 1; i < this.numPrimaryKeys; i++) {
query.append(" AND ");
query.append(this.primaryKeyColumns.get(i));
query.append(" = ?");
}
try {
pStmt = this.creatorResultSet.connection.prepareStatement(query.toString());
pStmt.setBytes(1, bytesToWrite);
for (int j = 0; j < this.numPrimaryKeys; j++)
pStmt.setString(j + 2, this.primaryKeyValues.get(j));
int rowsUpdated = pStmt.executeUpdate();
if (rowsUpdated != 1)
throw SQLError.createSQLException("BLOB data not found! Did primary keys change?", "S1000", this.exceptionInterceptor);
} finally {
if (pStmt != null) {
try {
pStmt.close();
} catch (SQLException sqlEx) {}
pStmt = null;
}
}
return (int)length();
}
public int setBytes(long writeAt, byte[] bytes) throws SQLException {
return setBytes(writeAt, bytes, 0, bytes.length);
}
public byte[] getBytes(long pos, int length) throws SQLException {
java.sql.PreparedStatement pStmt = null;
try {
pStmt = createGetBytesStatement();
return getBytesInternal(pStmt, pos, length);
} finally {
if (pStmt != null) {
try {
pStmt.close();
} catch (SQLException sqlEx) {}
pStmt = null;
}
}
}
public long length() throws SQLException {
ResultSet blobRs = null;
java.sql.PreparedStatement pStmt = null;
StringBuffer query = new StringBuffer("SELECT LENGTH(");
query.append(this.blobColumnName);
query.append(") FROM ");
query.append(this.tableName);
query.append(" WHERE ");
query.append(this.primaryKeyColumns.get(0));
query.append(" = ?");
for (int i = 1; i < this.numPrimaryKeys; i++) {
query.append(" AND ");
query.append(this.primaryKeyColumns.get(i));
query.append(" = ?");
}
try {
pStmt = this.creatorResultSet.connection.prepareStatement(query.toString());
for (int j = 0; j < this.numPrimaryKeys; j++)
pStmt.setString(j + 1, this.primaryKeyValues.get(j));
blobRs = pStmt.executeQuery();
if (blobRs.next())
return blobRs.getLong(1);
throw SQLError.createSQLException("BLOB data not found! Did primary keys change?", "S1000", this.exceptionInterceptor);
} finally {
if (blobRs != null) {
try {
blobRs.close();
} catch (SQLException sqlEx) {}
blobRs = null;
}
if (pStmt != null) {
try {
pStmt.close();
} catch (SQLException sqlEx) {}
pStmt = null;
}
}
}
public long position(java.sql.Blob pattern, long start) throws SQLException {
return position(pattern.getBytes(0L, (int)pattern.length()), start);
}
public long position(byte[] pattern, long start) throws SQLException {
ResultSet blobRs = null;
java.sql.PreparedStatement pStmt = null;
StringBuffer query = new StringBuffer("SELECT LOCATE(");
query.append("?, ");
query.append(this.blobColumnName);
query.append(", ");
query.append(start);
query.append(") FROM ");
query.append(this.tableName);
query.append(" WHERE ");
query.append(this.primaryKeyColumns.get(0));
query.append(" = ?");
for (int i = 1; i < this.numPrimaryKeys; i++) {
query.append(" AND ");
query.append(this.primaryKeyColumns.get(i));
query.append(" = ?");
}
try {
pStmt = this.creatorResultSet.connection.prepareStatement(query.toString());
pStmt.setBytes(1, pattern);
for (int j = 0; j < this.numPrimaryKeys; j++)
pStmt.setString(j + 2, this.primaryKeyValues.get(j));
blobRs = pStmt.executeQuery();
if (blobRs.next())
return blobRs.getLong(1);
throw SQLError.createSQLException("BLOB data not found! Did primary keys change?", "S1000", this.exceptionInterceptor);
} finally {
if (blobRs != null) {
try {
blobRs.close();
} catch (SQLException sqlEx) {}
blobRs = null;
}
if (pStmt != null) {
try {
pStmt.close();
} catch (SQLException sqlEx) {}
pStmt = null;
}
}
}
public void truncate(long length) throws SQLException {
java.sql.PreparedStatement pStmt = null;
StringBuffer query = new StringBuffer("UPDATE ");
query.append(this.tableName);
query.append(" SET ");
query.append(this.blobColumnName);
query.append(" = LEFT(");
query.append(this.blobColumnName);
query.append(", ");
query.append(length);
query.append(") WHERE ");
query.append(this.primaryKeyColumns.get(0));
query.append(" = ?");
for (int i = 1; i < this.numPrimaryKeys; i++) {
query.append(" AND ");
query.append(this.primaryKeyColumns.get(i));
query.append(" = ?");
}
try {
pStmt = this.creatorResultSet.connection.prepareStatement(query.toString());
for (int j = 0; j < this.numPrimaryKeys; j++)
pStmt.setString(j + 1, this.primaryKeyValues.get(j));
int rowsUpdated = pStmt.executeUpdate();
if (rowsUpdated != 1)
throw SQLError.createSQLException("BLOB data not found! Did primary keys change?", "S1000", this.exceptionInterceptor);
} finally {
if (pStmt != null) {
try {
pStmt.close();
} catch (SQLException sqlEx) {}
pStmt = null;
}
}
}
java.sql.PreparedStatement createGetBytesStatement() throws SQLException {
StringBuffer query = new StringBuffer("SELECT SUBSTRING(");
query.append(this.blobColumnName);
query.append(", ");
query.append("?");
query.append(", ");
query.append("?");
query.append(") FROM ");
query.append(this.tableName);
query.append(" WHERE ");
query.append(this.primaryKeyColumns.get(0));
query.append(" = ?");
for (int i = 1; i < this.numPrimaryKeys; i++) {
query.append(" AND ");
query.append(this.primaryKeyColumns.get(i));
query.append(" = ?");
}
return this.creatorResultSet.connection.prepareStatement(query.toString());
}
byte[] getBytesInternal(java.sql.PreparedStatement pStmt, long pos, int length) throws SQLException {
ResultSet blobRs = null;
try {
pStmt.setLong(1, pos);
pStmt.setInt(2, length);
for (int i = 0; i < this.numPrimaryKeys; i++)
pStmt.setString(i + 3, this.primaryKeyValues.get(i));
blobRs = pStmt.executeQuery();
if (blobRs.next())
return ((ResultSetImpl)blobRs).getBytes(1, true);
throw SQLError.createSQLException("BLOB data not found! Did primary keys change?", "S1000", this.exceptionInterceptor);
} finally {
if (blobRs != null) {
try {
blobRs.close();
} catch (SQLException sqlEx) {}
blobRs = null;
}
}
}
class LocatorInputStream extends InputStream {
long currentPositionInBlob = 0L;
long length = 0L;
java.sql.PreparedStatement pStmt = null;
LocatorInputStream() throws SQLException {
this.length = BlobFromLocator.this.length();
this.pStmt = BlobFromLocator.this.createGetBytesStatement();
}
LocatorInputStream(long pos, long len) throws SQLException {
this.length = pos + len;
this.currentPositionInBlob = pos;
long blobLength = BlobFromLocator.this.length();
if (pos + len > blobLength)
throw SQLError.createSQLException(Messages.getString("Blob.invalidStreamLength", new Object[] { blobLength, pos, len }), "S1009", BlobFromLocator.this.exceptionInterceptor);
if (pos < 1L)
throw SQLError.createSQLException(Messages.getString("Blob.invalidStreamPos"), "S1009", BlobFromLocator.this.exceptionInterceptor);
if (pos > blobLength)
throw SQLError.createSQLException(Messages.getString("Blob.invalidStreamPos"), "S1009", BlobFromLocator.this.exceptionInterceptor);
}
public int read() throws IOException {
if (this.currentPositionInBlob + 1L > this.length)
return -1;
try {
byte[] asBytes = BlobFromLocator.this.getBytesInternal(this.pStmt, this.currentPositionInBlob++ + 1L, 1);
if (asBytes == null)
return -1;
return asBytes[0];
} catch (SQLException sqlEx) {
throw new IOException(sqlEx.toString());
}
}
public int read(byte[] b, int off, int len) throws IOException {
if (this.currentPositionInBlob + 1L > this.length)
return -1;
try {
byte[] asBytes = BlobFromLocator.this.getBytesInternal(this.pStmt, this.currentPositionInBlob + 1L, len);
if (asBytes == null)
return -1;
System.arraycopy(asBytes, 0, b, off, asBytes.length);
this.currentPositionInBlob += (long)asBytes.length;
return asBytes.length;
} catch (SQLException sqlEx) {
throw new IOException(sqlEx.toString());
}
}
public int read(byte[] b) throws IOException {
if (this.currentPositionInBlob + 1L > this.length)
return -1;
try {
byte[] asBytes = BlobFromLocator.this.getBytesInternal(this.pStmt, this.currentPositionInBlob + 1L, b.length);
if (asBytes == null)
return -1;
System.arraycopy(asBytes, 0, b, 0, asBytes.length);
this.currentPositionInBlob += (long)asBytes.length;
return asBytes.length;
} catch (SQLException sqlEx) {
throw new IOException(sqlEx.toString());
}
}
public void close() throws IOException {
if (this.pStmt != null)
try {
this.pStmt.close();
} catch (SQLException sqlEx) {
throw new IOException(sqlEx.toString());
}
super.close();
}
}
public void free() throws SQLException {
this.creatorResultSet = null;
this.primaryKeyColumns = null;
this.primaryKeyValues = null;
}
public InputStream getBinaryStream(long pos, long length) throws SQLException {
return new LocatorInputStream(pos, length);
}
}

View file

@ -0,0 +1,475 @@
package com.mysql.jdbc;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.sql.SQLException;
public class Buffer {
static final int MAX_BYTES_TO_DUMP = 512;
static final int NO_LENGTH_LIMIT = -1;
static final long NULL_LENGTH = -1L;
private int bufLength = 0;
private byte[] byteBuffer;
private int position = 0;
protected boolean wasMultiPacket = false;
public Buffer(byte[] buf) {
this.byteBuffer = buf;
setBufLength(buf.length);
}
Buffer(int size) {
this.byteBuffer = new byte[size];
setBufLength(this.byteBuffer.length);
this.position = 4;
}
final void clear() {
this.position = 4;
}
final void dump() {
dump(getBufLength());
}
final String dump(int numBytes) {
return StringUtils.dumpAsHex(getBytes(0, (numBytes > getBufLength()) ? getBufLength() : numBytes), (numBytes > getBufLength()) ? getBufLength() : numBytes);
}
final String dumpClampedBytes(int numBytes) {
int numBytesToDump = (numBytes < 512) ? numBytes : 512;
String dumped = StringUtils.dumpAsHex(getBytes(0, (numBytesToDump > getBufLength()) ? getBufLength() : numBytesToDump), (numBytesToDump > getBufLength()) ? getBufLength() : numBytesToDump);
if (numBytesToDump < numBytes)
return dumped + " ....(packet exceeds max. dump length)";
return dumped;
}
final void dumpHeader() {
for (int i = 0; i < 4; i++) {
String hexVal = Integer.toHexString(readByte(i) & 0xFF);
if (hexVal.length() == 1)
hexVal = "0" + hexVal;
System.out.print(hexVal + " ");
}
}
final void dumpNBytes(int start, int nBytes) {
StringBuffer asciiBuf = new StringBuffer();
for (int i = start; i < start + nBytes && i < getBufLength(); i++) {
String hexVal = Integer.toHexString(readByte(i) & 0xFF);
if (hexVal.length() == 1)
hexVal = "0" + hexVal;
System.out.print(hexVal + " ");
if (readByte(i) > 32 && readByte(i) < Byte.MAX_VALUE) {
asciiBuf.append((char)readByte(i));
} else {
asciiBuf.append(".");
}
asciiBuf.append(" ");
}
System.out.println(" " + asciiBuf.toString());
}
final void ensureCapacity(int additionalData) throws SQLException {
if (this.position + additionalData > getBufLength())
if (this.position + additionalData < this.byteBuffer.length) {
setBufLength(this.byteBuffer.length);
} else {
int newLength = (int)((double)this.byteBuffer.length * 1.25D);
if (newLength < this.byteBuffer.length + additionalData)
newLength = this.byteBuffer.length + (int)((double)additionalData * 1.25D);
if (newLength < this.byteBuffer.length)
newLength = this.byteBuffer.length + additionalData;
byte[] newBytes = new byte[newLength];
System.arraycopy(this.byteBuffer, 0, newBytes, 0, this.byteBuffer.length);
this.byteBuffer = newBytes;
setBufLength(this.byteBuffer.length);
}
}
public int fastSkipLenString() {
long len = readFieldLength();
this.position = (int)((long)this.position + len);
return (int)len;
}
public void fastSkipLenByteArray() {
long len = readFieldLength();
if (len == -1L || len == 0L)
return;
this.position = (int)((long)this.position + len);
}
protected final byte[] getBufferSource() {
return this.byteBuffer;
}
public int getBufLength() {
return this.bufLength;
}
public byte[] getByteBuffer() {
return this.byteBuffer;
}
final byte[] getBytes(int len) {
byte[] b = new byte[len];
System.arraycopy(this.byteBuffer, this.position, b, 0, len);
this.position += len;
return b;
}
byte[] getBytes(int offset, int len) {
byte[] dest = new byte[len];
System.arraycopy(this.byteBuffer, offset, dest, 0, len);
return dest;
}
int getCapacity() {
return this.byteBuffer.length;
}
public ByteBuffer getNioBuffer() {
throw new IllegalArgumentException(Messages.getString("ByteArrayBuffer.0"));
}
public int getPosition() {
return this.position;
}
final boolean isLastDataPacket() {
return (getBufLength() < 9 && (this.byteBuffer[0] & 0xFF) == 254);
}
final boolean isAuthMethodSwitchRequestPacket() {
return ((this.byteBuffer[0] & 0xFF) == 254);
}
final boolean isOKPacket() {
return ((this.byteBuffer[0] & 0xFF) == 0);
}
final boolean isRawPacket() {
return ((this.byteBuffer[0] & 0xFF) == 1);
}
final long newReadLength() {
int sw = this.byteBuffer[this.position++] & 0xFF;
switch (sw) {
case 251:
return 0L;
case 252:
return (long)readInt();
case 253:
return (long)readLongInt();
case 254:
return readLongLong();
}
return (long)sw;
}
final byte readByte() {
return this.byteBuffer[this.position++];
}
final byte readByte(int readAt) {
return this.byteBuffer[readAt];
}
final long readFieldLength() {
int sw = this.byteBuffer[this.position++] & 0xFF;
switch (sw) {
case 251:
return -1L;
case 252:
return (long)readInt();
case 253:
return (long)readLongInt();
case 254:
return readLongLong();
}
return (long)sw;
}
final int readInt() {
byte[] b = this.byteBuffer;
return b[this.position++] & 0xFF | (b[this.position++] & 0xFF) << 8;
}
final int readIntAsLong() {
byte[] b = this.byteBuffer;
return b[this.position++] & 0xFF | (b[this.position++] & 0xFF) << 8 | (b[this.position++] & 0xFF) << 16 | (b[this.position++] & 0xFF) << 24;
}
final byte[] readLenByteArray(int offset) {
long len = readFieldLength();
if (len == -1L)
return null;
if (len == 0L)
return Constants.EMPTY_BYTE_ARRAY;
this.position += offset;
return getBytes((int)len);
}
final long readLength() {
int sw = this.byteBuffer[this.position++] & 0xFF;
switch (sw) {
case 251:
return 0L;
case 252:
return (long)readInt();
case 253:
return (long)readLongInt();
case 254:
return readLong();
}
return (long)sw;
}
final long readLong() {
byte[] b = this.byteBuffer;
return (long)b[this.position++] & 0xFFL | ((long)b[this.position++] & 0xFFL) << 8L | (long)(b[this.position++] & 0xFF) << 16L | (long)(b[this.position++] & 0xFF) << 24L;
}
final int readLongInt() {
byte[] b = this.byteBuffer;
return b[this.position++] & 0xFF | (b[this.position++] & 0xFF) << 8 | (b[this.position++] & 0xFF) << 16;
}
final long readLongLong() {
byte[] b = this.byteBuffer;
return (long)(b[this.position++] & 0xFF) | (long)(b[this.position++] & 0xFF) << 8L | (long)(b[this.position++] & 0xFF) << 16L | (long)(b[this.position++] & 0xFF) << 24L | (long)(b[this.position++] & 0xFF) << 32L | (long)(b[this.position++] & 0xFF) << 40L | (long)(b[this.position++] & 0xFF) << 48L | (long)(b[this.position++] & 0xFF) << 56L;
}
final int readnBytes() {
int sw = this.byteBuffer[this.position++] & 0xFF;
switch (sw) {
case 1:
return this.byteBuffer[this.position++] & 0xFF;
case 2:
return readInt();
case 3:
return readLongInt();
case 4:
return (int)readLong();
}
return 255;
}
public final String readString() {
int i = this.position;
int len = 0;
int maxLen = getBufLength();
while (i < maxLen && this.byteBuffer[i] != 0) {
len++;
i++;
}
String s = StringUtils.toString(this.byteBuffer, this.position, len);
this.position += len + 1;
return s;
}
final String readString(String encoding, ExceptionInterceptor exceptionInterceptor) throws SQLException {
int i = this.position;
int len = 0;
int maxLen = getBufLength();
while (i < maxLen && this.byteBuffer[i] != 0) {
len++;
i++;
}
try {
return StringUtils.toString(this.byteBuffer, this.position, len, encoding);
} catch (UnsupportedEncodingException uEE) {
throw SQLError.createSQLException(Messages.getString("ByteArrayBuffer.1") + encoding + "'", "S1009", exceptionInterceptor);
} finally {
this.position += len + 1;
}
}
final String readString(String encoding, ExceptionInterceptor exceptionInterceptor, int expectedLength) throws SQLException {
if (this.position + expectedLength > getBufLength())
throw SQLError.createSQLException(Messages.getString("ByteArrayBuffer.2"), "S1009", exceptionInterceptor);
try {
return StringUtils.toString(this.byteBuffer, this.position, expectedLength, encoding);
} catch (UnsupportedEncodingException uEE) {
throw SQLError.createSQLException(Messages.getString("ByteArrayBuffer.1") + encoding + "'", "S1009", exceptionInterceptor);
} finally {
this.position += expectedLength;
}
}
public void setBufLength(int bufLengthToSet) {
this.bufLength = bufLengthToSet;
}
public void setByteBuffer(byte[] byteBufferToSet) {
this.byteBuffer = byteBufferToSet;
}
public void setPosition(int positionToSet) {
this.position = positionToSet;
}
public void setWasMultiPacket(boolean flag) {
this.wasMultiPacket = flag;
}
public String toString() {
return dumpClampedBytes(getPosition());
}
public String toSuperString() {
return super.toString();
}
public boolean wasMultiPacket() {
return this.wasMultiPacket;
}
public final void writeByte(byte b) throws SQLException {
ensureCapacity(1);
this.byteBuffer[this.position++] = b;
}
public final void writeBytesNoNull(byte[] bytes) throws SQLException {
int len = bytes.length;
ensureCapacity(len);
System.arraycopy(bytes, 0, this.byteBuffer, this.position, len);
this.position += len;
}
final void writeBytesNoNull(byte[] bytes, int offset, int length) throws SQLException {
ensureCapacity(length);
System.arraycopy(bytes, offset, this.byteBuffer, this.position, length);
this.position += length;
}
final void writeDouble(double d) throws SQLException {
long l = Double.doubleToLongBits(d);
writeLongLong(l);
}
final void writeFieldLength(long length) throws SQLException {
if (length < 251L) {
writeByte((byte)(int)length);
} else if (length < 65536L) {
ensureCapacity(3);
writeByte((byte)-4);
writeInt((int)length);
} else if (length < 16777216L) {
ensureCapacity(4);
writeByte((byte)-3);
writeLongInt((int)length);
} else {
ensureCapacity(9);
writeByte((byte)-2);
writeLongLong(length);
}
}
final void writeFloat(float f) throws SQLException {
ensureCapacity(4);
int i = Float.floatToIntBits(f);
byte[] b = this.byteBuffer;
b[this.position++] = (byte)(i & 0xFF);
b[this.position++] = (byte)(i >>> 8);
b[this.position++] = (byte)(i >>> 16);
b[this.position++] = (byte)(i >>> 24);
}
final void writeInt(int i) throws SQLException {
ensureCapacity(2);
byte[] b = this.byteBuffer;
b[this.position++] = (byte)(i & 0xFF);
b[this.position++] = (byte)(i >>> 8);
}
final void writeLenBytes(byte[] b) throws SQLException {
int len = b.length;
ensureCapacity(len + 9);
writeFieldLength((long)len);
System.arraycopy(b, 0, this.byteBuffer, this.position, len);
this.position += len;
}
final void writeLenString(String s, String encoding, String serverEncoding, SingleByteCharsetConverter converter, boolean parserKnowsUnicode, MySQLConnection conn) throws UnsupportedEncodingException, SQLException {
byte[] b = null;
if (converter != null) {
b = converter.toBytes(s);
} else {
b = StringUtils.getBytes(s, encoding, serverEncoding, parserKnowsUnicode, conn, conn.getExceptionInterceptor());
}
int len = b.length;
ensureCapacity(len + 9);
writeFieldLength((long)len);
System.arraycopy(b, 0, this.byteBuffer, this.position, len);
this.position += len;
}
final void writeLong(long i) throws SQLException {
ensureCapacity(4);
byte[] b = this.byteBuffer;
b[this.position++] = (byte)(int)(i & 0xFFL);
b[this.position++] = (byte)(int)(i >>> 8L);
b[this.position++] = (byte)(int)(i >>> 16L);
b[this.position++] = (byte)(int)(i >>> 24L);
}
final void writeLongInt(int i) throws SQLException {
ensureCapacity(3);
byte[] b = this.byteBuffer;
b[this.position++] = (byte)(i & 0xFF);
b[this.position++] = (byte)(i >>> 8);
b[this.position++] = (byte)(i >>> 16);
}
final void writeLongLong(long i) throws SQLException {
ensureCapacity(8);
byte[] b = this.byteBuffer;
b[this.position++] = (byte)(int)(i & 0xFFL);
b[this.position++] = (byte)(int)(i >>> 8L);
b[this.position++] = (byte)(int)(i >>> 16L);
b[this.position++] = (byte)(int)(i >>> 24L);
b[this.position++] = (byte)(int)(i >>> 32L);
b[this.position++] = (byte)(int)(i >>> 40L);
b[this.position++] = (byte)(int)(i >>> 48L);
b[this.position++] = (byte)(int)(i >>> 56L);
}
final void writeString(String s) throws SQLException {
ensureCapacity(s.length() * 3 + 1);
writeStringNoNull(s);
this.byteBuffer[this.position++] = 0;
}
final void writeString(String s, String encoding, MySQLConnection conn) throws SQLException {
ensureCapacity(s.length() * 3 + 1);
try {
writeStringNoNull(s, encoding, encoding, false, conn);
} catch (UnsupportedEncodingException ue) {
throw new SQLException(ue.toString(), "S1000");
}
this.byteBuffer[this.position++] = 0;
}
final void writeStringNoNull(String s) throws SQLException {
int len = s.length();
ensureCapacity(len * 3);
System.arraycopy(StringUtils.getBytes(s), 0, this.byteBuffer, this.position, len);
this.position += len;
}
final void writeStringNoNull(String s, String encoding, String serverEncoding, boolean parserKnowsUnicode, MySQLConnection conn) throws UnsupportedEncodingException, SQLException {
byte[] b = StringUtils.getBytes(s, encoding, serverEncoding, parserKnowsUnicode, conn, conn.getExceptionInterceptor());
int len = b.length;
ensureCapacity(len);
System.arraycopy(b, 0, this.byteBuffer, this.position, len);
this.position += len;
}
}

View file

@ -0,0 +1,459 @@
package com.mysql.jdbc;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;
public class BufferRow extends ResultSetRow {
private Buffer rowFromServer;
private int homePosition = 0;
private int preNullBitmaskHomePosition = 0;
private int lastRequestedIndex = -1;
private int lastRequestedPos;
private Field[] metadata;
private boolean isBinaryEncoded;
private boolean[] isNull;
private List<InputStream> openStreams;
public BufferRow(Buffer buf, Field[] fields, boolean isBinaryEncoded, ExceptionInterceptor exceptionInterceptor) throws SQLException {
super(exceptionInterceptor);
this.rowFromServer = buf;
this.metadata = fields;
this.isBinaryEncoded = isBinaryEncoded;
this.homePosition = this.rowFromServer.getPosition();
this.preNullBitmaskHomePosition = this.homePosition;
if (fields != null)
setMetadata(fields);
}
public synchronized void closeOpenStreams() {
if (this.openStreams != null) {
Iterator<InputStream> iter = this.openStreams.iterator();
while (iter.hasNext()) {
try {
iter.next().close();
} catch (IOException e) {}
}
this.openStreams.clear();
}
}
private int findAndSeekToOffset(int index) throws SQLException {
if (!this.isBinaryEncoded) {
if (index == 0) {
this.lastRequestedIndex = 0;
this.lastRequestedPos = this.homePosition;
this.rowFromServer.setPosition(this.homePosition);
return 0;
}
if (index == this.lastRequestedIndex) {
this.rowFromServer.setPosition(this.lastRequestedPos);
return this.lastRequestedPos;
}
int startingIndex = 0;
if (index > this.lastRequestedIndex) {
if (this.lastRequestedIndex >= 0) {
startingIndex = this.lastRequestedIndex;
} else {
startingIndex = 0;
}
this.rowFromServer.setPosition(this.lastRequestedPos);
} else {
this.rowFromServer.setPosition(this.homePosition);
}
for (int i = startingIndex; i < index; i++)
this.rowFromServer.fastSkipLenByteArray();
this.lastRequestedIndex = index;
this.lastRequestedPos = this.rowFromServer.getPosition();
return this.lastRequestedPos;
}
return findAndSeekToOffsetForBinaryEncoding(index);
}
private int findAndSeekToOffsetForBinaryEncoding(int index) throws SQLException {
if (index == 0) {
this.lastRequestedIndex = 0;
this.lastRequestedPos = this.homePosition;
this.rowFromServer.setPosition(this.homePosition);
return 0;
}
if (index == this.lastRequestedIndex) {
this.rowFromServer.setPosition(this.lastRequestedPos);
return this.lastRequestedPos;
}
int startingIndex = 0;
if (index > this.lastRequestedIndex) {
if (this.lastRequestedIndex >= 0) {
startingIndex = this.lastRequestedIndex;
} else {
startingIndex = 0;
this.lastRequestedPos = this.homePosition;
}
this.rowFromServer.setPosition(this.lastRequestedPos);
} else {
this.rowFromServer.setPosition(this.homePosition);
}
for (int i = startingIndex; i < index; i++) {
if (!this.isNull[i]) {
int curPosition = this.rowFromServer.getPosition();
switch (this.metadata[i].getMysqlType()) {
case 6:
break;
case 1:
this.rowFromServer.setPosition(curPosition + 1);
break;
case 2:
case 13:
this.rowFromServer.setPosition(curPosition + 2);
break;
case 3:
case 9:
this.rowFromServer.setPosition(curPosition + 4);
break;
case 8:
this.rowFromServer.setPosition(curPosition + 8);
break;
case 4:
this.rowFromServer.setPosition(curPosition + 4);
break;
case 5:
this.rowFromServer.setPosition(curPosition + 8);
break;
case 11:
this.rowFromServer.fastSkipLenByteArray();
break;
case 10:
this.rowFromServer.fastSkipLenByteArray();
break;
case 7:
case 12:
this.rowFromServer.fastSkipLenByteArray();
break;
case 0:
case 15:
case 16:
case 246:
case 249:
case 250:
case 251:
case 252:
case 253:
case 254:
case 255:
this.rowFromServer.fastSkipLenByteArray();
break;
default:
throw SQLError.createSQLException(Messages.getString("MysqlIO.97") + this.metadata[i].getMysqlType() + Messages.getString("MysqlIO.98") + (i + 1) + Messages.getString("MysqlIO.99") + this.metadata.length + Messages.getString("MysqlIO.100"), "S1000", this.exceptionInterceptor);
}
}
}
this.lastRequestedIndex = index;
this.lastRequestedPos = this.rowFromServer.getPosition();
return this.lastRequestedPos;
}
public synchronized InputStream getBinaryInputStream(int columnIndex) throws SQLException {
if (this.isBinaryEncoded &&
isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
if (length == -1L)
return null;
InputStream stream = new ByteArrayInputStream(this.rowFromServer.getByteBuffer(), offset, (int)length);
if (this.openStreams == null)
this.openStreams = new LinkedList<InputStream>();
return stream;
}
public byte[] getColumnValue(int index) throws SQLException {
findAndSeekToOffset(index);
if (!this.isBinaryEncoded)
return this.rowFromServer.readLenByteArray(0);
if (this.isNull[index])
return null;
switch (this.metadata[index].getMysqlType()) {
case 6:
return null;
case 1:
return new byte[] { this.rowFromServer.readByte() };
case 2:
case 13:
return this.rowFromServer.getBytes(2);
case 3:
case 9:
return this.rowFromServer.getBytes(4);
case 8:
return this.rowFromServer.getBytes(8);
case 4:
return this.rowFromServer.getBytes(4);
case 5:
return this.rowFromServer.getBytes(8);
case 0:
case 7:
case 10:
case 11:
case 12:
case 15:
case 16:
case 246:
case 249:
case 250:
case 251:
case 252:
case 253:
case 254:
case 255:
return this.rowFromServer.readLenByteArray(0);
}
throw SQLError.createSQLException(Messages.getString("MysqlIO.97") + this.metadata[index].getMysqlType() + Messages.getString("MysqlIO.98") + (index + 1) + Messages.getString("MysqlIO.99") + this.metadata.length + Messages.getString("MysqlIO.100"), "S1000", this.exceptionInterceptor);
}
public int getInt(int columnIndex) throws SQLException {
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
if (length == -1L)
return 0;
return StringUtils.getInt(this.rowFromServer.getByteBuffer(), offset, offset + (int)length);
}
public long getLong(int columnIndex) throws SQLException {
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
if (length == -1L)
return 0L;
return StringUtils.getLong(this.rowFromServer.getByteBuffer(), offset, offset + (int)length);
}
public double getNativeDouble(int columnIndex) throws SQLException {
if (isNull(columnIndex))
return 0.0D;
findAndSeekToOffset(columnIndex);
int offset = this.rowFromServer.getPosition();
return getNativeDouble(this.rowFromServer.getByteBuffer(), offset);
}
public float getNativeFloat(int columnIndex) throws SQLException {
if (isNull(columnIndex))
return 0.0F;
findAndSeekToOffset(columnIndex);
int offset = this.rowFromServer.getPosition();
return getNativeFloat(this.rowFromServer.getByteBuffer(), offset);
}
public int getNativeInt(int columnIndex) throws SQLException {
if (isNull(columnIndex))
return 0;
findAndSeekToOffset(columnIndex);
int offset = this.rowFromServer.getPosition();
return getNativeInt(this.rowFromServer.getByteBuffer(), offset);
}
public long getNativeLong(int columnIndex) throws SQLException {
if (isNull(columnIndex))
return 0L;
findAndSeekToOffset(columnIndex);
int offset = this.rowFromServer.getPosition();
return getNativeLong(this.rowFromServer.getByteBuffer(), offset);
}
public short getNativeShort(int columnIndex) throws SQLException {
if (isNull(columnIndex))
return 0;
findAndSeekToOffset(columnIndex);
int offset = this.rowFromServer.getPosition();
return getNativeShort(this.rowFromServer.getByteBuffer(), offset);
}
public Timestamp getNativeTimestamp(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
if (isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
return getNativeTimestamp(this.rowFromServer.getByteBuffer(), offset, (int)length, targetCalendar, tz, rollForward, conn, rs);
}
public Reader getReader(int columnIndex) throws SQLException {
InputStream stream = getBinaryInputStream(columnIndex);
if (stream == null)
return null;
try {
return new InputStreamReader(stream, this.metadata[columnIndex].getEncoding());
} catch (UnsupportedEncodingException e) {
SQLException sqlEx = SQLError.createSQLException("", this.exceptionInterceptor);
sqlEx.initCause(e);
throw sqlEx;
}
}
public String getString(int columnIndex, String encoding, MySQLConnection conn) throws SQLException {
if (this.isBinaryEncoded &&
isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
if (length == -1L)
return null;
if (length == 0L)
return "";
int offset = this.rowFromServer.getPosition();
return getString(encoding, conn, this.rowFromServer.getByteBuffer(), offset, (int)length);
}
public Time getTimeFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
if (isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
return getTimeFast(columnIndex, this.rowFromServer.getByteBuffer(), offset, (int)length, targetCalendar, tz, rollForward, conn, rs);
}
public Timestamp getTimestampFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
if (isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
return getTimestampFast(columnIndex, this.rowFromServer.getByteBuffer(), offset, (int)length, targetCalendar, tz, rollForward, conn, rs);
}
public boolean isFloatingPointNumber(int index) throws SQLException {
if (this.isBinaryEncoded) {
switch (this.metadata[index].getSQLType()) {
case 2:
case 3:
case 6:
case 8:
return true;
}
return false;
}
findAndSeekToOffset(index);
long length = this.rowFromServer.readFieldLength();
if (length == -1L)
return false;
if (length == 0L)
return false;
int offset = this.rowFromServer.getPosition();
byte[] buffer = this.rowFromServer.getByteBuffer();
for (int i = 0; i < (int)length; i++) {
char c = (char)buffer[offset + i];
if (c == 'e' || c == 'E')
return true;
}
return false;
}
public boolean isNull(int index) throws SQLException {
if (!this.isBinaryEncoded) {
findAndSeekToOffset(index);
return (this.rowFromServer.readFieldLength() == -1L);
}
return this.isNull[index];
}
public long length(int index) throws SQLException {
findAndSeekToOffset(index);
long length = this.rowFromServer.readFieldLength();
if (length == -1L)
return 0L;
return length;
}
public void setColumnValue(int index, byte[] value) throws SQLException {
throw new OperationNotSupportedException();
}
public ResultSetRow setMetadata(Field[] f) throws SQLException {
super.setMetadata(f);
if (this.isBinaryEncoded)
setupIsNullBitmask();
return this;
}
private void setupIsNullBitmask() throws SQLException {
if (this.isNull != null)
return;
this.rowFromServer.setPosition(this.preNullBitmaskHomePosition);
int nullCount = (this.metadata.length + 9) / 8;
byte[] nullBitMask = new byte[nullCount];
for (int i = 0; i < nullCount; i++)
nullBitMask[i] = this.rowFromServer.readByte();
this.homePosition = this.rowFromServer.getPosition();
this.isNull = new boolean[this.metadata.length];
int nullMaskPos = 0;
int bit = 4;
for (int j = 0; j < this.metadata.length; j++) {
this.isNull[j] = ((nullBitMask[nullMaskPos] & bit) != 0);
if (((bit <<= 1) & 0xFF) == 0) {
bit = 1;
nullMaskPos++;
}
}
}
public Date getDateFast(int columnIndex, MySQLConnection conn, ResultSetImpl rs, Calendar targetCalendar) throws SQLException {
if (isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
return getDateFast(columnIndex, this.rowFromServer.getByteBuffer(), offset, (int)length, conn, rs, targetCalendar);
}
public Date getNativeDate(int columnIndex, MySQLConnection conn, ResultSetImpl rs, Calendar cal) throws SQLException {
if (isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
return getNativeDate(columnIndex, this.rowFromServer.getByteBuffer(), offset, (int)length, conn, rs, cal);
}
public Object getNativeDateTimeValue(int columnIndex, Calendar targetCalendar, int jdbcType, int mysqlType, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
if (isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
return getNativeDateTimeValue(columnIndex, this.rowFromServer.getByteBuffer(), offset, (int)length, targetCalendar, jdbcType, mysqlType, tz, rollForward, conn, rs);
}
public Time getNativeTime(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
if (isNull(columnIndex))
return null;
findAndSeekToOffset(columnIndex);
long length = this.rowFromServer.readFieldLength();
int offset = this.rowFromServer.getPosition();
return getNativeTime(columnIndex, this.rowFromServer.getByteBuffer(), offset, (int)length, targetCalendar, tz, rollForward, conn, rs);
}
public int getBytesSize() {
return this.rowFromServer.getBufLength();
}
}

View file

@ -0,0 +1,181 @@
package com.mysql.jdbc;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.TimeZone;
public class ByteArrayRow extends ResultSetRow {
byte[][] internalRowData;
public ByteArrayRow(byte[][] internalRowData, ExceptionInterceptor exceptionInterceptor) {
super(exceptionInterceptor);
this.internalRowData = internalRowData;
}
public byte[] getColumnValue(int index) throws SQLException {
return this.internalRowData[index];
}
public void setColumnValue(int index, byte[] value) throws SQLException {
this.internalRowData[index] = value;
}
public String getString(int index, String encoding, MySQLConnection conn) throws SQLException {
byte[] columnData = this.internalRowData[index];
if (columnData == null)
return null;
return getString(encoding, conn, columnData, 0, columnData.length);
}
public boolean isNull(int index) throws SQLException {
return (this.internalRowData[index] == null);
}
public boolean isFloatingPointNumber(int index) throws SQLException {
byte[] numAsBytes = this.internalRowData[index];
if (this.internalRowData[index] == null || (this.internalRowData[index]).length == 0)
return false;
for (int i = 0; i < numAsBytes.length; i++) {
if ((char)numAsBytes[i] == 'e' || (char)numAsBytes[i] == 'E')
return true;
}
return false;
}
public long length(int index) throws SQLException {
if (this.internalRowData[index] == null)
return 0L;
return (long)(this.internalRowData[index]).length;
}
public int getInt(int columnIndex) {
if (this.internalRowData[columnIndex] == null)
return 0;
return StringUtils.getInt(this.internalRowData[columnIndex]);
}
public long getLong(int columnIndex) {
if (this.internalRowData[columnIndex] == null)
return 0L;
return StringUtils.getLong(this.internalRowData[columnIndex]);
}
public Timestamp getTimestampFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
byte[] columnValue = this.internalRowData[columnIndex];
if (columnValue == null)
return null;
return getTimestampFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs);
}
public double getNativeDouble(int columnIndex) throws SQLException {
if (this.internalRowData[columnIndex] == null)
return 0.0D;
return getNativeDouble(this.internalRowData[columnIndex], 0);
}
public float getNativeFloat(int columnIndex) throws SQLException {
if (this.internalRowData[columnIndex] == null)
return 0.0F;
return getNativeFloat(this.internalRowData[columnIndex], 0);
}
public int getNativeInt(int columnIndex) throws SQLException {
if (this.internalRowData[columnIndex] == null)
return 0;
return getNativeInt(this.internalRowData[columnIndex], 0);
}
public long getNativeLong(int columnIndex) throws SQLException {
if (this.internalRowData[columnIndex] == null)
return 0L;
return getNativeLong(this.internalRowData[columnIndex], 0);
}
public short getNativeShort(int columnIndex) throws SQLException {
if (this.internalRowData[columnIndex] == null)
return 0;
return getNativeShort(this.internalRowData[columnIndex], 0);
}
public Timestamp getNativeTimestamp(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
byte[] bits = this.internalRowData[columnIndex];
if (bits == null)
return null;
return getNativeTimestamp(bits, 0, bits.length, targetCalendar, tz, rollForward, conn, rs);
}
public void closeOpenStreams() {}
public InputStream getBinaryInputStream(int columnIndex) throws SQLException {
if (this.internalRowData[columnIndex] == null)
return null;
return new ByteArrayInputStream(this.internalRowData[columnIndex]);
}
public Reader getReader(int columnIndex) throws SQLException {
InputStream stream = getBinaryInputStream(columnIndex);
if (stream == null)
return null;
try {
return new InputStreamReader(stream, this.metadata[columnIndex].getEncoding());
} catch (UnsupportedEncodingException e) {
SQLException sqlEx = SQLError.createSQLException("", this.exceptionInterceptor);
sqlEx.initCause(e);
throw sqlEx;
}
}
public Time getTimeFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
byte[] columnValue = this.internalRowData[columnIndex];
if (columnValue == null)
return null;
return getTimeFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs);
}
public Date getDateFast(int columnIndex, MySQLConnection conn, ResultSetImpl rs, Calendar targetCalendar) throws SQLException {
byte[] columnValue = this.internalRowData[columnIndex];
if (columnValue == null)
return null;
return getDateFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, conn, rs, targetCalendar);
}
public Object getNativeDateTimeValue(int columnIndex, Calendar targetCalendar, int jdbcType, int mysqlType, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
byte[] columnValue = this.internalRowData[columnIndex];
if (columnValue == null)
return null;
return getNativeDateTimeValue(columnIndex, columnValue, 0, columnValue.length, targetCalendar, jdbcType, mysqlType, tz, rollForward, conn, rs);
}
public Date getNativeDate(int columnIndex, MySQLConnection conn, ResultSetImpl rs, Calendar cal) throws SQLException {
byte[] columnValue = this.internalRowData[columnIndex];
if (columnValue == null)
return null;
return getNativeDate(columnIndex, columnValue, 0, columnValue.length, conn, rs, cal);
}
public Time getNativeTime(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException {
byte[] columnValue = this.internalRowData[columnIndex];
if (columnValue == null)
return null;
return getNativeTime(columnIndex, columnValue, 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs);
}
public int getBytesSize() {
if (this.internalRowData == null)
return 0;
int bytesSize = 0;
for (int i = 0; i < this.internalRowData.length; i++) {
if (this.internalRowData[i] != null)
bytesSize += (this.internalRowData[i]).length;
}
return bytesSize;
}
}

View file

@ -0,0 +1,15 @@
package com.mysql.jdbc;
import java.util.Set;
public interface CacheAdapter<K, V> {
V get(K paramK);
void put(K paramK, V paramV);
void invalidate(K paramK);
void invalidateAll(Set<K> paramSet);
void invalidateAll();
}

View file

@ -0,0 +1,8 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.Properties;
public interface CacheAdapterFactory<K, V> {
CacheAdapter<K, V> getInstance(Connection paramConnection, String paramString, int paramInt1, int paramInt2, Properties paramProperties) throws SQLException;
}

View file

@ -0,0 +1,29 @@
package com.mysql.jdbc;
import java.util.Map;
public class CachedResultSetMetaData {
Map<String, Integer> columnNameToIndex = null;
Field[] fields;
Map<String, Integer> fullColumnNameToIndex = null;
java.sql.ResultSetMetaData metadata;
public Map<String, Integer> getColumnNameToIndex() {
return this.columnNameToIndex;
}
public Field[] getFields() {
return this.fields;
}
public Map<String, Integer> getFullColumnNameToIndex() {
return this.fullColumnNameToIndex;
}
public java.sql.ResultSetMetaData getMetadata() {
return this.metadata;
}
}

View file

@ -0,0 +1,617 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class CharsetMapping {
private static int numberOfEncodingsConfigured = 0;
static {
MysqlCharset[] charset = {
new MysqlCharset("usa7", 1, 0, new String[] { "US-ASCII" }, 4, 0), new MysqlCharset("ascii", 1, 0, new String[] { "US-ASCII", "ASCII" }), new MysqlCharset("big5", 2, 0, new String[] { "Big5" }), new MysqlCharset("gbk", 2, 0, new String[] { "GBK" }), new MysqlCharset("sjis", 2, 0, new String[] { "SHIFT_JIS", "Cp943", "WINDOWS-31J" }), new MysqlCharset("cp932", 2, 1, new String[] { "WINDOWS-31J" }), new MysqlCharset("gb2312", 2, 0, new String[] { "GB2312" }), new MysqlCharset("ujis", 3, 0, new String[] { "EUC_JP" }), new MysqlCharset("eucjpms", 3, 0, new String[] { "EUC_JP_Solaris" }, 5, 0, 3), new MysqlCharset("euc_kr", 2, 0, new String[] { "EUC_KR" }, 4, 0),
new MysqlCharset("euckr", 2, 0, new String[] { "EUC-KR" }), new MysqlCharset("latin1", 1, 1, new String[] { "Cp1252", "ISO8859_1" }), new MysqlCharset("swe7", 1, 0, new String[] { "Cp1252" }), new MysqlCharset("hp8", 1, 0, new String[] { "Cp1252" }), new MysqlCharset("dec8", 1, 0, new String[] { "Cp1252" }), new MysqlCharset("armscii8", 1, 0, new String[] { "Cp1252" }), new MysqlCharset("geostd8", 1, 0, new String[] { "Cp1252" }), new MysqlCharset("latin2", 1, 0, new String[] { "ISO8859_2" }), new MysqlCharset("czech", 1, 0, new String[] { "ISO8859_2" }, 4, 0), new MysqlCharset("hungarian", 1, 0, new String[] { "ISO8859_2" }, 4, 0),
new MysqlCharset("croat", 1, 0, new String[] { "ISO8859_2" }, 4, 0), new MysqlCharset("greek", 1, 0, new String[] { "ISO8859_7", "greek" }), new MysqlCharset("latin7", 1, 0, new String[] { "ISO-8859-13" }), new MysqlCharset("hebrew", 1, 0, new String[] { "ISO8859_8" }), new MysqlCharset("latin5", 1, 0, new String[] { "ISO8859_9" }), new MysqlCharset("latvian", 1, 0, new String[] { "ISO8859_13" }, 4, 0), new MysqlCharset("latvian1", 1, 0, new String[] { "ISO8859_13" }, 4, 0), new MysqlCharset("estonia", 1, 1, new String[] { "ISO8859_13" }, 4, 0), new MysqlCharset("cp850", 1, 0, new String[] { "Cp850", "Cp437" }), new MysqlCharset("dos", 1, 0, new String[] { "Cp850", "Cp437" }, 4, 0),
new MysqlCharset("cp852", 1, 0, new String[] { "Cp852" }), new MysqlCharset("keybcs2", 1, 0, new String[] { "Cp852" }), new MysqlCharset("cp866", 1, 0, new String[] { "Cp866" }), new MysqlCharset("koi8_ru", 1, 0, new String[] { "KOI8_R" }, 4, 0), new MysqlCharset("koi8r", 1, 1, new String[] { "KOI8_R" }), new MysqlCharset("koi8u", 1, 0, new String[] { "KOI8_R" }), new MysqlCharset("koi8_ukr", 1, 0, new String[] { "KOI8_R" }, 4, 0), new MysqlCharset("tis620", 1, 0, new String[] { "TIS620" }), new MysqlCharset("cp1250", 1, 0, new String[] { "Cp1250" }), new MysqlCharset("win1250", 1, 0, new String[] { "Cp1250" }, 4, 0),
new MysqlCharset("cp1251", 1, 1, new String[] { "Cp1251" }), new MysqlCharset("win1251", 1, 0, new String[] { "Cp1251" }, 4, 0), new MysqlCharset("cp1251cias", 1, 0, new String[] { "Cp1251" }, 4, 0), new MysqlCharset("cp1251csas", 1, 0, new String[] { "Cp1251" }, 4, 0), new MysqlCharset("win1251ukr", 1, 0, new String[] { "Cp1251" }, 4, 0), new MysqlCharset("cp1256", 1, 0, new String[] { "Cp1256" }), new MysqlCharset("cp1257", 1, 0, new String[] { "Cp1257" }), new MysqlCharset("macroman", 1, 0, new String[] { "MacRoman" }), new MysqlCharset("macce", 1, 0, new String[] { "MacCentralEurope" }), new MysqlCharset("utf8", 3, 1, new String[] { "UTF-8" }),
new MysqlCharset("utf8mb4", 4, 0, new String[] { "UTF-8" }), new MysqlCharset("ucs2", 2, 0, new String[] { "UnicodeBig" }), new MysqlCharset("binary", 1, 1, new String[] { "ISO8859_1" }), new MysqlCharset("latin1_de", 1, 0, new String[] { "ISO8859_1" }, 4, 0), new MysqlCharset("german1", 1, 0, new String[] { "ISO8859_1" }, 4, 0), new MysqlCharset("danish", 1, 0, new String[] { "ISO8859_1" }, 4, 0), new MysqlCharset("utf16", 4, 0, new String[] { "UTF-16" }), new MysqlCharset("utf16le", 4, 0, new String[] { "UTF-16LE" }), new MysqlCharset("utf32", 4, 0, new String[] { "UTF-32" }) };
HashMap<String, MysqlCharset> charsetNameToMysqlCharsetMap = new HashMap<String, MysqlCharset>();
HashMap<String, List<MysqlCharset>> javaUcToMysqlCharsetMap = new HashMap<String, List<MysqlCharset>>();
Set<String> tempMultibyteEncodings = new HashSet<String>();
Set<String> tempEscapeEncodings = new HashSet<String>();
for (int i = 0; i < charset.length; i++) {
String charsetName = (charset[i]).charsetName;
charsetNameToMysqlCharsetMap.put(charsetName, charset[i]);
numberOfEncodingsConfigured += (charset[i]).javaEncodingsUc.size();
for (String encUC : (charset[i]).javaEncodingsUc) {
List<MysqlCharset> charsets = javaUcToMysqlCharsetMap.get(encUC);
if (charsets == null) {
charsets = new ArrayList<MysqlCharset>();
javaUcToMysqlCharsetMap.put(encUC, charsets);
}
charsets.add(charset[i]);
if ((charset[i]).mblen > 1)
tempMultibyteEncodings.add(encUC);
}
if (charsetName.equals("big5") || charsetName.equals("gbk") || charsetName.equals("sjis"))
tempEscapeEncodings.addAll((charset[i]).javaEncodingsUc);
}
CHARSET_NAME_TO_CHARSET = Collections.<String, MysqlCharset>unmodifiableMap(charsetNameToMysqlCharsetMap);
JAVA_ENCODING_UC_TO_MYSQL_CHARSET = Collections.<String, List<MysqlCharset>>unmodifiableMap(javaUcToMysqlCharsetMap);
MULTIBYTE_ENCODINGS = Collections.<String>unmodifiableSet(tempMultibyteEncodings);
ESCAPE_ENCODINGS = Collections.<String>unmodifiableSet(tempEscapeEncodings);
Collation[] collation = new Collation[255];
collation[1] = new Collation(1, "big5_chinese_ci", 1, "big5");
collation[84] = new Collation(84, "big5_bin", 0, "big5");
collation[2] = new Collation(2, "latin2_czech_cs", 0, "latin2");
collation[9] = new Collation(9, "latin2_general_ci", 1, "latin2");
collation[21] = new Collation(21, "latin2_hungarian_ci", 0, "latin2");
collation[27] = new Collation(27, "latin2_croatian_ci", 0, "latin2");
collation[77] = new Collation(77, "latin2_bin", 0, "latin2");
collation[4] = new Collation(4, "cp850_general_ci", 1, "cp850");
collation[80] = new Collation(80, "cp850_bin", 0, "cp850");
collation[5] = new Collation(5, "latin1_german1_ci", 1, "latin1");
collation[8] = new Collation(8, "latin1_swedish_ci", 0, "latin1");
collation[15] = new Collation(15, "latin1_danish_ci", 0, "latin1");
collation[31] = new Collation(31, "latin1_german2_ci", 0, "latin1");
collation[47] = new Collation(47, "latin1_bin", 0, "latin1");
collation[48] = new Collation(48, "latin1_general_ci", 0, "latin1");
collation[49] = new Collation(49, "latin1_general_cs", 0, "latin1");
collation[76] = new Collation(76, "not_implemented", 0, "latin1");
collation[94] = new Collation(94, "latin1_spanish_ci", 0, "latin1");
collation[100] = new Collation(100, "not_implemented", 0, "latin1");
collation[125] = new Collation(125, "not_implemented", 0, "latin1");
collation[126] = new Collation(126, "not_implemented", 0, "latin1");
collation[127] = new Collation(127, "not_implemented", 0, "latin1");
collation[152] = new Collation(152, "not_implemented", 0, "latin1");
collation[153] = new Collation(153, "not_implemented", 0, "latin1");
collation[154] = new Collation(154, "not_implemented", 0, "latin1");
collation[155] = new Collation(155, "not_implemented", 0, "latin1");
collation[156] = new Collation(156, "not_implemented", 0, "latin1");
collation[157] = new Collation(157, "not_implemented", 0, "latin1");
collation[158] = new Collation(158, "not_implemented", 0, "latin1");
collation[184] = new Collation(184, "not_implemented", 0, "latin1");
collation[185] = new Collation(185, "not_implemented", 0, "latin1");
collation[186] = new Collation(186, "not_implemented", 0, "latin1");
collation[187] = new Collation(187, "not_implemented", 0, "latin1");
collation[188] = new Collation(188, "not_implemented", 0, "latin1");
collation[189] = new Collation(189, "not_implemented", 0, "latin1");
collation[190] = new Collation(190, "not_implemented", 0, "latin1");
collation[191] = new Collation(191, "not_implemented", 0, "latin1");
collation[216] = new Collation(216, "not_implemented", 0, "latin1");
collation[217] = new Collation(217, "not_implemented", 0, "latin1");
collation[218] = new Collation(218, "not_implemented", 0, "latin1");
collation[219] = new Collation(219, "not_implemented", 0, "latin1");
collation[220] = new Collation(220, "not_implemented", 0, "latin1");
collation[221] = new Collation(221, "not_implemented", 0, "latin1");
collation[222] = new Collation(222, "not_implemented", 0, "latin1");
collation[248] = new Collation(248, "not_implemented", 0, "latin1");
collation[249] = new Collation(249, "not_implemented", 0, "latin1");
collation[250] = new Collation(250, "not_implemented", 0, "latin1");
collation[251] = new Collation(251, "not_implemented", 0, "latin1");
collation[252] = new Collation(252, "not_implemented", 0, "latin1");
collation[253] = new Collation(253, "not_implemented", 0, "latin1");
collation[254] = new Collation(254, "not_implemented", 0, "latin1");
collation[10] = new Collation(10, "swe7_swedish_ci", 0, "swe7");
collation[82] = new Collation(82, "swe7_bin", 0, "swe7");
collation[6] = new Collation(6, "hp8_english_ci", 0, "hp8");
collation[72] = new Collation(72, "hp8_bin", 0, "hp8");
collation[3] = new Collation(3, "dec8_swedish_ci", 0, "dec8");
collation[69] = new Collation(69, "dec8_bin", 0, "dec8");
collation[32] = new Collation(32, "armscii8_general_ci", 0, "armscii8");
collation[64] = new Collation(64, "armscii8_bin", 0, "armscii8");
collation[92] = new Collation(92, "geostd8_general_ci", 0, "geostd8");
collation[93] = new Collation(93, "geostd8_bin", 0, "geostd8");
collation[7] = new Collation(7, "koi8r_general_ci", 0, "koi8r");
collation[74] = new Collation(74, "koi8r_bin", 0, "koi8r");
collation[11] = new Collation(11, "ascii_general_ci", 0, "ascii");
collation[65] = new Collation(65, "ascii_bin", 0, "ascii");
collation[12] = new Collation(12, "ujis_japanese_ci", 0, "ujis");
collation[91] = new Collation(91, "ujis_bin", 0, "ujis");
collation[13] = new Collation(13, "sjis_japanese_ci", 0, "sjis");
collation[14] = new Collation(14, "cp1251_bulgarian_ci", 0, "cp1251");
collation[16] = new Collation(16, "hebrew_general_ci", 0, "hebrew");
collation[17] = new Collation(17, "latin1_german1_ci", 0, "win1251");
collation[18] = new Collation(18, "tis620_thai_ci", 0, "tis620");
collation[19] = new Collation(19, "euckr_korean_ci", 0, "euckr");
collation[20] = new Collation(20, "latin7_estonian_cs", 0, "latin7");
collation[22] = new Collation(22, "koi8u_general_ci", 0, "koi8u");
collation[23] = new Collation(23, "cp1251_ukrainian_ci", 0, "cp1251");
collation[24] = new Collation(24, "gb2312_chinese_ci", 0, "gb2312");
collation[25] = new Collation(25, "greek_general_ci", 0, "greek");
collation[26] = new Collation(26, "cp1250_general_ci", 1, "cp1250");
collation[28] = new Collation(28, "gbk_chinese_ci", 1, "gbk");
collation[29] = new Collation(29, "cp1257_lithuanian_ci", 0, "cp1257");
collation[30] = new Collation(30, "latin5_turkish_ci", 1, "latin5");
collation[33] = new Collation(33, "utf8_general_ci", 1, "utf8");
collation[34] = new Collation(34, "cp1250_czech_cs", 0, "cp1250");
collation[35] = new Collation(35, "ucs2_general_ci", 1, "ucs2");
collation[36] = new Collation(36, "cp866_general_ci", 1, "cp866");
collation[37] = new Collation(37, "keybcs2_general_ci", 1, "keybcs2");
collation[38] = new Collation(38, "macce_general_ci", 1, "macce");
collation[39] = new Collation(39, "macroman_general_ci", 1, "macroman");
collation[40] = new Collation(40, "cp852_general_ci", 1, "cp852");
collation[41] = new Collation(41, "latin7_general_ci", 1, "latin7");
collation[42] = new Collation(42, "latin7_general_cs", 0, "latin7");
collation[43] = new Collation(43, "macce_bin", 0, "macce");
collation[44] = new Collation(44, "cp1250_croatian_ci", 0, "cp1250");
collation[45] = new Collation(45, "utf8mb4_general_ci", 1, "utf8mb4");
collation[46] = new Collation(46, "utf8mb4_bin", 0, "utf8mb4");
collation[50] = new Collation(50, "cp1251_bin", 0, "cp1251");
collation[51] = new Collation(51, "cp1251_general_ci", 1, "cp1251");
collation[52] = new Collation(52, "cp1251_general_cs", 0, "cp1251");
collation[53] = new Collation(53, "macroman_bin", 0, "macroman");
collation[54] = new Collation(54, "utf16_general_ci", 1, "utf16");
collation[55] = new Collation(55, "utf16_bin", 0, "utf16");
collation[56] = new Collation(56, "utf16le_general_ci", 1, "utf16le");
collation[57] = new Collation(57, "cp1256_general_ci", 1, "cp1256");
collation[58] = new Collation(58, "cp1257_bin", 0, "cp1257");
collation[59] = new Collation(59, "cp1257_general_ci", 1, "cp1257");
collation[60] = new Collation(60, "utf32_general_ci", 1, "utf32");
collation[61] = new Collation(61, "utf32_bin", 0, "utf32");
collation[62] = new Collation(62, "utf16le_bin", 0, "utf16le");
collation[63] = new Collation(63, "binary", 1, "binary");
collation[66] = new Collation(66, "cp1250_bin", 0, "cp1250");
collation[67] = new Collation(67, "cp1256_bin", 0, "cp1256");
collation[68] = new Collation(68, "cp866_bin", 0, "cp866");
collation[70] = new Collation(70, "greek_bin", 0, "greek");
collation[71] = new Collation(71, "hebrew_bin", 0, "hebrew");
collation[73] = new Collation(73, "keybcs2_bin", 0, "keybcs2");
collation[75] = new Collation(75, "koi8u_bin", 0, "koi8u");
collation[78] = new Collation(78, "latin5_bin", 0, "latin5");
collation[79] = new Collation(79, "latin7_bin", 0, "latin7");
collation[81] = new Collation(81, "cp852_bin", 0, "cp852");
collation[83] = new Collation(83, "utf8_bin", 0, "utf8");
collation[85] = new Collation(85, "euckr_bin", 0, "euckr");
collation[86] = new Collation(86, "gb2312_bin", 0, "gb2312");
collation[87] = new Collation(87, "gbk_bin", 0, "gbk");
collation[88] = new Collation(88, "sjis_bin", 0, "sjis");
collation[89] = new Collation(89, "tis620_bin", 0, "tis620");
collation[90] = new Collation(90, "ucs2_bin", 0, "ucs2");
collation[95] = new Collation(95, "cp932_japanese_ci", 1, "cp932");
collation[96] = new Collation(96, "cp932_bin", 0, "cp932");
collation[97] = new Collation(97, "eucjpms_japanese_ci", 1, "eucjpms");
collation[98] = new Collation(98, "eucjpms_bin", 0, "eucjpms");
collation[99] = new Collation(99, "cp1250_polish_ci", 0, "cp1250");
collation[101] = new Collation(101, "utf16_unicode_ci", 0, "utf16");
collation[102] = new Collation(102, "utf16_icelandic_ci", 0, "utf16");
collation[103] = new Collation(103, "utf16_latvian_ci", 0, "utf16");
collation[104] = new Collation(104, "utf16_romanian_ci", 0, "utf16");
collation[105] = new Collation(105, "utf16_slovenian_ci", 0, "utf16");
collation[106] = new Collation(106, "utf16_polish_ci", 0, "utf16");
collation[107] = new Collation(107, "utf16_estonian_ci", 0, "utf16");
collation[108] = new Collation(108, "utf16_spanish_ci", 0, "utf16");
collation[109] = new Collation(109, "utf16_swedish_ci", 0, "utf16");
collation[110] = new Collation(110, "utf16_turkish_ci", 0, "utf16");
collation[111] = new Collation(111, "utf16_czech_ci", 0, "utf16");
collation[112] = new Collation(112, "utf16_danish_ci", 0, "utf16");
collation[113] = new Collation(113, "utf16_lithuanian_ci", 0, "utf16");
collation[114] = new Collation(114, "utf16_slovak_ci", 0, "utf16");
collation[115] = new Collation(115, "utf16_spanish2_ci", 0, "utf16");
collation[116] = new Collation(116, "utf16_roman_ci", 0, "utf16");
collation[117] = new Collation(117, "utf16_persian_ci", 0, "utf16");
collation[118] = new Collation(118, "utf16_esperanto_ci", 0, "utf16");
collation[119] = new Collation(119, "utf16_hungarian_ci", 0, "utf16");
collation[120] = new Collation(120, "utf16_sinhala_ci", 0, "utf16");
collation[121] = new Collation(121, "utf16_german2_ci", 0, "utf16");
collation[122] = new Collation(122, "utf16_croatian_ci", 0, "utf16");
collation[123] = new Collation(123, "utf16_unicode_520_ci", 0, "utf16");
collation[124] = new Collation(124, "utf16_vietnamese_ci", 0, "utf16");
collation[128] = new Collation(128, "ucs2_unicode_ci", 0, "ucs2");
collation[129] = new Collation(129, "ucs2_icelandic_ci", 0, "ucs2");
collation[130] = new Collation(130, "ucs2_latvian_ci", 0, "ucs2");
collation[131] = new Collation(131, "ucs2_romanian_ci", 0, "ucs2");
collation[132] = new Collation(132, "ucs2_slovenian_ci", 0, "ucs2");
collation[133] = new Collation(133, "ucs2_polish_ci", 0, "ucs2");
collation[134] = new Collation(134, "ucs2_estonian_ci", 0, "ucs2");
collation[135] = new Collation(135, "ucs2_spanish_ci", 0, "ucs2");
collation[136] = new Collation(136, "ucs2_swedish_ci", 0, "ucs2");
collation[137] = new Collation(137, "ucs2_turkish_ci", 0, "ucs2");
collation[138] = new Collation(138, "ucs2_czech_ci", 0, "ucs2");
collation[139] = new Collation(139, "ucs2_danish_ci", 0, "ucs2");
collation[140] = new Collation(140, "ucs2_lithuanian_ci", 0, "ucs2");
collation[141] = new Collation(141, "ucs2_slovak_ci", 0, "ucs2");
collation[142] = new Collation(142, "ucs2_spanish2_ci", 0, "ucs2");
collation[143] = new Collation(143, "ucs2_roman_ci", 0, "ucs2");
collation[144] = new Collation(144, "ucs2_persian_ci", 0, "ucs2");
collation[145] = new Collation(145, "ucs2_esperanto_ci", 0, "ucs2");
collation[146] = new Collation(146, "ucs2_hungarian_ci", 0, "ucs2");
collation[147] = new Collation(147, "ucs2_sinhala_ci", 0, "ucs2");
collation[148] = new Collation(148, "ucs2_german2_ci", 0, "ucs2");
collation[149] = new Collation(149, "ucs2_croatian_ci", 0, "ucs2");
collation[150] = new Collation(150, "ucs2_unicode_520_ci", 0, "ucs2");
collation[151] = new Collation(151, "ucs2_vietnamese_ci", 0, "ucs2");
collation[159] = new Collation(159, "ucs2_general_mysql500_ci", 0, "ucs2");
collation[160] = new Collation(160, "utf32_unicode_ci", 0, "utf32");
collation[161] = new Collation(161, "utf32_icelandic_ci", 0, "utf32");
collation[162] = new Collation(162, "utf32_latvian_ci", 0, "utf32");
collation[163] = new Collation(163, "utf32_romanian_ci", 0, "utf32");
collation[164] = new Collation(164, "utf32_slovenian_ci", 0, "utf32");
collation[165] = new Collation(165, "utf32_polish_ci", 0, "utf32");
collation[166] = new Collation(166, "utf32_estonian_ci", 0, "utf32");
collation[167] = new Collation(167, "utf32_spanish_ci", 0, "utf32");
collation[168] = new Collation(168, "utf32_swedish_ci", 0, "utf32");
collation[169] = new Collation(169, "utf32_turkish_ci", 0, "utf32");
collation[170] = new Collation(170, "utf32_czech_ci", 0, "utf32");
collation[171] = new Collation(171, "utf32_danish_ci", 0, "utf32");
collation[172] = new Collation(172, "utf32_lithuanian_ci", 0, "utf32");
collation[173] = new Collation(173, "utf32_slovak_ci", 0, "utf32");
collation[174] = new Collation(174, "utf32_spanish2_ci", 0, "utf32");
collation[175] = new Collation(175, "utf32_roman_ci", 0, "utf32");
collation[176] = new Collation(176, "utf32_persian_ci", 0, "utf32");
collation[177] = new Collation(177, "utf32_esperanto_ci", 0, "utf32");
collation[178] = new Collation(178, "utf32_hungarian_ci", 0, "utf32");
collation[179] = new Collation(179, "utf32_sinhala_ci", 0, "utf32");
collation[180] = new Collation(180, "utf32_german2_ci", 0, "utf32");
collation[181] = new Collation(181, "utf32_croatian_ci", 0, "utf32");
collation[182] = new Collation(182, "utf32_unicode_520_ci", 0, "utf32");
collation[183] = new Collation(183, "utf32_vietnamese_ci", 0, "utf32");
collation[192] = new Collation(192, "utf8_unicode_ci", 0, "utf8");
collation[193] = new Collation(193, "utf8_icelandic_ci", 0, "utf8");
collation[194] = new Collation(194, "utf8_latvian_ci", 0, "utf8");
collation[195] = new Collation(195, "utf8_romanian_ci", 0, "utf8");
collation[196] = new Collation(196, "utf8_slovenian_ci", 0, "utf8");
collation[197] = new Collation(197, "utf8_polish_ci", 0, "utf8");
collation[198] = new Collation(198, "utf8_estonian_ci", 0, "utf8");
collation[199] = new Collation(199, "utf8_spanish_ci", 0, "utf8");
collation[200] = new Collation(200, "utf8_swedish_ci", 0, "utf8");
collation[201] = new Collation(201, "utf8_turkish_ci", 0, "utf8");
collation[202] = new Collation(202, "utf8_czech_ci", 0, "utf8");
collation[203] = new Collation(203, "utf8_danish_ci", 0, "utf8");
collation[204] = new Collation(204, "utf8_lithuanian_ci", 0, "utf8");
collation[205] = new Collation(205, "utf8_slovak_ci", 0, "utf8");
collation[206] = new Collation(206, "utf8_spanish2_ci", 0, "utf8");
collation[207] = new Collation(207, "utf8_roman_ci", 0, "utf8");
collation[208] = new Collation(208, "utf8_persian_ci", 0, "utf8");
collation[209] = new Collation(209, "utf8_esperanto_ci", 0, "utf8");
collation[210] = new Collation(210, "utf8_hungarian_ci", 0, "utf8");
collation[211] = new Collation(211, "utf8_sinhala_ci", 0, "utf8");
collation[212] = new Collation(212, "utf8_german2_ci", 0, "utf8");
collation[213] = new Collation(213, "utf8_croatian_ci", 0, "utf8");
collation[214] = new Collation(214, "utf8_unicode_520_ci", 0, "utf8");
collation[215] = new Collation(215, "utf8_vietnamese_ci", 0, "utf8");
collation[223] = new Collation(223, "utf8_general_mysql500_ci", 0, "utf8");
collation[224] = new Collation(224, "utf8mb4_unicode_ci", 0, "utf8mb4");
collation[225] = new Collation(225, "utf8mb4_icelandic_ci", 0, "utf8mb4");
collation[226] = new Collation(226, "utf8mb4_latvian_ci", 0, "utf8mb4");
collation[227] = new Collation(227, "utf8mb4_romanian_ci", 0, "utf8mb4");
collation[228] = new Collation(228, "utf8mb4_slovenian_ci", 0, "utf8mb4");
collation[229] = new Collation(229, "utf8mb4_polish_ci", 0, "utf8mb4");
collation[230] = new Collation(230, "utf8mb4_estonian_ci", 0, "utf8mb4");
collation[231] = new Collation(231, "utf8mb4_spanish_ci", 0, "utf8mb4");
collation[232] = new Collation(232, "utf8mb4_swedish_ci", 0, "utf8mb4");
collation[233] = new Collation(233, "utf8mb4_turkish_ci", 0, "utf8mb4");
collation[234] = new Collation(234, "utf8mb4_czech_ci", 0, "utf8mb4");
collation[235] = new Collation(235, "utf8mb4_danish_ci", 0, "utf8mb4");
collation[236] = new Collation(236, "utf8mb4_lithuanian_ci", 0, "utf8mb4");
collation[237] = new Collation(237, "utf8mb4_slovak_ci", 0, "utf8mb4");
collation[238] = new Collation(238, "utf8mb4_spanish2_ci", 0, "utf8mb4");
collation[239] = new Collation(239, "utf8mb4_roman_ci", 0, "utf8mb4");
collation[240] = new Collation(240, "utf8mb4_persian_ci", 0, "utf8mb4");
collation[241] = new Collation(241, "utf8mb4_esperanto_ci", 0, "utf8mb4");
collation[242] = new Collation(242, "utf8mb4_hungarian_ci", 0, "utf8mb4");
collation[243] = new Collation(243, "utf8mb4_sinhala_ci", 0, "utf8mb4");
collation[244] = new Collation(244, "utf8mb4_german2_ci", 0, "utf8mb4");
collation[245] = new Collation(245, "utf8mb4_croatian_ci", 0, "utf8mb4");
collation[246] = new Collation(246, "utf8mb4_unicode_520_ci", 0, "utf8mb4");
collation[247] = new Collation(247, "utf8mb4_vietnamese_ci", 0, "utf8mb4");
}
public static final String[] COLLATION_INDEX_TO_COLLATION_NAME = new String[255];
public static final MysqlCharset[] COLLATION_INDEX_TO_CHARSET = new MysqlCharset[255];
public static final int MAP_SIZE = 255;
public static final Map<String, MysqlCharset> CHARSET_NAME_TO_CHARSET;
public static final Map<String, Integer> CHARSET_NAME_TO_COLLATION_INDEX;
private static final Map<String, List<MysqlCharset>> JAVA_ENCODING_UC_TO_MYSQL_CHARSET;
private static final Set<String> MULTIBYTE_ENCODINGS;
private static final Map<String, String> ERROR_MESSAGE_FILE_TO_MYSQL_CHARSET;
private static final Set<String> ESCAPE_ENCODINGS;
private static final String MYSQL_CHARSET_NAME_armscii8 = "armscii8";
private static final String MYSQL_CHARSET_NAME_ascii = "ascii";
private static final String MYSQL_CHARSET_NAME_big5 = "big5";
private static final String MYSQL_CHARSET_NAME_binary = "binary";
private static final String MYSQL_CHARSET_NAME_cp1250 = "cp1250";
private static final String MYSQL_CHARSET_NAME_cp1251 = "cp1251";
private static final String MYSQL_CHARSET_NAME_cp1256 = "cp1256";
private static final String MYSQL_CHARSET_NAME_cp1257 = "cp1257";
private static final String MYSQL_CHARSET_NAME_cp850 = "cp850";
private static final String MYSQL_CHARSET_NAME_cp852 = "cp852";
private static final String MYSQL_CHARSET_NAME_cp866 = "cp866";
private static final String MYSQL_CHARSET_NAME_cp932 = "cp932";
private static final String MYSQL_CHARSET_NAME_dec8 = "dec8";
private static final String MYSQL_CHARSET_NAME_eucjpms = "eucjpms";
private static final String MYSQL_CHARSET_NAME_euckr = "euckr";
private static final String MYSQL_CHARSET_NAME_gb2312 = "gb2312";
private static final String MYSQL_CHARSET_NAME_gbk = "gbk";
private static final String MYSQL_CHARSET_NAME_geostd8 = "geostd8";
private static final String MYSQL_CHARSET_NAME_greek = "greek";
private static final String MYSQL_CHARSET_NAME_hebrew = "hebrew";
private static final String MYSQL_CHARSET_NAME_hp8 = "hp8";
private static final String MYSQL_CHARSET_NAME_keybcs2 = "keybcs2";
private static final String MYSQL_CHARSET_NAME_koi8r = "koi8r";
private static final String MYSQL_CHARSET_NAME_koi8u = "koi8u";
private static final String MYSQL_CHARSET_NAME_latin1 = "latin1";
private static final String MYSQL_CHARSET_NAME_latin2 = "latin2";
private static final String MYSQL_CHARSET_NAME_latin5 = "latin5";
private static final String MYSQL_CHARSET_NAME_latin7 = "latin7";
private static final String MYSQL_CHARSET_NAME_macce = "macce";
private static final String MYSQL_CHARSET_NAME_macroman = "macroman";
private static final String MYSQL_CHARSET_NAME_sjis = "sjis";
private static final String MYSQL_CHARSET_NAME_swe7 = "swe7";
private static final String MYSQL_CHARSET_NAME_tis620 = "tis620";
private static final String MYSQL_CHARSET_NAME_ucs2 = "ucs2";
private static final String MYSQL_CHARSET_NAME_ujis = "ujis";
private static final String MYSQL_CHARSET_NAME_utf16 = "utf16";
private static final String MYSQL_CHARSET_NAME_utf16le = "utf16le";
private static final String MYSQL_CHARSET_NAME_utf32 = "utf32";
private static final String MYSQL_CHARSET_NAME_utf8 = "utf8";
private static final String MYSQL_CHARSET_NAME_utf8mb4 = "utf8mb4";
private static final String MYSQL_4_0_CHARSET_NAME_cp1251cias = "cp1251cias";
private static final String MYSQL_4_0_CHARSET_NAME_cp1251csas = "cp1251csas";
private static final String MYSQL_4_0_CHARSET_NAME_croat = "croat";
private static final String MYSQL_4_0_CHARSET_NAME_czech = "czech";
private static final String MYSQL_4_0_CHARSET_NAME_danish = "danish";
private static final String MYSQL_4_0_CHARSET_NAME_dos = "dos";
private static final String MYSQL_4_0_CHARSET_NAME_estonia = "estonia";
private static final String MYSQL_4_0_CHARSET_NAME_euc_kr = "euc_kr";
private static final String MYSQL_4_0_CHARSET_NAME_german1 = "german1";
private static final String MYSQL_4_0_CHARSET_NAME_hungarian = "hungarian";
private static final String MYSQL_4_0_CHARSET_NAME_koi8_ru = "koi8_ru";
private static final String MYSQL_4_0_CHARSET_NAME_koi8_ukr = "koi8_ukr";
private static final String MYSQL_4_0_CHARSET_NAME_latin1_de = "latin1_de";
private static final String MYSQL_4_0_CHARSET_NAME_latvian = "latvian";
private static final String MYSQL_4_0_CHARSET_NAME_latvian1 = "latvian1";
private static final String MYSQL_4_0_CHARSET_NAME_usa7 = "usa7";
private static final String MYSQL_4_0_CHARSET_NAME_win1250 = "win1250";
private static final String MYSQL_4_0_CHARSET_NAME_win1251 = "win1251";
private static final String MYSQL_4_0_CHARSET_NAME_win1251ukr = "win1251ukr";
private static final String NOT_USED = "latin1";
public static final int MYSQL_COLLATION_INDEX_utf8 = 33;
public static final int MYSQL_COLLATION_INDEX_binary = 63;
static {
Map<String, Integer> charsetNameToCollationIndexMap = new TreeMap<String, Integer>();
Map<String, Integer> charsetNameToCollationPriorityMap = new TreeMap<String, Integer>();
for (int k = 1; k < 255; k++) {
COLLATION_INDEX_TO_COLLATION_NAME[k] = (collation[k]).collationName;
COLLATION_INDEX_TO_CHARSET[k] = (collation[k]).mysqlCharset;
String charsetName = (collation[k]).mysqlCharset.charsetName;
if (!charsetNameToCollationIndexMap.containsKey(charsetName) || charsetNameToCollationPriorityMap.get(charsetName) < (collation[k]).priority) {
charsetNameToCollationIndexMap.put(charsetName, Integer.valueOf(k));
charsetNameToCollationPriorityMap.put(charsetName, Integer.valueOf((collation[k]).priority));
}
}
for (int j = 1; j < 255; j++) {
if (COLLATION_INDEX_TO_COLLATION_NAME[j] == null)
throw new RuntimeException("Assertion failure: No mapping from charset index " + j + " to a mysql collation");
if (COLLATION_INDEX_TO_COLLATION_NAME[j] == null)
throw new RuntimeException("Assertion failure: No mapping from charset index " + j + " to a Java character set");
}
CHARSET_NAME_TO_COLLATION_INDEX = Collections.<String, Integer>unmodifiableMap(charsetNameToCollationIndexMap);
Map<String, String> tempMap = new HashMap<String, String>();
tempMap.put("czech", "latin2");
tempMap.put("danish", "latin1");
tempMap.put("dutch", "latin1");
tempMap.put("english", "latin1");
tempMap.put("estonian", "latin7");
tempMap.put("french", "latin1");
tempMap.put("german", "latin1");
tempMap.put("greek", "greek");
tempMap.put("hungarian", "latin2");
tempMap.put("italian", "latin1");
tempMap.put("japanese", "ujis");
tempMap.put("japanese-sjis", "sjis");
tempMap.put("korean", "euckr");
tempMap.put("norwegian", "latin1");
tempMap.put("norwegian-ny", "latin1");
tempMap.put("polish", "latin2");
tempMap.put("portuguese", "latin1");
tempMap.put("romanian", "latin2");
tempMap.put("russian", "koi8r");
tempMap.put("serbian", "cp1250");
tempMap.put("slovak", "latin2");
tempMap.put("spanish", "latin1");
tempMap.put("swedish", "latin1");
tempMap.put("ukrainian", "koi8u");
ERROR_MESSAGE_FILE_TO_MYSQL_CHARSET = Collections.<String, String>unmodifiableMap(tempMap);
}
public static final String getMysqlCharsetForJavaEncoding(String javaEncoding, Connection conn) throws SQLException {
try {
List<MysqlCharset> mysqlCharsets = JAVA_ENCODING_UC_TO_MYSQL_CHARSET.get(javaEncoding.toUpperCase(Locale.ENGLISH));
if (mysqlCharsets != null) {
Iterator<MysqlCharset> iter = mysqlCharsets.iterator();
MysqlCharset versionedProp = null;
while (iter.hasNext()) {
MysqlCharset charset = iter.next();
if (conn == null)
return charset.charsetName;
if (versionedProp == null || versionedProp.major < charset.major || versionedProp.minor < charset.minor || versionedProp.subminor < charset.subminor || versionedProp.priority < charset.priority)
if (charset.isOkayForVersion(conn))
versionedProp = charset;
}
if (versionedProp != null)
return versionedProp.charsetName;
}
return null;
} catch (SQLException ex) {
throw ex;
} catch (RuntimeException ex) {
SQLException sqlEx = SQLError.createSQLException(ex.toString(), "S1009", null);
sqlEx.initCause(ex);
throw sqlEx;
}
}
public static int getCollationIndexForJavaEncoding(String javaEncoding, java.sql.Connection conn) throws SQLException {
String charsetName = getMysqlCharsetForJavaEncoding(javaEncoding, (Connection)conn);
if (charsetName != null) {
Integer ci = CHARSET_NAME_TO_COLLATION_INDEX.get(charsetName);
if (ci != null)
return ci;
}
return 0;
}
public static String getMysqlCharsetNameForCollationIndex(Integer collationIndex) {
if (collationIndex != null && collationIndex > 0 && collationIndex < 255)
return (COLLATION_INDEX_TO_CHARSET[collationIndex]).charsetName;
return null;
}
public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName, String javaEncoding) {
String res = javaEncoding;
MysqlCharset cs = CHARSET_NAME_TO_CHARSET.get(mysqlCharsetName);
if (cs != null)
res = cs.getMatchingJavaEncoding(javaEncoding);
return res;
}
public static String getJavaEncodingForMysqlCharset(String mysqlCharsetName) {
return getJavaEncodingForMysqlCharset(mysqlCharsetName, null);
}
public static String getJavaEncodingForCollationIndex(Integer collationIndex, String javaEncoding) {
if (collationIndex != null && collationIndex > 0 && collationIndex < 255) {
MysqlCharset cs = COLLATION_INDEX_TO_CHARSET[collationIndex];
return cs.getMatchingJavaEncoding(javaEncoding);
}
return null;
}
public static String getJavaEncodingForCollationIndex(Integer collationIndex) {
return getJavaEncodingForCollationIndex(collationIndex, null);
}
static final int getNumberOfCharsetsConfigured() {
return numberOfEncodingsConfigured;
}
static final String getCharacterEncodingForErrorMessages(ConnectionImpl conn) throws SQLException {
if (conn.versionMeetsMinimum(5, 5, 0)) {
String errorMessageCharsetName = conn.getServerVariable("character_set_results");
if (errorMessageCharsetName != null) {
String str = getJavaEncodingForMysqlCharset(errorMessageCharsetName);
if (str != null)
return str;
}
return "UTF-8";
}
String errorMessageFile = conn.getServerVariable("language");
if (errorMessageFile == null || errorMessageFile.length() == 0)
return "Cp1252";
int endWithoutSlash = errorMessageFile.length();
if (errorMessageFile.endsWith("/") || errorMessageFile.endsWith("\\"))
endWithoutSlash--;
int lastSlashIndex = errorMessageFile.lastIndexOf('/', endWithoutSlash - 1);
if (lastSlashIndex == -1)
lastSlashIndex = errorMessageFile.lastIndexOf('\\', endWithoutSlash - 1);
if (lastSlashIndex == -1)
lastSlashIndex = 0;
if (lastSlashIndex == endWithoutSlash || endWithoutSlash < lastSlashIndex)
return "Cp1252";
errorMessageFile = errorMessageFile.substring(lastSlashIndex + 1, endWithoutSlash);
String errorMessageEncodingMysql = ERROR_MESSAGE_FILE_TO_MYSQL_CHARSET.get(errorMessageFile);
if (errorMessageEncodingMysql == null)
return "Cp1252";
String javaEncoding = getJavaEncodingForMysqlCharset(errorMessageEncodingMysql);
if (javaEncoding == null)
return "Cp1252";
return javaEncoding;
}
static final boolean requiresEscapeEasternUnicode(String javaEncodingName) {
return ESCAPE_ENCODINGS.contains(javaEncodingName.toUpperCase(Locale.ENGLISH));
}
public static final boolean isMultibyteCharset(String javaEncodingName) {
return MULTIBYTE_ENCODINGS.contains(javaEncodingName.toUpperCase(Locale.ENGLISH));
}
public static int getMblen(String charsetName) {
if (charsetName != null) {
MysqlCharset cs = CHARSET_NAME_TO_CHARSET.get(charsetName);
if (cs != null)
return cs.mblen;
}
return 0;
}
}

View file

@ -0,0 +1,102 @@
#
# Charset Mappings
#
# Java Encoding MySQL Name (and version, '*'
# denotes preferred value)
#
javaToMysqlMappings=\
US-ASCII = usa7,\
US-ASCII = ascii,\
Big5 = big5,\
GBK = gbk,\
SJIS = sjis,\
EUC_CN = gb2312,\
EUC_JP = ujis,\
EUC_JP_Solaris = >5.0.3 eucjpms,\
EUC_KR = euc_kr,\
EUC_KR = >4.1.0 euckr,\
ISO8859_1 = *latin1,\
ISO8859_1 = latin1_de,\
ISO8859_1 = german1,\
ISO8859_1 = danish,\
ISO8859_2 = latin2,\
ISO8859_2 = czech,\
ISO8859_2 = hungarian,\
ISO8859_2 = croat,\
ISO8859_7 = greek,\
ISO8859_7 = latin7,\
ISO8859_8 = hebrew,\
ISO8859_9 = latin5,\
ISO8859_13 = latvian,\
ISO8859_13 = latvian1,\
ISO8859_13 = estonia,\
Cp437 = *>4.1.0 cp850,\
Cp437 = dos,\
Cp850 = Cp850,\
Cp852 = Cp852,\
Cp866 = cp866,\
KOI8_R = koi8_ru,\
KOI8_R = >4.1.0 koi8r,\
TIS620 = tis620,\
Cp1250 = cp1250,\
Cp1250 = win1250,\
Cp1251 = *>4.1.0 cp1251,\
Cp1251 = win1251,\
Cp1251 = cp1251cias,\
Cp1251 = cp1251csas,\
Cp1256 = cp1256,\
Cp1251 = win1251ukr,\
Cp1257 = cp1257,\
MacRoman = macroman,\
MacCentralEurope = macce,\
UTF-8 = utf8,\
UnicodeBig = ucs2,\
US-ASCII = binary,\
Cp943 = sjis,\
MS932 = sjis,\
MS932 = >4.1.11 cp932,\
WINDOWS-31J = sjis,\
WINDOWS-31J = >4.1.11 cp932,\
CP932 = sjis,\
CP932 = *>4.1.11 cp932,\
SHIFT_JIS = sjis,\
ASCII = ascii,\
LATIN5 = latin5,\
LATIN7 = latin7,\
HEBREW = hebrew,\
GREEK = greek,\
EUCKR = euckr,\
GB2312 = gb2312,\
LATIN2 = latin2
#
# List of multibyte character sets that can not
# use efficient charset conversion or escaping
#
# This map is made case-insensitive inside CharsetMapping
#
# Java Name MySQL Name (not currently used)
multibyteCharsets=\
Big5 = big5,\
GBK = gbk,\
SJIS = sjis,\
EUC_CN = gb2312,\
EUC_JP = ujis,\
EUC_JP_Solaris = eucjpms,\
EUC_KR = euc_kr,\
EUC_KR = >4.1.0 euckr,\
Cp943 = sjis,\
Cp943 = cp943,\
WINDOWS-31J = sjis,\
WINDOWS-31J = cp932,\
CP932 = cp932,\
MS932 = sjis,\
MS932 = cp932,\
SHIFT_JIS = sjis,\
EUCKR = euckr,\
GB2312 = gb2312,\
UTF-8 = utf8,\
utf8 = utf8,\
UnicodeBig = ucs2

View file

@ -0,0 +1,152 @@
package com.mysql.jdbc;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.sql.SQLException;
public class Clob implements java.sql.Clob, OutputStreamWatcher, WriterWatcher {
private String charData;
private ExceptionInterceptor exceptionInterceptor;
Clob(ExceptionInterceptor exceptionInterceptor) {
this.charData = "";
this.exceptionInterceptor = exceptionInterceptor;
}
Clob(String charDataInit, ExceptionInterceptor exceptionInterceptor) {
this.charData = charDataInit;
this.exceptionInterceptor = exceptionInterceptor;
}
public InputStream getAsciiStream() throws SQLException {
if (this.charData != null)
return new ByteArrayInputStream(StringUtils.getBytes(this.charData));
return null;
}
public Reader getCharacterStream() throws SQLException {
if (this.charData != null)
return new StringReader(this.charData);
return null;
}
public String getSubString(long startPos, int length) throws SQLException {
if (startPos < 1L)
throw SQLError.createSQLException(Messages.getString("Clob.6"), "S1009", this.exceptionInterceptor);
int adjustedStartPos = (int)startPos - 1;
int adjustedEndIndex = adjustedStartPos + length;
if (this.charData != null) {
if (adjustedEndIndex > this.charData.length())
throw SQLError.createSQLException(Messages.getString("Clob.7"), "S1009", this.exceptionInterceptor);
return this.charData.substring(adjustedStartPos, adjustedEndIndex);
}
return null;
}
public long length() throws SQLException {
if (this.charData != null)
return (long)this.charData.length();
return 0L;
}
public long position(java.sql.Clob arg0, long arg1) throws SQLException {
return position(arg0.getSubString(0L, (int)arg0.length()), arg1);
}
public long position(String stringToFind, long startPos) throws SQLException {
if (startPos < 1L)
throw SQLError.createSQLException(Messages.getString("Clob.8") + startPos + Messages.getString("Clob.9"), "S1009", this.exceptionInterceptor);
if (this.charData != null) {
if (startPos - 1L > (long)this.charData.length())
throw SQLError.createSQLException(Messages.getString("Clob.10"), "S1009", this.exceptionInterceptor);
int pos = this.charData.indexOf(stringToFind, (int)(startPos - 1L));
return (pos == -1) ? -1L : (long)(pos + 1);
}
return -1L;
}
public OutputStream setAsciiStream(long indexToWriteAt) throws SQLException {
if (indexToWriteAt < 1L)
throw SQLError.createSQLException(Messages.getString("Clob.0"), "S1009", this.exceptionInterceptor);
WatchableOutputStream bytesOut = new WatchableOutputStream();
bytesOut.setWatcher(this);
if (indexToWriteAt > 0L)
bytesOut.write(StringUtils.getBytes(this.charData), 0, (int)(indexToWriteAt - 1L));
return bytesOut;
}
public Writer setCharacterStream(long indexToWriteAt) throws SQLException {
if (indexToWriteAt < 1L)
throw SQLError.createSQLException(Messages.getString("Clob.1"), "S1009", this.exceptionInterceptor);
WatchableWriter writer = new WatchableWriter();
writer.setWatcher(this);
if (indexToWriteAt > 1L)
writer.write(this.charData, 0, (int)(indexToWriteAt - 1L));
return writer;
}
public int setString(long pos, String str) throws SQLException {
if (pos < 1L)
throw SQLError.createSQLException(Messages.getString("Clob.2"), "S1009", this.exceptionInterceptor);
if (str == null)
throw SQLError.createSQLException(Messages.getString("Clob.3"), "S1009", this.exceptionInterceptor);
StringBuffer charBuf = new StringBuffer(this.charData);
pos--;
int strLength = str.length();
charBuf.replace((int)pos, (int)(pos + (long)strLength), str);
this.charData = charBuf.toString();
return strLength;
}
public int setString(long pos, String str, int offset, int len) throws SQLException {
if (pos < 1L)
throw SQLError.createSQLException(Messages.getString("Clob.4"), "S1009", this.exceptionInterceptor);
if (str == null)
throw SQLError.createSQLException(Messages.getString("Clob.5"), "S1009", this.exceptionInterceptor);
StringBuffer charBuf = new StringBuffer(this.charData);
pos--;
String replaceString = str.substring(offset, len);
charBuf.replace((int)pos, (int)(pos + (long)replaceString.length()), replaceString);
this.charData = charBuf.toString();
return len;
}
public void streamClosed(WatchableOutputStream out) {
int streamSize = out.size();
if (streamSize < this.charData.length())
try {
out.write(StringUtils.getBytes(this.charData, null, null, false, null, this.exceptionInterceptor), streamSize, this.charData.length() - streamSize);
} catch (SQLException ex) {}
this.charData = StringUtils.toAsciiString(out.toByteArray());
}
public void truncate(long length) throws SQLException {
if (length > (long)this.charData.length())
throw SQLError.createSQLException(Messages.getString("Clob.11") + this.charData.length() + Messages.getString("Clob.12") + length + Messages.getString("Clob.13"), this.exceptionInterceptor);
this.charData = this.charData.substring(0, (int)length);
}
public void writerClosed(char[] charDataBeingWritten) {
this.charData = new String(charDataBeingWritten);
}
public void writerClosed(WatchableWriter out) {
int dataLength = out.size();
if (dataLength < this.charData.length())
out.write(this.charData, dataLength, this.charData.length() - dataLength);
this.charData = out.toString();
}
public void free() throws SQLException {
this.charData = null;
}
public Reader getCharacterStream(long pos, long length) throws SQLException {
return new StringReader(getSubString(pos, (int)length));
}
}

View file

@ -0,0 +1,33 @@
package com.mysql.jdbc;
class Collation {
public final int index;
public final String collationName;
public final int priority;
public final MysqlCharset mysqlCharset;
public Collation(int index, String collationName, int priority, String charsetName) {
this.index = index;
this.collationName = collationName;
this.priority = priority;
this.mysqlCharset = CharsetMapping.CHARSET_NAME_TO_CHARSET.get(charsetName);
}
public String toString() {
StringBuffer asString = new StringBuffer();
asString.append("[");
asString.append("index=");
asString.append(this.index);
asString.append(",collationName=");
asString.append(this.collationName);
asString.append(",charsetName=");
asString.append(this.mysqlCharset.charsetName);
asString.append(",javaCharsetName=");
asString.append(this.mysqlCharset.getMatchingJavaEncoding(null));
asString.append("]");
return asString.toString();
}
}

View file

@ -0,0 +1,45 @@
package com.mysql.jdbc;
import java.sql.SQLException;
public class CommunicationsException extends SQLException implements StreamingNotifiable {
static final long serialVersionUID = 3193864990663398317L;
private String exceptionMessage = null;
private boolean streamingResultSetInPlay = false;
private MySQLConnection conn;
private long lastPacketSentTimeMs;
private long lastPacketReceivedTimeMs;
private Exception underlyingException;
public CommunicationsException(MySQLConnection conn, long lastPacketSentTimeMs, long lastPacketReceivedTimeMs, Exception underlyingException) {
this.conn = conn;
this.lastPacketReceivedTimeMs = lastPacketReceivedTimeMs;
this.lastPacketSentTimeMs = lastPacketSentTimeMs;
this.underlyingException = underlyingException;
if (underlyingException != null)
initCause(underlyingException);
}
public String getMessage() {
if (this.exceptionMessage == null) {
this.exceptionMessage = SQLError.createLinkFailureMessageBasedOnHeuristics(this.conn, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, this.underlyingException, this.streamingResultSetInPlay);
this.conn = null;
this.underlyingException = null;
}
return this.exceptionMessage;
}
public String getSQLState() {
return "08S01";
}
public void setWasStreamingResults() {
this.streamingResultSetInPlay = true;
}
}

View file

@ -0,0 +1,160 @@
package com.mysql.jdbc;
import com.mysql.jdbc.log.Log;
import com.mysql.jdbc.log.NullLogger;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
class CompressedInputStream extends InputStream {
private byte[] buffer;
private InputStream in;
private Inflater inflater;
private ConnectionPropertiesImpl.BooleanConnectionProperty traceProtocol;
private Log log;
private byte[] packetHeaderBuffer = new byte[7];
private int pos = 0;
public CompressedInputStream(Connection conn, InputStream streamFromServer) {
this.traceProtocol = ((ConnectionPropertiesImpl)conn).traceProtocol;
try {
this.log = conn.getLog();
} catch (SQLException e) {
this.log = new NullLogger(null);
}
this.in = streamFromServer;
this.inflater = new Inflater();
}
public int available() throws IOException {
if (this.buffer == null)
return this.in.available();
return this.buffer.length - this.pos + this.in.available();
}
public void close() throws IOException {
this.in.close();
this.buffer = null;
this.inflater.end();
this.inflater = null;
this.traceProtocol = null;
this.log = null;
}
private void getNextPacketFromServer() throws IOException {
byte[] uncompressedData = null;
int lengthRead = readFully(this.packetHeaderBuffer, 0, 7);
if (lengthRead < 7)
throw new IOException("Unexpected end of input stream");
int compressedPacketLength = (this.packetHeaderBuffer[0] & 0xFF) + ((this.packetHeaderBuffer[1] & 0xFF) << 8) + ((this.packetHeaderBuffer[2] & 0xFF) << 16);
int uncompressedLength = (this.packetHeaderBuffer[4] & 0xFF) + ((this.packetHeaderBuffer[5] & 0xFF) << 8) + ((this.packetHeaderBuffer[6] & 0xFF) << 16);
boolean doTrace = this.traceProtocol.getValueAsBoolean();
if (doTrace)
this.log.logTrace("Reading compressed packet of length " + compressedPacketLength + " uncompressed to " + uncompressedLength);
if (uncompressedLength > 0) {
uncompressedData = new byte[uncompressedLength];
byte[] compressedBuffer = new byte[compressedPacketLength];
readFully(compressedBuffer, 0, compressedPacketLength);
try {
this.inflater.reset();
} catch (NullPointerException npe) {
this.inflater = new Inflater();
}
this.inflater.setInput(compressedBuffer);
try {
this.inflater.inflate(uncompressedData);
} catch (DataFormatException dfe) {
throw new IOException("Error while uncompressing packet from server.");
}
this.inflater.end();
} else {
if (doTrace)
this.log.logTrace("Packet didn't meet compression threshold, not uncompressing...");
uncompressedData = new byte[compressedPacketLength];
readFully(uncompressedData, 0, compressedPacketLength);
}
if (doTrace)
this.log.logTrace("Uncompressed packet: \n" + StringUtils.dumpAsHex(uncompressedData, compressedPacketLength));
if (this.buffer != null && this.pos < this.buffer.length) {
if (doTrace)
this.log.logTrace("Combining remaining packet with new: ");
int remaining = this.buffer.length - this.pos;
byte[] newBuffer = new byte[remaining + uncompressedData.length];
int newIndex = 0;
for (int i = this.pos; i < this.buffer.length; i++)
newBuffer[newIndex++] = this.buffer[i];
System.arraycopy(uncompressedData, 0, newBuffer, newIndex, uncompressedData.length);
uncompressedData = newBuffer;
}
this.pos = 0;
this.buffer = uncompressedData;
}
private void getNextPacketIfRequired(int numBytes) throws IOException {
if (this.buffer == null || this.pos + numBytes > this.buffer.length)
getNextPacketFromServer();
}
public int read() throws IOException {
try {
getNextPacketIfRequired(1);
} catch (IOException ioEx) {
return -1;
}
return this.buffer[this.pos++] & 0xFF;
}
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
public int read(byte[] b, int off, int len) throws IOException {
if (b == null)
throw new NullPointerException();
if (off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0)
throw new IndexOutOfBoundsException();
if (len <= 0)
return 0;
try {
getNextPacketIfRequired(len);
} catch (IOException ioEx) {
return -1;
}
System.arraycopy(this.buffer, this.pos, b, off, len);
this.pos += len;
return len;
}
private final int readFully(byte[] b, int off, int len) throws IOException {
if (len < 0)
throw new IndexOutOfBoundsException();
int n = 0;
while (n < len) {
int count = this.in.read(b, off + n, len - n);
if (count < 0)
throw new EOFException();
n += count;
}
return n;
}
public long skip(long n) throws IOException {
long count = 0L;
for (long i = 0L; i < n; i++) {
int bytesRead = read();
if (bytesRead == -1)
break;
count++;
}
return count;
}
}

View file

@ -0,0 +1,126 @@
package com.mysql.jdbc;
import com.mysql.jdbc.log.Log;
import java.sql.SQLException;
import java.util.Properties;
import java.util.TimeZone;
import java.util.concurrent.Executor;
public interface Connection extends java.sql.Connection, ConnectionProperties {
void changeUser(String paramString1, String paramString2) throws SQLException;
void clearHasTriedMaster();
java.sql.PreparedStatement clientPrepareStatement(String paramString) throws SQLException;
java.sql.PreparedStatement clientPrepareStatement(String paramString, int paramInt) throws SQLException;
java.sql.PreparedStatement clientPrepareStatement(String paramString, int paramInt1, int paramInt2) throws SQLException;
java.sql.PreparedStatement clientPrepareStatement(String paramString, int[] paramArrayOfint) throws SQLException;
java.sql.PreparedStatement clientPrepareStatement(String paramString, int paramInt1, int paramInt2, int paramInt3) throws SQLException;
java.sql.PreparedStatement clientPrepareStatement(String paramString, String[] paramArrayOfString) throws SQLException;
int getActiveStatementCount();
long getIdleFor();
Log getLog() throws SQLException;
@Deprecated
String getServerCharacterEncoding();
String getServerCharset();
TimeZone getServerTimezoneTZ();
String getStatementComment();
boolean hasTriedMaster();
boolean isInGlobalTx();
void setInGlobalTx(boolean paramBoolean);
boolean isMasterConnection();
boolean isNoBackslashEscapesSet();
boolean isSameResource(Connection paramConnection);
boolean lowerCaseTableNames();
boolean parserKnowsUnicode();
void ping() throws SQLException;
void resetServerState() throws SQLException;
java.sql.PreparedStatement serverPrepareStatement(String paramString) throws SQLException;
java.sql.PreparedStatement serverPrepareStatement(String paramString, int paramInt) throws SQLException;
java.sql.PreparedStatement serverPrepareStatement(String paramString, int paramInt1, int paramInt2) throws SQLException;
java.sql.PreparedStatement serverPrepareStatement(String paramString, int paramInt1, int paramInt2, int paramInt3) throws SQLException;
java.sql.PreparedStatement serverPrepareStatement(String paramString, int[] paramArrayOfint) throws SQLException;
java.sql.PreparedStatement serverPrepareStatement(String paramString, String[] paramArrayOfString) throws SQLException;
void setFailedOver(boolean paramBoolean);
void setPreferSlaveDuringFailover(boolean paramBoolean);
void setStatementComment(String paramString);
void shutdownServer() throws SQLException;
boolean supportsIsolationLevel();
boolean supportsQuotedIdentifiers();
boolean supportsTransactions();
boolean versionMeetsMinimum(int paramInt1, int paramInt2, int paramInt3) throws SQLException;
void reportQueryTime(long paramLong);
boolean isAbonormallyLongQuery(long paramLong);
void initializeExtension(Extension paramExtension) throws SQLException;
int getAutoIncrementIncrement();
boolean hasSameProperties(Connection paramConnection);
Properties getProperties();
String getHost();
void setProxy(MySQLConnection paramMySQLConnection);
boolean isServerLocal() throws SQLException;
int getSessionMaxRows();
void setSessionMaxRows(int paramInt) throws SQLException;
void setSchema(String paramString) throws SQLException;
String getSchema() throws SQLException;
void abort(Executor paramExecutor) throws SQLException;
void setNetworkTimeout(Executor paramExecutor, int paramInt) throws SQLException;
int getNetworkTimeout() throws SQLException;
void abortInternal() throws SQLException;
void checkClosed() throws SQLException;
Object getConnectionMutex();
}

View file

@ -0,0 +1,17 @@
package com.mysql.jdbc;
public class ConnectionFeatureNotAvailableException extends CommunicationsException {
static final long serialVersionUID = -5065030488729238287L;
public ConnectionFeatureNotAvailableException(MySQLConnection conn, long lastPacketSentTimeMs, Exception underlyingException) {
super(conn, lastPacketSentTimeMs, 0L, underlyingException);
}
public String getMessage() {
return "Feature not available in this distribution of Connector/J";
}
public String getSQLState() {
return "01S00";
}
}

View file

@ -0,0 +1,180 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ConnectionGroup {
private String groupName;
private long connections = 0L;
private long activeConnections = 0L;
private HashMap<Long, LoadBalancingConnectionProxy> connectionProxies = new HashMap<Long, LoadBalancingConnectionProxy>();
private Set<String> hostList = new HashSet<String>();
private boolean isInitialized = false;
private long closedProxyTotalPhysicalConnections = 0L;
private long closedProxyTotalTransactions = 0L;
private int activeHosts = 0;
private Set<String> closedHosts = new HashSet<String>();
ConnectionGroup(String groupName) {
this.groupName = groupName;
}
public long registerConnectionProxy(LoadBalancingConnectionProxy proxy, List<String> localHostList) {
long currentConnectionId;
synchronized (this) {
if (!this.isInitialized) {
this.hostList.addAll(localHostList);
this.isInitialized = true;
this.activeHosts = localHostList.size();
}
currentConnectionId = ++this.connections;
this.connectionProxies.put(Long.valueOf(currentConnectionId), proxy);
}
this.activeConnections++;
return currentConnectionId;
}
public String getGroupName() {
return this.groupName;
}
public Collection<String> getInitialHosts() {
return this.hostList;
}
public int getActiveHostCount() {
return this.activeHosts;
}
public Collection<String> getClosedHosts() {
return this.closedHosts;
}
public long getTotalLogicalConnectionCount() {
return this.connections;
}
public long getActiveLogicalConnectionCount() {
return this.activeConnections;
}
public long getActivePhysicalConnectionCount() {
long result = 0L;
Map<Long, LoadBalancingConnectionProxy> proxyMap = new HashMap<Long, LoadBalancingConnectionProxy>();
synchronized (this.connectionProxies) {
proxyMap.putAll(this.connectionProxies);
}
Iterator<Map.Entry<Long, LoadBalancingConnectionProxy>> i = proxyMap.entrySet().iterator();
while (i.hasNext()) {
LoadBalancingConnectionProxy proxy = (LoadBalancingConnectionProxy)i.next().getValue();
result += proxy.getActivePhysicalConnectionCount();
}
return result;
}
public long getTotalPhysicalConnectionCount() {
long allConnections = this.closedProxyTotalPhysicalConnections;
Map<Long, LoadBalancingConnectionProxy> proxyMap = new HashMap<Long, LoadBalancingConnectionProxy>();
synchronized (this.connectionProxies) {
proxyMap.putAll(this.connectionProxies);
}
Iterator<Map.Entry<Long, LoadBalancingConnectionProxy>> i = proxyMap.entrySet().iterator();
while (i.hasNext()) {
LoadBalancingConnectionProxy proxy = (LoadBalancingConnectionProxy)i.next().getValue();
allConnections += proxy.getTotalPhysicalConnectionCount();
}
return allConnections;
}
public long getTotalTransactionCount() {
long transactions = this.closedProxyTotalTransactions;
Map<Long, LoadBalancingConnectionProxy> proxyMap = new HashMap<Long, LoadBalancingConnectionProxy>();
synchronized (this.connectionProxies) {
proxyMap.putAll(this.connectionProxies);
}
Iterator<Map.Entry<Long, LoadBalancingConnectionProxy>> i = proxyMap.entrySet().iterator();
while (i.hasNext()) {
LoadBalancingConnectionProxy proxy = (LoadBalancingConnectionProxy)i.next().getValue();
transactions += proxy.getTransactionCount();
}
return transactions;
}
public void closeConnectionProxy(LoadBalancingConnectionProxy proxy) {
this.activeConnections--;
this.connectionProxies.remove(Long.valueOf(proxy.getConnectionGroupProxyID()));
this.closedProxyTotalPhysicalConnections += proxy.getTotalPhysicalConnectionCount();
this.closedProxyTotalTransactions += proxy.getTransactionCount();
}
public void removeHost(String host) throws SQLException {
removeHost(host, false);
}
public void removeHost(String host, boolean killExistingConnections) throws SQLException {
removeHost(host, killExistingConnections, true);
}
public synchronized void removeHost(String host, boolean killExistingConnections, boolean waitForGracefulFailover) throws SQLException {
if (this.activeHosts == 1)
throw SQLError.createSQLException("Cannot remove host, only one configured host active.", null);
if (this.hostList.remove(host)) {
this.activeHosts--;
} else {
throw SQLError.createSQLException("Host is not configured: " + host, null);
}
if (killExistingConnections) {
Map<Long, LoadBalancingConnectionProxy> proxyMap = new HashMap<Long, LoadBalancingConnectionProxy>();
synchronized (this.connectionProxies) {
proxyMap.putAll(this.connectionProxies);
}
Iterator<Map.Entry<Long, LoadBalancingConnectionProxy>> i = proxyMap.entrySet().iterator();
while (i.hasNext()) {
LoadBalancingConnectionProxy proxy = (LoadBalancingConnectionProxy)i.next().getValue();
if (waitForGracefulFailover) {
proxy.removeHostWhenNotInUse(host);
continue;
}
proxy.removeHost(host);
}
}
this.closedHosts.add(host);
}
public void addHost(String host) {
addHost(host, false);
}
public void addHost(String host, boolean forExisting) {
synchronized (this) {
if (this.hostList.add(host))
this.activeHosts++;
}
if (!forExisting)
return;
Map<Long, LoadBalancingConnectionProxy> proxyMap = new HashMap<Long, LoadBalancingConnectionProxy>();
synchronized (this.connectionProxies) {
proxyMap.putAll(this.connectionProxies);
}
Iterator<Map.Entry<Long, LoadBalancingConnectionProxy>> i = proxyMap.entrySet().iterator();
while (i.hasNext()) {
LoadBalancingConnectionProxy proxy = (LoadBalancingConnectionProxy)i.next().getValue();
proxy.addHost(host);
}
}
}

View file

@ -0,0 +1,164 @@
package com.mysql.jdbc;
import com.mysql.jdbc.jmx.LoadBalanceConnectionGroupManager;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ConnectionGroupManager {
private static HashMap<String, ConnectionGroup> GROUP_MAP = new HashMap<String, ConnectionGroup>();
private static LoadBalanceConnectionGroupManager mbean = new LoadBalanceConnectionGroupManager();
private static boolean hasRegisteredJmx = false;
public static synchronized ConnectionGroup getConnectionGroupInstance(String groupName) {
if (GROUP_MAP.containsKey(groupName))
return GROUP_MAP.get(groupName);
ConnectionGroup group = new ConnectionGroup(groupName);
GROUP_MAP.put(groupName, group);
return group;
}
public static void registerJmx() throws SQLException {
if (hasRegisteredJmx)
return;
mbean.registerJmx();
hasRegisteredJmx = true;
}
public static ConnectionGroup getConnectionGroup(String groupName) {
return GROUP_MAP.get(groupName);
}
private static Collection<ConnectionGroup> getGroupsMatching(String group) {
if (group == null || group.equals("")) {
Set<ConnectionGroup> set = new HashSet<ConnectionGroup>();
set.addAll(GROUP_MAP.values());
return set;
}
Set<ConnectionGroup> s = new HashSet<ConnectionGroup>();
ConnectionGroup o = GROUP_MAP.get(group);
if (o != null)
s.add(o);
return s;
}
public static void addHost(String group, String host, boolean forExisting) {
Collection<ConnectionGroup> s = getGroupsMatching(group);
for (ConnectionGroup cg : s)
cg.addHost(host, forExisting);
}
public static int getActiveHostCount(String group) {
Set<String> active = new HashSet<String>();
Collection<ConnectionGroup> s = getGroupsMatching(group);
for (ConnectionGroup cg : s)
active.addAll(cg.getInitialHosts());
return active.size();
}
public static long getActiveLogicalConnectionCount(String group) {
int count = 0;
Collection<ConnectionGroup> s = getGroupsMatching(group);
for (ConnectionGroup cg : s)
count = (int)((long)count + cg.getActiveLogicalConnectionCount());
return (long)count;
}
public static long getActivePhysicalConnectionCount(String group) {
int count = 0;
Collection<ConnectionGroup> s = getGroupsMatching(group);
for (ConnectionGroup cg : s)
count = (int)((long)count + cg.getActivePhysicalConnectionCount());
return (long)count;
}
public static int getTotalHostCount(String group) {
Collection<ConnectionGroup> s = getGroupsMatching(group);
Set<String> hosts = new HashSet<String>();
for (ConnectionGroup cg : s) {
hosts.addAll(cg.getInitialHosts());
hosts.addAll(cg.getClosedHosts());
}
return hosts.size();
}
public static long getTotalLogicalConnectionCount(String group) {
long count = 0L;
Collection<ConnectionGroup> s = getGroupsMatching(group);
for (ConnectionGroup cg : s)
count += cg.getTotalLogicalConnectionCount();
return count;
}
public static long getTotalPhysicalConnectionCount(String group) {
long count = 0L;
Collection<ConnectionGroup> s = getGroupsMatching(group);
for (ConnectionGroup cg : s)
count += cg.getTotalPhysicalConnectionCount();
return count;
}
public static long getTotalTransactionCount(String group) {
long count = 0L;
Collection<ConnectionGroup> s = getGroupsMatching(group);
for (ConnectionGroup cg : s)
count += cg.getTotalTransactionCount();
return count;
}
public static void removeHost(String group, String host) throws SQLException {
removeHost(group, host, false);
}
public static void removeHost(String group, String host, boolean removeExisting) throws SQLException {
Collection<ConnectionGroup> s = getGroupsMatching(group);
for (ConnectionGroup cg : s)
cg.removeHost(host, removeExisting);
}
public static String getActiveHostLists(String group) {
Collection<ConnectionGroup> s = getGroupsMatching(group);
Map<String, Integer> hosts = new HashMap<String, Integer>();
for (ConnectionGroup cg : s) {
Collection<String> l = cg.getInitialHosts();
for (String host : l) {
Integer o = hosts.get(host);
if (o == null) {
o = 1;
} else {
o = o + 1;
}
hosts.put(host, o);
}
}
StringBuffer sb = new StringBuffer();
String sep = "";
for (String host : hosts.keySet()) {
sb.append(sep);
sb.append(host);
sb.append('(');
sb.append(hosts.get(host));
sb.append(')');
sep = ",";
}
return sb.toString();
}
public static String getRegisteredConnectionGroups() {
Collection<ConnectionGroup> s = getGroupsMatching(null);
StringBuffer sb = new StringBuffer();
String sep = "";
for (ConnectionGroup cg : s) {
String group = cg.getGroupName();
sb.append(sep);
sb.append(group);
sep = ",";
}
return sb.toString();
}
}

View file

@ -0,0 +1,22 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.sql.Savepoint;
public interface ConnectionLifecycleInterceptor extends Extension {
void close() throws SQLException;
boolean commit() throws SQLException;
boolean rollback() throws SQLException;
boolean rollback(Savepoint paramSavepoint) throws SQLException;
boolean setAutoCommit(boolean paramBoolean) throws SQLException;
boolean setCatalog(String paramString) throws SQLException;
boolean transactionBegun() throws SQLException;
boolean transactionCompleted() throws SQLException;
}

View file

@ -0,0 +1,829 @@
package com.mysql.jdbc;
import java.sql.SQLException;
public interface ConnectionProperties {
String exposeAsXml() throws SQLException;
boolean getAllowLoadLocalInfile();
boolean getAllowMultiQueries();
boolean getAllowNanAndInf();
boolean getAllowUrlInLocalInfile();
boolean getAlwaysSendSetIsolation();
boolean getAutoDeserialize();
boolean getAutoGenerateTestcaseScript();
boolean getAutoReconnectForPools();
int getBlobSendChunkSize();
boolean getCacheCallableStatements();
boolean getCachePreparedStatements();
boolean getCacheResultSetMetadata();
boolean getCacheServerConfiguration();
int getCallableStatementCacheSize();
boolean getCapitalizeTypeNames();
String getCharacterSetResults();
boolean getClobberStreamingResults();
String getClobCharacterEncoding();
String getConnectionCollation();
int getConnectTimeout();
boolean getContinueBatchOnError();
boolean getCreateDatabaseIfNotExist();
int getDefaultFetchSize();
boolean getDontTrackOpenResources();
boolean getDumpQueriesOnException();
boolean getDynamicCalendars();
boolean getElideSetAutoCommits();
boolean getEmptyStringsConvertToZero();
boolean getEmulateLocators();
boolean getEmulateUnsupportedPstmts();
boolean getEnablePacketDebug();
String getEncoding();
boolean getExplainSlowQueries();
boolean getFailOverReadOnly();
boolean getGatherPerformanceMetrics();
boolean getHoldResultsOpenOverStatementClose();
boolean getIgnoreNonTxTables();
int getInitialTimeout();
boolean getInteractiveClient();
boolean getIsInteractiveClient();
boolean getJdbcCompliantTruncation();
int getLocatorFetchBufferSize();
String getLogger();
String getLoggerClassName();
boolean getLogSlowQueries();
boolean getMaintainTimeStats();
int getMaxQuerySizeToLog();
int getMaxReconnects();
int getMaxRows();
int getMetadataCacheSize();
boolean getNoDatetimeStringSync();
boolean getNullCatalogMeansCurrent();
boolean getNullNamePatternMatchesAll();
int getPacketDebugBufferSize();
boolean getParanoid();
boolean getPedantic();
int getPreparedStatementCacheSize();
int getPreparedStatementCacheSqlLimit();
boolean getProfileSql();
boolean getProfileSQL();
String getPropertiesTransform();
int getQueriesBeforeRetryMaster();
boolean getReconnectAtTxEnd();
boolean getRelaxAutoCommit();
int getReportMetricsIntervalMillis();
boolean getRequireSSL();
boolean getRollbackOnPooledClose();
boolean getRoundRobinLoadBalance();
boolean getRunningCTS13();
int getSecondsBeforeRetryMaster();
String getServerTimezone();
String getSessionVariables();
int getSlowQueryThresholdMillis();
String getSocketFactoryClassName();
int getSocketTimeout();
boolean getStrictFloatingPoint();
boolean getStrictUpdates();
boolean getTinyInt1isBit();
boolean getTraceProtocol();
boolean getTransformedBitIsBoolean();
boolean getUseCompression();
boolean getUseFastIntParsing();
boolean getUseHostsInPrivileges();
boolean getUseInformationSchema();
boolean getUseLocalSessionState();
boolean getUseOldUTF8Behavior();
boolean getUseOnlyServerErrorMessages();
boolean getUseReadAheadInput();
boolean getUseServerPreparedStmts();
boolean getUseSqlStateCodes();
boolean getUseSSL();
boolean getUseStreamLengthsInPrepStmts();
boolean getUseTimezone();
boolean getUseUltraDevWorkAround();
boolean getUseUnbufferedInput();
boolean getUseUnicode();
boolean getUseUsageAdvisor();
boolean getYearIsDateType();
String getZeroDateTimeBehavior();
void setAllowLoadLocalInfile(boolean paramBoolean);
void setAllowMultiQueries(boolean paramBoolean);
void setAllowNanAndInf(boolean paramBoolean);
void setAllowUrlInLocalInfile(boolean paramBoolean);
void setAlwaysSendSetIsolation(boolean paramBoolean);
void setAutoDeserialize(boolean paramBoolean);
void setAutoGenerateTestcaseScript(boolean paramBoolean);
void setAutoReconnect(boolean paramBoolean);
void setAutoReconnectForConnectionPools(boolean paramBoolean);
void setAutoReconnectForPools(boolean paramBoolean);
void setBlobSendChunkSize(String paramString) throws SQLException;
void setCacheCallableStatements(boolean paramBoolean);
void setCachePreparedStatements(boolean paramBoolean);
void setCacheResultSetMetadata(boolean paramBoolean);
void setCacheServerConfiguration(boolean paramBoolean);
void setCallableStatementCacheSize(int paramInt) throws SQLException;
void setCapitalizeDBMDTypes(boolean paramBoolean);
void setCapitalizeTypeNames(boolean paramBoolean);
void setCharacterEncoding(String paramString);
void setCharacterSetResults(String paramString);
void setClobberStreamingResults(boolean paramBoolean);
void setClobCharacterEncoding(String paramString);
void setConnectionCollation(String paramString);
void setConnectTimeout(int paramInt) throws SQLException;
void setContinueBatchOnError(boolean paramBoolean);
void setCreateDatabaseIfNotExist(boolean paramBoolean);
void setDefaultFetchSize(int paramInt) throws SQLException;
void setDetectServerPreparedStmts(boolean paramBoolean);
void setDontTrackOpenResources(boolean paramBoolean);
void setDumpQueriesOnException(boolean paramBoolean);
void setDynamicCalendars(boolean paramBoolean);
void setElideSetAutoCommits(boolean paramBoolean);
void setEmptyStringsConvertToZero(boolean paramBoolean);
void setEmulateLocators(boolean paramBoolean);
void setEmulateUnsupportedPstmts(boolean paramBoolean);
void setEnablePacketDebug(boolean paramBoolean);
void setEncoding(String paramString);
void setExplainSlowQueries(boolean paramBoolean);
void setFailOverReadOnly(boolean paramBoolean);
void setGatherPerformanceMetrics(boolean paramBoolean);
void setHoldResultsOpenOverStatementClose(boolean paramBoolean);
void setIgnoreNonTxTables(boolean paramBoolean);
void setInitialTimeout(int paramInt) throws SQLException;
void setIsInteractiveClient(boolean paramBoolean);
void setJdbcCompliantTruncation(boolean paramBoolean);
void setLocatorFetchBufferSize(String paramString) throws SQLException;
void setLogger(String paramString);
void setLoggerClassName(String paramString);
void setLogSlowQueries(boolean paramBoolean);
void setMaintainTimeStats(boolean paramBoolean);
void setMaxQuerySizeToLog(int paramInt) throws SQLException;
void setMaxReconnects(int paramInt) throws SQLException;
void setMaxRows(int paramInt) throws SQLException;
void setMetadataCacheSize(int paramInt) throws SQLException;
void setNoDatetimeStringSync(boolean paramBoolean);
void setNullCatalogMeansCurrent(boolean paramBoolean);
void setNullNamePatternMatchesAll(boolean paramBoolean);
void setPacketDebugBufferSize(int paramInt) throws SQLException;
void setParanoid(boolean paramBoolean);
void setPedantic(boolean paramBoolean);
void setPreparedStatementCacheSize(int paramInt) throws SQLException;
void setPreparedStatementCacheSqlLimit(int paramInt) throws SQLException;
void setProfileSql(boolean paramBoolean);
void setProfileSQL(boolean paramBoolean);
void setPropertiesTransform(String paramString);
void setQueriesBeforeRetryMaster(int paramInt) throws SQLException;
void setReconnectAtTxEnd(boolean paramBoolean);
void setRelaxAutoCommit(boolean paramBoolean);
void setReportMetricsIntervalMillis(int paramInt) throws SQLException;
void setRequireSSL(boolean paramBoolean);
void setRetainStatementAfterResultSetClose(boolean paramBoolean);
void setRollbackOnPooledClose(boolean paramBoolean);
void setRoundRobinLoadBalance(boolean paramBoolean);
void setRunningCTS13(boolean paramBoolean);
void setSecondsBeforeRetryMaster(int paramInt) throws SQLException;
void setServerTimezone(String paramString);
void setSessionVariables(String paramString);
void setSlowQueryThresholdMillis(int paramInt) throws SQLException;
void setSocketFactoryClassName(String paramString);
void setSocketTimeout(int paramInt) throws SQLException;
void setStrictFloatingPoint(boolean paramBoolean);
void setStrictUpdates(boolean paramBoolean);
void setTinyInt1isBit(boolean paramBoolean);
void setTraceProtocol(boolean paramBoolean);
void setTransformedBitIsBoolean(boolean paramBoolean);
void setUseCompression(boolean paramBoolean);
void setUseFastIntParsing(boolean paramBoolean);
void setUseHostsInPrivileges(boolean paramBoolean);
void setUseInformationSchema(boolean paramBoolean);
void setUseLocalSessionState(boolean paramBoolean);
void setUseOldUTF8Behavior(boolean paramBoolean);
void setUseOnlyServerErrorMessages(boolean paramBoolean);
void setUseReadAheadInput(boolean paramBoolean);
void setUseServerPreparedStmts(boolean paramBoolean);
void setUseSqlStateCodes(boolean paramBoolean);
void setUseSSL(boolean paramBoolean);
void setUseStreamLengthsInPrepStmts(boolean paramBoolean);
void setUseTimezone(boolean paramBoolean);
void setUseUltraDevWorkAround(boolean paramBoolean);
void setUseUnbufferedInput(boolean paramBoolean);
void setUseUnicode(boolean paramBoolean);
void setUseUsageAdvisor(boolean paramBoolean);
void setYearIsDateType(boolean paramBoolean);
void setZeroDateTimeBehavior(String paramString);
boolean useUnbufferedInput();
boolean getUseCursorFetch();
void setUseCursorFetch(boolean paramBoolean);
boolean getOverrideSupportsIntegrityEnhancementFacility();
void setOverrideSupportsIntegrityEnhancementFacility(boolean paramBoolean);
boolean getNoTimezoneConversionForTimeType();
void setNoTimezoneConversionForTimeType(boolean paramBoolean);
boolean getUseJDBCCompliantTimezoneShift();
void setUseJDBCCompliantTimezoneShift(boolean paramBoolean);
boolean getAutoClosePStmtStreams();
void setAutoClosePStmtStreams(boolean paramBoolean);
boolean getProcessEscapeCodesForPrepStmts();
void setProcessEscapeCodesForPrepStmts(boolean paramBoolean);
boolean getUseGmtMillisForDatetimes();
void setUseGmtMillisForDatetimes(boolean paramBoolean);
boolean getDumpMetadataOnColumnNotFound();
void setDumpMetadataOnColumnNotFound(boolean paramBoolean);
String getResourceId();
void setResourceId(String paramString);
boolean getRewriteBatchedStatements();
void setRewriteBatchedStatements(boolean paramBoolean);
boolean getJdbcCompliantTruncationForReads();
void setJdbcCompliantTruncationForReads(boolean paramBoolean);
boolean getUseJvmCharsetConverters();
void setUseJvmCharsetConverters(boolean paramBoolean);
boolean getPinGlobalTxToPhysicalConnection();
void setPinGlobalTxToPhysicalConnection(boolean paramBoolean);
void setGatherPerfMetrics(boolean paramBoolean);
boolean getGatherPerfMetrics();
void setUltraDevHack(boolean paramBoolean);
boolean getUltraDevHack();
void setInteractiveClient(boolean paramBoolean);
void setSocketFactory(String paramString);
String getSocketFactory();
void setUseServerPrepStmts(boolean paramBoolean);
boolean getUseServerPrepStmts();
void setCacheCallableStmts(boolean paramBoolean);
boolean getCacheCallableStmts();
void setCachePrepStmts(boolean paramBoolean);
boolean getCachePrepStmts();
void setCallableStmtCacheSize(int paramInt) throws SQLException;
int getCallableStmtCacheSize();
void setPrepStmtCacheSize(int paramInt) throws SQLException;
int getPrepStmtCacheSize();
void setPrepStmtCacheSqlLimit(int paramInt) throws SQLException;
int getPrepStmtCacheSqlLimit();
boolean getNoAccessToProcedureBodies();
void setNoAccessToProcedureBodies(boolean paramBoolean);
boolean getUseOldAliasMetadataBehavior();
void setUseOldAliasMetadataBehavior(boolean paramBoolean);
String getClientCertificateKeyStorePassword();
void setClientCertificateKeyStorePassword(String paramString);
String getClientCertificateKeyStoreType();
void setClientCertificateKeyStoreType(String paramString);
String getClientCertificateKeyStoreUrl();
void setClientCertificateKeyStoreUrl(String paramString);
String getTrustCertificateKeyStorePassword();
void setTrustCertificateKeyStorePassword(String paramString);
String getTrustCertificateKeyStoreType();
void setTrustCertificateKeyStoreType(String paramString);
String getTrustCertificateKeyStoreUrl();
void setTrustCertificateKeyStoreUrl(String paramString);
boolean getUseSSPSCompatibleTimezoneShift();
void setUseSSPSCompatibleTimezoneShift(boolean paramBoolean);
boolean getTreatUtilDateAsTimestamp();
void setTreatUtilDateAsTimestamp(boolean paramBoolean);
boolean getUseFastDateParsing();
void setUseFastDateParsing(boolean paramBoolean);
String getLocalSocketAddress();
void setLocalSocketAddress(String paramString);
void setUseConfigs(String paramString);
String getUseConfigs();
boolean getGenerateSimpleParameterMetadata();
void setGenerateSimpleParameterMetadata(boolean paramBoolean);
boolean getLogXaCommands();
void setLogXaCommands(boolean paramBoolean);
int getResultSetSizeThreshold();
void setResultSetSizeThreshold(int paramInt) throws SQLException;
int getNetTimeoutForStreamingResults();
void setNetTimeoutForStreamingResults(int paramInt) throws SQLException;
boolean getEnableQueryTimeouts();
void setEnableQueryTimeouts(boolean paramBoolean);
boolean getPadCharsWithSpace();
void setPadCharsWithSpace(boolean paramBoolean);
boolean getUseDynamicCharsetInfo();
void setUseDynamicCharsetInfo(boolean paramBoolean);
String getClientInfoProvider();
void setClientInfoProvider(String paramString);
boolean getPopulateInsertRowWithDefaultValues();
void setPopulateInsertRowWithDefaultValues(boolean paramBoolean);
String getLoadBalanceStrategy();
void setLoadBalanceStrategy(String paramString);
boolean getTcpNoDelay();
void setTcpNoDelay(boolean paramBoolean);
boolean getTcpKeepAlive();
void setTcpKeepAlive(boolean paramBoolean);
int getTcpRcvBuf();
void setTcpRcvBuf(int paramInt) throws SQLException;
int getTcpSndBuf();
void setTcpSndBuf(int paramInt) throws SQLException;
int getTcpTrafficClass();
void setTcpTrafficClass(int paramInt) throws SQLException;
boolean getUseNanosForElapsedTime();
void setUseNanosForElapsedTime(boolean paramBoolean);
long getSlowQueryThresholdNanos();
void setSlowQueryThresholdNanos(long paramLong) throws SQLException;
String getStatementInterceptors();
void setStatementInterceptors(String paramString);
boolean getUseDirectRowUnpack();
void setUseDirectRowUnpack(boolean paramBoolean);
String getLargeRowSizeThreshold();
void setLargeRowSizeThreshold(String paramString) throws SQLException;
boolean getUseBlobToStoreUTF8OutsideBMP();
void setUseBlobToStoreUTF8OutsideBMP(boolean paramBoolean);
String getUtf8OutsideBmpExcludedColumnNamePattern();
void setUtf8OutsideBmpExcludedColumnNamePattern(String paramString);
String getUtf8OutsideBmpIncludedColumnNamePattern();
void setUtf8OutsideBmpIncludedColumnNamePattern(String paramString);
boolean getIncludeInnodbStatusInDeadlockExceptions();
void setIncludeInnodbStatusInDeadlockExceptions(boolean paramBoolean);
boolean getIncludeThreadDumpInDeadlockExceptions();
void setIncludeThreadDumpInDeadlockExceptions(boolean paramBoolean);
boolean getIncludeThreadNamesAsStatementComment();
void setIncludeThreadNamesAsStatementComment(boolean paramBoolean);
boolean getBlobsAreStrings();
void setBlobsAreStrings(boolean paramBoolean);
boolean getFunctionsNeverReturnBlobs();
void setFunctionsNeverReturnBlobs(boolean paramBoolean);
boolean getAutoSlowLog();
void setAutoSlowLog(boolean paramBoolean);
String getConnectionLifecycleInterceptors();
void setConnectionLifecycleInterceptors(String paramString);
String getProfilerEventHandler();
void setProfilerEventHandler(String paramString);
boolean getVerifyServerCertificate();
void setVerifyServerCertificate(boolean paramBoolean);
boolean getUseLegacyDatetimeCode();
void setUseLegacyDatetimeCode(boolean paramBoolean);
int getSelfDestructOnPingSecondsLifetime();
void setSelfDestructOnPingSecondsLifetime(int paramInt) throws SQLException;
int getSelfDestructOnPingMaxOperations();
void setSelfDestructOnPingMaxOperations(int paramInt) throws SQLException;
boolean getUseColumnNamesInFindColumn();
void setUseColumnNamesInFindColumn(boolean paramBoolean);
boolean getUseLocalTransactionState();
void setUseLocalTransactionState(boolean paramBoolean);
boolean getCompensateOnDuplicateKeyUpdateCounts();
void setCompensateOnDuplicateKeyUpdateCounts(boolean paramBoolean);
void setUseAffectedRows(boolean paramBoolean);
boolean getUseAffectedRows();
void setPasswordCharacterEncoding(String paramString);
String getPasswordCharacterEncoding();
int getLoadBalanceBlacklistTimeout();
void setLoadBalanceBlacklistTimeout(int paramInt) throws SQLException;
void setRetriesAllDown(int paramInt) throws SQLException;
int getRetriesAllDown();
ExceptionInterceptor getExceptionInterceptor();
void setExceptionInterceptors(String paramString);
String getExceptionInterceptors();
boolean getQueryTimeoutKillsConnection();
void setQueryTimeoutKillsConnection(boolean paramBoolean);
int getMaxAllowedPacket();
boolean getRetainStatementAfterResultSetClose();
int getLoadBalancePingTimeout();
void setLoadBalancePingTimeout(int paramInt) throws SQLException;
boolean getLoadBalanceValidateConnectionOnSwapServer();
void setLoadBalanceValidateConnectionOnSwapServer(boolean paramBoolean);
String getLoadBalanceConnectionGroup();
void setLoadBalanceConnectionGroup(String paramString);
String getLoadBalanceExceptionChecker();
void setLoadBalanceExceptionChecker(String paramString);
String getLoadBalanceSQLStateFailover();
void setLoadBalanceSQLStateFailover(String paramString);
String getLoadBalanceSQLExceptionSubclassFailover();
void setLoadBalanceSQLExceptionSubclassFailover(String paramString);
boolean getLoadBalanceEnableJMX();
void setLoadBalanceEnableJMX(boolean paramBoolean);
void setLoadBalanceAutoCommitStatementThreshold(int paramInt) throws SQLException;
int getLoadBalanceAutoCommitStatementThreshold();
void setLoadBalanceAutoCommitStatementRegex(String paramString);
String getLoadBalanceAutoCommitStatementRegex();
void setAuthenticationPlugins(String paramString);
String getAuthenticationPlugins();
void setDisabledAuthenticationPlugins(String paramString);
String getDisabledAuthenticationPlugins();
void setDefaultAuthenticationPlugin(String paramString);
String getDefaultAuthenticationPlugin();
void setParseInfoCacheFactory(String paramString);
String getParseInfoCacheFactory();
void setServerConfigCacheFactory(String paramString);
String getServerConfigCacheFactory();
void setDisconnectOnExpiredPasswords(boolean paramBoolean);
boolean getDisconnectOnExpiredPasswords();
boolean getAllowMasterDownConnections();
void setAllowMasterDownConnections(boolean paramBoolean);
boolean getReplicationEnableJMX();
void setReplicationEnableJMX(boolean paramBoolean);
void setGetProceduresReturnsFunctions(boolean paramBoolean);
boolean getGetProceduresReturnsFunctions();
void setDetectCustomCollations(boolean paramBoolean);
boolean getDetectCustomCollations();
String getConnectionAttributes() throws SQLException;
String getServerRSAPublicKeyFile();
void setServerRSAPublicKeyFile(String paramString) throws SQLException;
boolean getAllowPublicKeyRetrieval();
void setAllowPublicKeyRetrieval(boolean paramBoolean) throws SQLException;
void setDontCheckOnDuplicateKeyUpdateInSQL(boolean paramBoolean);
boolean getDontCheckOnDuplicateKeyUpdateInSQL();
}

View file

@ -0,0 +1,8 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.Properties;
public interface ConnectionPropertiesTransform {
Properties transformProperties(Properties paramProperties) throws SQLException;
}

View file

@ -0,0 +1,11 @@
package com.mysql.jdbc;
public class Constants {
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
public static final String MILLIS_I18N = Messages.getString("Milliseconds");
public static final byte[] SLASH_STAR_SPACE_AS_BYTES = new byte[] { 47, 42, 32 };
public static final byte[] SPACE_STAR_SLASH_SPACE_AS_BYTES = new byte[] { 32, 42, 47, 32 };
}

View file

@ -0,0 +1,563 @@
package com.mysql.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class DatabaseMetaDataUsingInfoSchema extends DatabaseMetaData {
protected enum JDBC4FunctionConstant {
FUNCTION_COLUMN_UNKNOWN, FUNCTION_COLUMN_IN, FUNCTION_COLUMN_INOUT, FUNCTION_COLUMN_OUT, FUNCTION_COLUMN_RETURN, FUNCTION_COLUMN_RESULT, FUNCTION_NO_NULLS, FUNCTION_NULLABLE, FUNCTION_NULLABLE_UNKNOWN;
}
protected DatabaseMetaDataUsingInfoSchema(MySQLConnection connToSet, String databaseToSet) throws SQLException {
super(connToSet, databaseToSet);
ResultSet rs = null;
try {
rs = super.getTables("INFORMATION_SCHEMA", null, "PARAMETERS", new String[0]);
this.hasParametersView = rs.next();
} finally {
if (rs != null)
rs.close();
}
}
private boolean hasReferentialConstraintsView = this.conn.versionMeetsMinimum(5, 1, 10);
private final boolean hasParametersView;
protected ResultSet executeMetadataQuery(java.sql.PreparedStatement pStmt) throws SQLException {
ResultSet rs = pStmt.executeQuery();
((ResultSetInternalMethods)rs).setOwningStatement(null);
return rs;
}
public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException {
if (columnNamePattern == null)
if (this.conn.getNullNamePatternMatchesAll()) {
columnNamePattern = "%";
} else {
throw SQLError.createSQLException("Column name pattern can not be NULL or empty.", "S1009", getExceptionInterceptor());
}
if (catalog == null &&
this.conn.getNullCatalogMeansCurrent())
catalog = this.database;
String sql = "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME,COLUMN_NAME, NULL AS GRANTOR, GRANTEE, PRIVILEGE_TYPE AS PRIVILEGE, IS_GRANTABLE FROM INFORMATION_SCHEMA.COLUMN_PRIVILEGES WHERE TABLE_SCHEMA LIKE ? AND TABLE_NAME =? AND COLUMN_NAME LIKE ? ORDER BY COLUMN_NAME, PRIVILEGE_TYPE";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, table);
pStmt.setString(3, columnNamePattern);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(new Field[] { new Field("", "TABLE_CAT", 1, 64), new Field("", "TABLE_SCHEM", 1, 1), new Field("", "TABLE_NAME", 1, 64), new Field("", "COLUMN_NAME", 1, 64), new Field("", "GRANTOR", 1, 77), new Field("", "GRANTEE", 1, 77), new Field("", "PRIVILEGE", 1, 64), new Field("", "IS_GRANTABLE", 1, 3) });
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
public ResultSet getColumns(String catalog, String schemaPattern, String tableName, String columnNamePattern) throws SQLException {
if (columnNamePattern == null)
if (this.conn.getNullNamePatternMatchesAll()) {
columnNamePattern = "%";
} else {
throw SQLError.createSQLException("Column name pattern can not be NULL or empty.", "S1009", getExceptionInterceptor());
}
if (catalog == null &&
this.conn.getNullCatalogMeansCurrent())
catalog = this.database;
StringBuffer sqlBuf = new StringBuffer("SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM,TABLE_NAME,COLUMN_NAME,");
MysqlDefs.appendJdbcTypeMappingQuery(sqlBuf, "DATA_TYPE");
sqlBuf.append(" AS DATA_TYPE, ");
if (this.conn.getCapitalizeTypeNames()) {
sqlBuf.append("UPPER(CASE WHEN LOCATE('unsigned', COLUMN_TYPE) != 0 AND LOCATE('unsigned', DATA_TYPE) = 0 AND LOCATE('set', DATA_TYPE) <> 1 AND LOCATE('enum', DATA_TYPE) <> 1 THEN CONCAT(DATA_TYPE, ' unsigned') ELSE DATA_TYPE END) AS TYPE_NAME,");
} else {
sqlBuf.append("CASE WHEN LOCATE('unsigned', COLUMN_TYPE) != 0 AND LOCATE('unsigned', DATA_TYPE) = 0 AND LOCATE('set', DATA_TYPE) <> 1 AND LOCATE('enum', DATA_TYPE) <> 1 THEN CONCAT(DATA_TYPE, ' unsigned') ELSE DATA_TYPE END AS TYPE_NAME,");
}
sqlBuf.append("CASE WHEN LCASE(DATA_TYPE)='date' THEN 10 WHEN LCASE(DATA_TYPE)='time' THEN 8 WHEN LCASE(DATA_TYPE)='datetime' THEN 19 WHEN LCASE(DATA_TYPE)='timestamp' THEN 19 WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN NUMERIC_PRECISION WHEN CHARACTER_MAXIMUM_LENGTH > 2147483647 THEN 2147483647 ELSE CHARACTER_MAXIMUM_LENGTH END AS COLUMN_SIZE, " + MysqlIO.getMaxBuf() + " AS BUFFER_LENGTH," + "NUMERIC_SCALE AS DECIMAL_DIGITS," + "10 AS NUM_PREC_RADIX," + "CASE WHEN IS_NULLABLE='NO' THEN " + '\000' + " ELSE CASE WHEN IS_NULLABLE='YES' THEN " + '\001' + " ELSE " + '\002' + " END END AS NULLABLE," + "COLUMN_COMMENT AS REMARKS," + "COLUMN_DEFAULT AS COLUMN_DEF," + "0 AS SQL_DATA_TYPE," + "0 AS SQL_DATETIME_SUB," + "CASE WHEN CHARACTER_OCTET_LENGTH > " + 2147483647 + " THEN " + 2147483647 + " ELSE CHARACTER_OCTET_LENGTH END AS CHAR_OCTET_LENGTH," + "ORDINAL_POSITION," + "IS_NULLABLE," + "NULL AS SCOPE_CATALOG," + "NULL AS SCOPE_SCHEMA," + "NULL AS SCOPE_TABLE," + "NULL AS SOURCE_DATA_TYPE," + "IF (EXTRA LIKE '%auto_increment%','YES','NO') AS IS_AUTOINCREMENT " + "FROM INFORMATION_SCHEMA.COLUMNS WHERE ");
boolean operatingOnInformationSchema = "information_schema".equalsIgnoreCase(catalog);
if (catalog != null) {
if (operatingOnInformationSchema || (StringUtils.indexOfIgnoreCase(0, catalog, "%") == -1 && StringUtils.indexOfIgnoreCase(0, catalog, "_") == -1)) {
sqlBuf.append("TABLE_SCHEMA = ? AND ");
} else {
sqlBuf.append("TABLE_SCHEMA LIKE ? AND ");
}
} else {
sqlBuf.append("TABLE_SCHEMA LIKE ? AND ");
}
if (tableName != null) {
if (StringUtils.indexOfIgnoreCase(0, tableName, "%") == -1 && StringUtils.indexOfIgnoreCase(0, tableName, "_") == -1) {
sqlBuf.append("TABLE_NAME = ? AND ");
} else {
sqlBuf.append("TABLE_NAME LIKE ? AND ");
}
} else {
sqlBuf.append("TABLE_NAME LIKE ? AND ");
}
if (StringUtils.indexOfIgnoreCase(0, columnNamePattern, "%") == -1 && StringUtils.indexOfIgnoreCase(0, columnNamePattern, "_") == -1) {
sqlBuf.append("COLUMN_NAME = ? ");
} else {
sqlBuf.append("COLUMN_NAME LIKE ? ");
}
sqlBuf.append("ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION");
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sqlBuf.toString());
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, tableName);
pStmt.setString(3, columnNamePattern);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createColumnsFields());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
public ResultSet getCrossReference(String primaryCatalog, String primarySchema, String primaryTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException {
if (primaryTable == null)
throw SQLError.createSQLException("Table not specified.", "S1009", getExceptionInterceptor());
if (primaryCatalog == null &&
this.conn.getNullCatalogMeansCurrent())
primaryCatalog = this.database;
if (foreignCatalog == null &&
this.conn.getNullCatalogMeansCurrent())
foreignCatalog = this.database;
String sql = "SELECT A.REFERENCED_TABLE_SCHEMA AS PKTABLE_CAT,NULL AS PKTABLE_SCHEM,A.REFERENCED_TABLE_NAME AS PKTABLE_NAME,A.REFERENCED_COLUMN_NAME AS PKCOLUMN_NAME,A.TABLE_SCHEMA AS FKTABLE_CAT,NULL AS FKTABLE_SCHEM,A.TABLE_NAME AS FKTABLE_NAME, A.COLUMN_NAME AS FKCOLUMN_NAME, A.ORDINAL_POSITION AS KEY_SEQ," + generateUpdateRuleClause() + " AS UPDATE_RULE," + generateDeleteRuleClause() + " AS DELETE_RULE," + "A.CONSTRAINT_NAME AS FK_NAME," + "(SELECT CONSTRAINT_NAME FROM" + " INFORMATION_SCHEMA.TABLE_CONSTRAINTS" + " WHERE TABLE_SCHEMA = A.REFERENCED_TABLE_SCHEMA AND" + " TABLE_NAME = A.REFERENCED_TABLE_NAME AND" + " CONSTRAINT_TYPE IN ('UNIQUE','PRIMARY KEY') LIMIT 1)" + " AS PK_NAME," + '\007' + " AS DEFERRABILITY " + "FROM " + "INFORMATION_SCHEMA.KEY_COLUMN_USAGE A JOIN " + "INFORMATION_SCHEMA.TABLE_CONSTRAINTS B " + "USING (TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME) " + generateOptionalRefContraintsJoin() + "WHERE " + "B.CONSTRAINT_TYPE = 'FOREIGN KEY' " + "AND A.REFERENCED_TABLE_SCHEMA LIKE ? AND A.REFERENCED_TABLE_NAME=? " + "AND A.TABLE_SCHEMA LIKE ? AND A.TABLE_NAME=? " + "ORDER BY " + "A.TABLE_SCHEMA, A.TABLE_NAME, A.ORDINAL_POSITION";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (primaryCatalog != null) {
pStmt.setString(1, primaryCatalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, primaryTable);
if (foreignCatalog != null) {
pStmt.setString(3, foreignCatalog);
} else {
pStmt.setString(3, "%");
}
pStmt.setString(4, foreignTable);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createFkMetadataFields());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException {
if (table == null)
throw SQLError.createSQLException("Table not specified.", "S1009", getExceptionInterceptor());
if (catalog == null &&
this.conn.getNullCatalogMeansCurrent())
catalog = this.database;
String sql = "SELECT A.REFERENCED_TABLE_SCHEMA AS PKTABLE_CAT,NULL AS PKTABLE_SCHEM,A.REFERENCED_TABLE_NAME AS PKTABLE_NAME, A.REFERENCED_COLUMN_NAME AS PKCOLUMN_NAME, A.TABLE_SCHEMA AS FKTABLE_CAT,NULL AS FKTABLE_SCHEM,A.TABLE_NAME AS FKTABLE_NAME,A.COLUMN_NAME AS FKCOLUMN_NAME, A.ORDINAL_POSITION AS KEY_SEQ," + generateUpdateRuleClause() + " AS UPDATE_RULE," + generateDeleteRuleClause() + " AS DELETE_RULE," + "A.CONSTRAINT_NAME AS FK_NAME," + "(SELECT CONSTRAINT_NAME FROM" + " INFORMATION_SCHEMA.TABLE_CONSTRAINTS" + " WHERE TABLE_SCHEMA = A.REFERENCED_TABLE_SCHEMA AND" + " TABLE_NAME = A.REFERENCED_TABLE_NAME AND" + " CONSTRAINT_TYPE IN ('UNIQUE','PRIMARY KEY') LIMIT 1)" + " AS PK_NAME," + '\007' + " AS DEFERRABILITY " + "FROM " + "INFORMATION_SCHEMA.KEY_COLUMN_USAGE A JOIN " + "INFORMATION_SCHEMA.TABLE_CONSTRAINTS B " + "USING (TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_NAME) " + generateOptionalRefContraintsJoin() + "WHERE " + "B.CONSTRAINT_TYPE = 'FOREIGN KEY' " + "AND A.REFERENCED_TABLE_SCHEMA LIKE ? AND A.REFERENCED_TABLE_NAME=? " + "ORDER BY A.TABLE_SCHEMA, A.TABLE_NAME, A.ORDINAL_POSITION";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, table);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createFkMetadataFields());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
private String generateOptionalRefContraintsJoin() {
return this.hasReferentialConstraintsView ? "JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R ON (R.CONSTRAINT_NAME = B.CONSTRAINT_NAME AND R.TABLE_NAME = B.TABLE_NAME AND R.CONSTRAINT_SCHEMA = B.TABLE_SCHEMA) " : "";
}
private String generateDeleteRuleClause() {
return this.hasReferentialConstraintsView ? ("CASE WHEN R.DELETE_RULE='CASCADE' THEN " + String.valueOf(0) + " WHEN R.DELETE_RULE='SET NULL' THEN " + String.valueOf(2) + " WHEN R.DELETE_RULE='SET DEFAULT' THEN " + String.valueOf(4) + " WHEN R.DELETE_RULE='RESTRICT' THEN " + String.valueOf(1) + " WHEN R.DELETE_RULE='NO ACTION' THEN " + String.valueOf(3) + " ELSE " + String.valueOf(3) + " END ") : String.valueOf(1);
}
private String generateUpdateRuleClause() {
return this.hasReferentialConstraintsView ? ("CASE WHEN R.UPDATE_RULE='CASCADE' THEN " + String.valueOf(0) + " WHEN R.UPDATE_RULE='SET NULL' THEN " + String.valueOf(2) + " WHEN R.UPDATE_RULE='SET DEFAULT' THEN " + String.valueOf(4) + " WHEN R.UPDATE_RULE='RESTRICT' THEN " + String.valueOf(1) + " WHEN R.UPDATE_RULE='NO ACTION' THEN " + String.valueOf(3) + " ELSE " + String.valueOf(3) + " END ") : String.valueOf(1);
}
public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException {
if (table == null)
throw SQLError.createSQLException("Table not specified.", "S1009", getExceptionInterceptor());
if (catalog == null &&
this.conn.getNullCatalogMeansCurrent())
catalog = this.database;
String sql = "SELECT A.REFERENCED_TABLE_SCHEMA AS PKTABLE_CAT,NULL AS PKTABLE_SCHEM,A.REFERENCED_TABLE_NAME AS PKTABLE_NAME,A.REFERENCED_COLUMN_NAME AS PKCOLUMN_NAME,A.TABLE_SCHEMA AS FKTABLE_CAT,NULL AS FKTABLE_SCHEM,A.TABLE_NAME AS FKTABLE_NAME, A.COLUMN_NAME AS FKCOLUMN_NAME, A.ORDINAL_POSITION AS KEY_SEQ," + generateUpdateRuleClause() + " AS UPDATE_RULE," + generateDeleteRuleClause() + " AS DELETE_RULE," + "A.CONSTRAINT_NAME AS FK_NAME," + "(SELECT CONSTRAINT_NAME FROM" + " INFORMATION_SCHEMA.TABLE_CONSTRAINTS" + " WHERE TABLE_SCHEMA = A.REFERENCED_TABLE_SCHEMA AND" + " TABLE_NAME = A.REFERENCED_TABLE_NAME AND" + " CONSTRAINT_TYPE IN ('UNIQUE','PRIMARY KEY') LIMIT 1)" + " AS PK_NAME," + '\007' + " AS DEFERRABILITY " + "FROM " + "INFORMATION_SCHEMA.KEY_COLUMN_USAGE A " + "JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS B USING " + "(CONSTRAINT_NAME, TABLE_NAME) " + generateOptionalRefContraintsJoin() + "WHERE " + "B.CONSTRAINT_TYPE = 'FOREIGN KEY' " + "AND A.TABLE_SCHEMA LIKE ? " + "AND A.TABLE_NAME=? " + "AND A.REFERENCED_TABLE_SCHEMA IS NOT NULL " + "ORDER BY " + "A.REFERENCED_TABLE_SCHEMA, A.REFERENCED_TABLE_NAME, " + "A.ORDINAL_POSITION";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, table);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createFkMetadataFields());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException {
StringBuffer sqlBuf = new StringBuffer("SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM,TABLE_NAME,NON_UNIQUE,TABLE_SCHEMA AS INDEX_QUALIFIER,INDEX_NAME,3 AS TYPE,SEQ_IN_INDEX AS ORDINAL_POSITION,COLUMN_NAME,COLLATION AS ASC_OR_DESC,CARDINALITY,NULL AS PAGES,NULL AS FILTER_CONDITION FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA LIKE ? AND TABLE_NAME LIKE ?");
if (unique)
sqlBuf.append(" AND NON_UNIQUE=0 ");
sqlBuf.append("ORDER BY NON_UNIQUE, INDEX_NAME, SEQ_IN_INDEX");
java.sql.PreparedStatement pStmt = null;
try {
if (catalog == null &&
this.conn.getNullCatalogMeansCurrent())
catalog = this.database;
pStmt = prepareMetaDataSafeStatement(sqlBuf.toString());
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, table);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createIndexInfoFields());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException {
if (catalog == null &&
this.conn.getNullCatalogMeansCurrent())
catalog = this.database;
if (table == null)
throw SQLError.createSQLException("Table not specified.", "S1009", getExceptionInterceptor());
String sql = "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, SEQ_IN_INDEX AS KEY_SEQ, 'PRIMARY' AS PK_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA LIKE ? AND TABLE_NAME LIKE ? AND INDEX_NAME='PRIMARY' ORDER BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, table);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(new Field[] { new Field("", "TABLE_CAT", 1, 255), new Field("", "TABLE_SCHEM", 1, 0), new Field("", "TABLE_NAME", 1, 255), new Field("", "COLUMN_NAME", 1, 32), new Field("", "KEY_SEQ", 5, 5), new Field("", "PK_NAME", 1, 32) });
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException {
if (procedureNamePattern == null || procedureNamePattern.length() == 0)
if (this.conn.getNullNamePatternMatchesAll()) {
procedureNamePattern = "%";
} else {
throw SQLError.createSQLException("Procedure name pattern can not be NULL or empty.", "S1009", getExceptionInterceptor());
}
String db = null;
if (catalog == null) {
if (this.conn.getNullCatalogMeansCurrent())
db = this.database;
} else {
db = catalog;
}
String sql = "SELECT ROUTINE_SCHEMA AS PROCEDURE_CAT, NULL AS PROCEDURE_SCHEM, ROUTINE_NAME AS PROCEDURE_NAME, NULL AS RESERVED_1, NULL AS RESERVED_2, NULL AS RESERVED_3, ROUTINE_COMMENT AS REMARKS, CASE WHEN ROUTINE_TYPE = 'PROCEDURE' THEN 1 WHEN ROUTINE_TYPE='FUNCTION' THEN 2 ELSE 0 END AS PROCEDURE_TYPE, ROUTINE_NAME AS SPECIFIC_NAME FROM INFORMATION_SCHEMA.ROUTINES WHERE " + getRoutineTypeConditionForGetProcedures() + "ROUTINE_SCHEMA LIKE ? AND ROUTINE_NAME LIKE ? " + "ORDER BY ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (db != null) {
pStmt.setString(1, db);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, procedureNamePattern);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createFieldMetadataForGetProcedures());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
protected String getRoutineTypeConditionForGetProcedures() {
return "";
}
public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException {
if (!this.hasParametersView)
return getProcedureColumnsNoISParametersView(catalog, schemaPattern, procedureNamePattern, columnNamePattern);
if (procedureNamePattern == null || procedureNamePattern.length() == 0)
if (this.conn.getNullNamePatternMatchesAll()) {
procedureNamePattern = "%";
} else {
throw SQLError.createSQLException("Procedure name pattern can not be NULL or empty.", "S1009", getExceptionInterceptor());
}
String db = null;
if (catalog == null) {
if (this.conn.getNullCatalogMeansCurrent())
db = this.database;
} else {
db = catalog;
}
StringBuffer sqlBuf = new StringBuffer("SELECT SPECIFIC_SCHEMA AS PROCEDURE_CAT, NULL AS `PROCEDURE_SCHEM`, SPECIFIC_NAME AS `PROCEDURE_NAME`, IFNULL(PARAMETER_NAME, '') AS `COLUMN_NAME`, CASE WHEN PARAMETER_MODE = 'IN' THEN 1 WHEN PARAMETER_MODE = 'OUT' THEN 4 WHEN PARAMETER_MODE = 'INOUT' THEN 2 WHEN ORDINAL_POSITION = 0 THEN 5 ELSE 0 END AS `COLUMN_TYPE`, ");
MysqlDefs.appendJdbcTypeMappingQuery(sqlBuf, "DATA_TYPE");
sqlBuf.append(" AS `DATA_TYPE`, ");
if (this.conn.getCapitalizeTypeNames()) {
sqlBuf.append("UPPER(CASE WHEN LOCATE('unsigned', DATA_TYPE) != 0 AND LOCATE('unsigned', DATA_TYPE) = 0 THEN CONCAT(DATA_TYPE, ' unsigned') ELSE DATA_TYPE END) AS `TYPE_NAME`,");
} else {
sqlBuf.append("CASE WHEN LOCATE('unsigned', DATA_TYPE) != 0 AND LOCATE('unsigned', DATA_TYPE) = 0 THEN CONCAT(DATA_TYPE, ' unsigned') ELSE DATA_TYPE END AS `TYPE_NAME`,");
}
sqlBuf.append("NUMERIC_PRECISION AS `PRECISION`, ");
sqlBuf.append("CASE WHEN LCASE(DATA_TYPE)='date' THEN 10 WHEN LCASE(DATA_TYPE)='time' THEN 8 WHEN LCASE(DATA_TYPE)='datetime' THEN 19 WHEN LCASE(DATA_TYPE)='timestamp' THEN 19 WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN NUMERIC_PRECISION WHEN CHARACTER_MAXIMUM_LENGTH > 2147483647 THEN 2147483647 ELSE CHARACTER_MAXIMUM_LENGTH END AS LENGTH, ");
sqlBuf.append("NUMERIC_SCALE AS `SCALE`, ");
sqlBuf.append("10 AS RADIX,");
sqlBuf.append("1 AS `NULLABLE`, NULL AS `REMARKS`, NULL AS `COLUMN_DEF`, NULL AS `SQL_DATA_TYPE`, NULL AS `SQL_DATETIME_SUB`, CHARACTER_OCTET_LENGTH AS `CHAR_OCTET_LENGTH`, ORDINAL_POSITION, 'YES' AS `IS_NULLABLE`, SPECIFIC_NAME FROM INFORMATION_SCHEMA.PARAMETERS WHERE " + getRoutineTypeConditionForGetProcedureColumns() + "SPECIFIC_SCHEMA LIKE ? AND SPECIFIC_NAME LIKE ? AND (PARAMETER_NAME LIKE ? OR PARAMETER_NAME IS NULL) " + "ORDER BY SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_TYPE, ORDINAL_POSITION");
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sqlBuf.toString());
if (db != null) {
pStmt.setString(1, db);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, procedureNamePattern);
pStmt.setString(3, columnNamePattern);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createProcedureColumnsFields());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
protected ResultSet getProcedureColumnsNoISParametersView(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException {
return super.getProcedureColumns(catalog, schemaPattern, procedureNamePattern, columnNamePattern);
}
protected String getRoutineTypeConditionForGetProcedureColumns() {
return "";
}
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException {
String tableNamePat;
if (catalog == null &&
this.conn.getNullCatalogMeansCurrent())
catalog = this.database;
if (tableNamePattern == null)
if (this.conn.getNullNamePatternMatchesAll()) {
tableNamePattern = "%";
} else {
throw SQLError.createSQLException("Table name pattern can not be NULL or empty.", "S1009", getExceptionInterceptor());
}
String tmpCat = "";
if (catalog == null || catalog.length() == 0) {
if (this.conn.getNullCatalogMeansCurrent())
tmpCat = this.database;
} else {
tmpCat = catalog;
}
List<String> parseList = StringUtils.splitDBdotName(tableNamePattern, tmpCat, this.quotedId, this.conn.isNoBackslashEscapesSet());
if (parseList.size() == 2) {
tableNamePat = parseList.get(1);
} else {
tableNamePat = tableNamePattern;
}
java.sql.PreparedStatement pStmt = null;
String sql = "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME, CASE WHEN TABLE_TYPE='BASE TABLE' THEN CASE WHEN TABLE_SCHEMA = 'mysql' OR TABLE_SCHEMA = 'performance_schema' THEN 'SYSTEM TABLE' ELSE 'TABLE' END WHEN TABLE_TYPE='TEMPORARY' THEN 'LOCAL_TEMPORARY' ELSE TABLE_TYPE END AS TABLE_TYPE, TABLE_COMMENT AS REMARKS, NULL AS TYPE_CAT, NULL AS TYPE_SCHEM, NULL AS TYPE_NAME, NULL AS SELF_REFERENCING_COL_NAME, NULL AS REF_GENERATION FROM INFORMATION_SCHEMA.TABLES WHERE ";
boolean operatingOnInformationSchema = "information_schema".equalsIgnoreCase(catalog);
if (catalog != null) {
if (operatingOnInformationSchema || (StringUtils.indexOfIgnoreCase(0, catalog, "%") == -1 && StringUtils.indexOfIgnoreCase(0, catalog, "_") == -1)) {
sql = sql + "TABLE_SCHEMA = ? ";
} else {
sql = sql + "TABLE_SCHEMA LIKE ? ";
}
} else {
sql = sql + "TABLE_SCHEMA LIKE ? ";
}
if (tableNamePat != null) {
if (StringUtils.indexOfIgnoreCase(0, tableNamePat, "%") == -1 && StringUtils.indexOfIgnoreCase(0, tableNamePat, "_") == -1) {
sql = sql + "AND TABLE_NAME = ? ";
} else {
sql = sql + "AND TABLE_NAME LIKE ? ";
}
} else {
sql = sql + "AND TABLE_NAME LIKE ? ";
}
sql = sql + "HAVING TABLE_TYPE IN (?,?,?,?,?) ";
sql = sql + "ORDER BY TABLE_TYPE, TABLE_SCHEMA, TABLE_NAME";
try {
pStmt = prepareMetaDataSafeStatement(sql);
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, tableNamePat);
if (types == null || types.length == 0) {
DatabaseMetaData.TableType[] tableTypes = DatabaseMetaData.TableType.values();
for (int i = 0; i < 5; i++)
pStmt.setString(3 + i, tableTypes[i].getName());
} else {
for (int i = 0; i < 5; i++)
pStmt.setNull(3 + i, 12);
int idx = 3;
for (int j = 0; j < types.length; j++) {
DatabaseMetaData.TableType tableType = DatabaseMetaData.TableType.getTableTypeEqualTo(types[j]);
if (tableType != DatabaseMetaData.TableType.UNKNOWN)
pStmt.setString(idx++, tableType.getName());
}
}
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createTablesFields());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
public boolean gethasParametersView() {
return this.hasParametersView;
}
public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException {
if (catalog == null &&
this.conn.getNullCatalogMeansCurrent())
catalog = this.database;
if (table == null)
throw SQLError.createSQLException("Table not specified.", "S1009", getExceptionInterceptor());
StringBuffer sqlBuf = new StringBuffer("SELECT NULL AS SCOPE, COLUMN_NAME, ");
MysqlDefs.appendJdbcTypeMappingQuery(sqlBuf, "DATA_TYPE");
sqlBuf.append(" AS DATA_TYPE, ");
sqlBuf.append("COLUMN_TYPE AS TYPE_NAME, ");
sqlBuf.append("CASE WHEN LCASE(DATA_TYPE)='date' THEN 10 WHEN LCASE(DATA_TYPE)='time' THEN 8 WHEN LCASE(DATA_TYPE)='datetime' THEN 19 WHEN LCASE(DATA_TYPE)='timestamp' THEN 19 WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN NUMERIC_PRECISION WHEN CHARACTER_MAXIMUM_LENGTH > 2147483647 THEN 2147483647 ELSE CHARACTER_MAXIMUM_LENGTH END AS COLUMN_SIZE, ");
sqlBuf.append(MysqlIO.getMaxBuf() + " AS BUFFER_LENGTH," + "NUMERIC_SCALE AS DECIMAL_DIGITS, " + Integer.toString(1) + " AS PSEUDO_COLUMN " + "FROM INFORMATION_SCHEMA.COLUMNS " + "WHERE TABLE_SCHEMA LIKE ? AND TABLE_NAME LIKE ?" + " AND EXTRA LIKE '%on update CURRENT_TIMESTAMP%'");
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sqlBuf.toString());
if (catalog != null) {
pStmt.setString(1, catalog);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, table);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(new Field[] { new Field("", "SCOPE", 5, 5), new Field("", "COLUMN_NAME", 1, 32), new Field("", "DATA_TYPE", 4, 5), new Field("", "TYPE_NAME", 1, 16), new Field("", "COLUMN_SIZE", 4, 16), new Field("", "BUFFER_LENGTH", 4, 16), new Field("", "DECIMAL_DIGITS", 5, 16), new Field("", "PSEUDO_COLUMN", 5, 5) });
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException {
if (!this.hasParametersView)
return super.getFunctionColumns(catalog, schemaPattern, functionNamePattern, columnNamePattern);
if (functionNamePattern == null || functionNamePattern.length() == 0)
if (this.conn.getNullNamePatternMatchesAll()) {
functionNamePattern = "%";
} else {
throw SQLError.createSQLException("Procedure name pattern can not be NULL or empty.", "S1009", getExceptionInterceptor());
}
String db = null;
if (catalog == null) {
if (this.conn.getNullCatalogMeansCurrent())
db = this.database;
} else {
db = catalog;
}
StringBuffer sqlBuf = new StringBuffer("SELECT SPECIFIC_SCHEMA AS FUNCTION_CAT, NULL AS `FUNCTION_SCHEM`, SPECIFIC_NAME AS `FUNCTION_NAME`, IFNULL(PARAMETER_NAME, '') AS `COLUMN_NAME`, CASE WHEN PARAMETER_MODE = 'IN' THEN " + getJDBC4FunctionConstant(JDBC4FunctionConstant.FUNCTION_COLUMN_IN) + " WHEN PARAMETER_MODE = 'OUT' THEN " + getJDBC4FunctionConstant(JDBC4FunctionConstant.FUNCTION_COLUMN_OUT) + " WHEN PARAMETER_MODE = 'INOUT' THEN " + getJDBC4FunctionConstant(JDBC4FunctionConstant.FUNCTION_COLUMN_INOUT) + " WHEN ORDINAL_POSITION = 0 THEN " + getJDBC4FunctionConstant(JDBC4FunctionConstant.FUNCTION_COLUMN_RETURN) + " ELSE " + getJDBC4FunctionConstant(JDBC4FunctionConstant.FUNCTION_COLUMN_UNKNOWN) + " END AS `COLUMN_TYPE`, ");
MysqlDefs.appendJdbcTypeMappingQuery(sqlBuf, "DATA_TYPE");
sqlBuf.append(" AS `DATA_TYPE`, ");
if (this.conn.getCapitalizeTypeNames()) {
sqlBuf.append("UPPER(CASE WHEN LOCATE('unsigned', DATA_TYPE) != 0 AND LOCATE('unsigned', DATA_TYPE) = 0 THEN CONCAT(DATA_TYPE, ' unsigned') ELSE DATA_TYPE END) AS `TYPE_NAME`,");
} else {
sqlBuf.append("CASE WHEN LOCATE('unsigned', DATA_TYPE) != 0 AND LOCATE('unsigned', DATA_TYPE) = 0 THEN CONCAT(DATA_TYPE, ' unsigned') ELSE DATA_TYPE END AS `TYPE_NAME`,");
}
sqlBuf.append("NUMERIC_PRECISION AS `PRECISION`, ");
sqlBuf.append("CASE WHEN LCASE(DATA_TYPE)='date' THEN 10 WHEN LCASE(DATA_TYPE)='time' THEN 8 WHEN LCASE(DATA_TYPE)='datetime' THEN 19 WHEN LCASE(DATA_TYPE)='timestamp' THEN 19 WHEN CHARACTER_MAXIMUM_LENGTH IS NULL THEN NUMERIC_PRECISION WHEN CHARACTER_MAXIMUM_LENGTH > 2147483647 THEN 2147483647 ELSE CHARACTER_MAXIMUM_LENGTH END AS LENGTH, ");
sqlBuf.append("NUMERIC_SCALE AS `SCALE`, ");
sqlBuf.append("10 AS RADIX,");
sqlBuf.append(getJDBC4FunctionConstant(JDBC4FunctionConstant.FUNCTION_NULLABLE) + " AS `NULLABLE`, " + " NULL AS `REMARKS`, " + "CHARACTER_OCTET_LENGTH AS `CHAR_OCTET_LENGTH`, " + " ORDINAL_POSITION, " + "'YES' AS `IS_NULLABLE`, " + "SPECIFIC_NAME " + "FROM INFORMATION_SCHEMA.PARAMETERS WHERE " + "SPECIFIC_SCHEMA LIKE ? AND SPECIFIC_NAME LIKE ? AND (PARAMETER_NAME LIKE ? OR PARAMETER_NAME IS NULL) " + "AND ROUTINE_TYPE='FUNCTION' ORDER BY SPECIFIC_SCHEMA, SPECIFIC_NAME, ORDINAL_POSITION");
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sqlBuf.toString());
if (db != null) {
pStmt.setString(1, db);
} else {
pStmt.setString(1, "%");
}
pStmt.setString(2, functionNamePattern);
pStmt.setString(3, columnNamePattern);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(createFunctionColumnsFields());
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
protected int getJDBC4FunctionConstant(JDBC4FunctionConstant constant) {
return 0;
}
public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException {
if (functionNamePattern == null || functionNamePattern.length() == 0)
if (this.conn.getNullNamePatternMatchesAll()) {
functionNamePattern = "%";
} else {
throw SQLError.createSQLException("Function name pattern can not be NULL or empty.", "S1009", getExceptionInterceptor());
}
String db = null;
if (catalog == null) {
if (this.conn.getNullCatalogMeansCurrent())
db = this.database;
} else {
db = catalog;
}
String sql = "SELECT ROUTINE_SCHEMA AS FUNCTION_CAT, NULL AS FUNCTION_SCHEM, ROUTINE_NAME AS FUNCTION_NAME, ROUTINE_COMMENT AS REMARKS, " + getJDBC4FunctionNoTableConstant() + " AS FUNCTION_TYPE, ROUTINE_NAME AS SPECIFIC_NAME FROM INFORMATION_SCHEMA.ROUTINES " + "WHERE ROUTINE_TYPE LIKE 'FUNCTION' AND ROUTINE_SCHEMA LIKE ? AND " + "ROUTINE_NAME LIKE ? ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME";
java.sql.PreparedStatement pStmt = null;
try {
pStmt = prepareMetaDataSafeStatement(sql);
pStmt.setString(1, (db != null) ? db : "%");
pStmt.setString(2, functionNamePattern);
ResultSet rs = executeMetadataQuery(pStmt);
((ResultSetInternalMethods)rs).redefineFieldsForDBMD(new Field[] { new Field("", "FUNCTION_CAT", 1, 255), new Field("", "FUNCTION_SCHEM", 1, 255), new Field("", "FUNCTION_NAME", 1, 255), new Field("", "REMARKS", 1, 255), new Field("", "FUNCTION_TYPE", 5, 6), new Field("", "SPECIFIC_NAME", 1, 255) });
return rs;
} finally {
if (pStmt != null)
pStmt.close();
}
}
protected int getJDBC4FunctionNoTableConstant() {
return 0;
}
}

View file

@ -0,0 +1,9 @@
package com.mysql.jdbc;
public class DocsConnectionPropsHelper extends ConnectionPropertiesImpl {
static final long serialVersionUID = -1580779062220390294L;
public static void main(String[] args) throws Exception {
System.out.println(new DocsConnectionPropsHelper().exposeAsXml());
}
}

View file

@ -0,0 +1,14 @@
package com.mysql.jdbc;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
}

View file

@ -0,0 +1,398 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.TimeZone;
class EscapeProcessor {
private static Map<String, String> JDBC_CONVERT_TO_MYSQL_TYPE_MAP;
private static Map<String, String> JDBC_NO_CONVERT_TO_MYSQL_EXPRESSION_MAP;
static {
Map<String, String> tempMap = new HashMap<String, String>();
tempMap.put("BIGINT", "0 + ?");
tempMap.put("BINARY", "BINARY");
tempMap.put("BIT", "0 + ?");
tempMap.put("CHAR", "CHAR");
tempMap.put("DATE", "DATE");
tempMap.put("DECIMAL", "0.0 + ?");
tempMap.put("DOUBLE", "0.0 + ?");
tempMap.put("FLOAT", "0.0 + ?");
tempMap.put("INTEGER", "0 + ?");
tempMap.put("LONGVARBINARY", "BINARY");
tempMap.put("LONGVARCHAR", "CONCAT(?)");
tempMap.put("REAL", "0.0 + ?");
tempMap.put("SMALLINT", "CONCAT(?)");
tempMap.put("TIME", "TIME");
tempMap.put("TIMESTAMP", "DATETIME");
tempMap.put("TINYINT", "CONCAT(?)");
tempMap.put("VARBINARY", "BINARY");
tempMap.put("VARCHAR", "CONCAT(?)");
JDBC_CONVERT_TO_MYSQL_TYPE_MAP = Collections.<String, String>unmodifiableMap(tempMap);
tempMap = new HashMap<String, String>(JDBC_CONVERT_TO_MYSQL_TYPE_MAP);
tempMap.put("BINARY", "CONCAT(?)");
tempMap.put("CHAR", "CONCAT(?)");
tempMap.remove("DATE");
tempMap.put("LONGVARBINARY", "CONCAT(?)");
tempMap.remove("TIME");
tempMap.remove("TIMESTAMP");
tempMap.put("VARBINARY", "CONCAT(?)");
JDBC_NO_CONVERT_TO_MYSQL_EXPRESSION_MAP = Collections.<String, String>unmodifiableMap(tempMap);
}
public static final Object escapeSQL(String sql, boolean serverSupportsConvertFn, MySQLConnection conn) throws SQLException {
boolean replaceEscapeSequence = false;
String escapeSequence = null;
if (sql == null)
return null;
int beginBrace = sql.indexOf('{');
int nextEndBrace = (beginBrace == -1) ? -1 : sql.indexOf('}', beginBrace);
if (nextEndBrace == -1)
return sql;
StringBuffer newSql = new StringBuffer();
EscapeTokenizer escapeTokenizer = new EscapeTokenizer(sql);
byte usesVariables = 0;
boolean callingStoredFunction = false;
while (escapeTokenizer.hasMoreTokens()) {
String token = escapeTokenizer.nextToken();
if (token.length() != 0) {
if (token.charAt(0) == '{') {
if (!token.endsWith("}"))
throw SQLError.createSQLException("Not a valid escape sequence: " + token, conn.getExceptionInterceptor());
if (token.length() > 2) {
int nestedBrace = token.indexOf('{', 2);
if (nestedBrace != -1) {
StringBuffer buf = new StringBuffer(token.substring(0, 1));
Object remainingResults = escapeSQL(token.substring(1, token.length() - 1), serverSupportsConvertFn, conn);
String remaining = null;
if (remainingResults instanceof String) {
remaining = (String)remainingResults;
} else {
remaining = ((EscapeProcessorResult)remainingResults).escapedSql;
if (usesVariables != 1)
usesVariables = ((EscapeProcessorResult)remainingResults).usesVariables;
}
buf.append(remaining);
buf.append('}');
token = buf.toString();
}
}
String collapsedToken = removeWhitespace(token);
if (StringUtils.startsWithIgnoreCase(collapsedToken, "{escape")) {
try {
StringTokenizer st = new StringTokenizer(token, " '");
st.nextToken();
escapeSequence = st.nextToken();
if (escapeSequence.length() < 3) {
newSql.append(token);
continue;
}
escapeSequence = escapeSequence.substring(1, escapeSequence.length() - 1);
replaceEscapeSequence = true;
} catch (NoSuchElementException e) {
newSql.append(token);
}
continue;
}
if (StringUtils.startsWithIgnoreCase(collapsedToken, "{fn")) {
int startPos = token.toLowerCase().indexOf("fn ") + 3;
int endPos = token.length() - 1;
String fnToken = token.substring(startPos, endPos);
if (StringUtils.startsWithIgnoreCaseAndWs(fnToken, "convert")) {
newSql.append(processConvertToken(fnToken, serverSupportsConvertFn, conn));
continue;
}
newSql.append(fnToken);
continue;
}
if (StringUtils.startsWithIgnoreCase(collapsedToken, "{d")) {
int startPos = token.indexOf('\'') + 1;
int endPos = token.lastIndexOf('\'');
if (startPos == -1 || endPos == -1) {
newSql.append(token);
continue;
}
String argument = token.substring(startPos, endPos);
try {
StringTokenizer st = new StringTokenizer(argument, " -");
String year4 = st.nextToken();
String month2 = st.nextToken();
String day2 = st.nextToken();
String dateString = "'" + year4 + "-" + month2 + "-" + day2 + "'";
newSql.append(dateString);
} catch (NoSuchElementException e) {
throw SQLError.createSQLException("Syntax error for DATE escape sequence '" + argument + "'", "42000", conn.getExceptionInterceptor());
}
continue;
}
if (StringUtils.startsWithIgnoreCase(collapsedToken, "{ts")) {
processTimestampToken(conn, newSql, token);
continue;
}
if (StringUtils.startsWithIgnoreCase(collapsedToken, "{t")) {
processTimeToken(conn, newSql, token);
continue;
}
if (StringUtils.startsWithIgnoreCase(collapsedToken, "{call") || StringUtils.startsWithIgnoreCase(collapsedToken, "{?=call")) {
int startPos = StringUtils.indexOfIgnoreCase(token, "CALL") + 5;
int endPos = token.length() - 1;
if (StringUtils.startsWithIgnoreCase(collapsedToken, "{?=call")) {
callingStoredFunction = true;
newSql.append("SELECT ");
newSql.append(token.substring(startPos, endPos));
} else {
callingStoredFunction = false;
newSql.append("CALL ");
newSql.append(token.substring(startPos, endPos));
}
for (int i = endPos - 1; i >= startPos; ) {
char c = token.charAt(i);
if (Character.isWhitespace(c)) {
i--;
continue;
}
if (c != ')') {
newSql.append("()");
break;
}
break;
}
continue;
}
if (StringUtils.startsWithIgnoreCase(collapsedToken, "{oj")) {
newSql.append(token);
continue;
}
newSql.append(token);
continue;
}
newSql.append(token);
}
}
String escapedSql = newSql.toString();
if (replaceEscapeSequence) {
String currentSql = escapedSql;
while (currentSql.indexOf(escapeSequence) != -1) {
int escapePos = currentSql.indexOf(escapeSequence);
String lhs = currentSql.substring(0, escapePos);
String rhs = currentSql.substring(escapePos + 1, currentSql.length());
currentSql = lhs + "\\" + rhs;
}
escapedSql = currentSql;
}
EscapeProcessorResult epr = new EscapeProcessorResult();
epr.escapedSql = escapedSql;
epr.callingStoredFunction = callingStoredFunction;
if (usesVariables != 1)
if (escapeTokenizer.sawVariableUse()) {
epr.usesVariables = 1;
} else {
epr.usesVariables = 0;
}
return epr;
}
private static void processTimeToken(MySQLConnection conn, StringBuffer newSql, String token) throws SQLException {
int startPos = token.indexOf('\'') + 1;
int endPos = token.lastIndexOf('\'');
if (startPos == -1 || endPos == -1) {
newSql.append(token);
} else {
String argument = token.substring(startPos, endPos);
try {
StringTokenizer st = new StringTokenizer(argument, " :.");
String hour = st.nextToken();
String minute = st.nextToken();
String second = st.nextToken();
boolean serverSupportsFractionalSecond = false;
String fractionalSecond = "";
if (st.hasMoreTokens() &&
conn.versionMeetsMinimum(5, 6, 4)) {
serverSupportsFractionalSecond = true;
fractionalSecond = "." + st.nextToken();
}
if (conn != null && (!conn.getUseTimezone() || !conn.getUseLegacyDatetimeCode())) {
newSql.append("'");
newSql.append(hour);
newSql.append(":");
newSql.append(minute);
newSql.append(":");
newSql.append(second);
newSql.append(fractionalSecond);
newSql.append("'");
} else {
Calendar sessionCalendar = null;
if (conn != null) {
sessionCalendar = conn.getCalendarInstanceForSessionOrNew();
} else {
sessionCalendar = new GregorianCalendar();
}
try {
int hourInt = Integer.parseInt(hour);
int minuteInt = Integer.parseInt(minute);
int secondInt = Integer.parseInt(second);
synchronized (sessionCalendar) {
Time toBeAdjusted = TimeUtil.fastTimeCreate(sessionCalendar, hourInt, minuteInt, secondInt, conn.getExceptionInterceptor());
Time inServerTimezone = TimeUtil.changeTimezone(conn, sessionCalendar, null, toBeAdjusted, sessionCalendar.getTimeZone(), conn.getServerTimezoneTZ(), false);
newSql.append("'");
newSql.append(inServerTimezone.toString());
if (serverSupportsFractionalSecond)
newSql.append(fractionalSecond);
newSql.append("'");
}
} catch (NumberFormatException nfe) {
throw SQLError.createSQLException("Syntax error in TIMESTAMP escape sequence '" + token + "'.", "S1009", conn.getExceptionInterceptor());
}
}
} catch (NoSuchElementException e) {
throw SQLError.createSQLException("Syntax error for escape sequence '" + argument + "'", "42000", conn.getExceptionInterceptor());
}
}
}
private static void processTimestampToken(MySQLConnection conn, StringBuffer newSql, String token) throws SQLException {
int startPos = token.indexOf('\'') + 1;
int endPos = token.lastIndexOf('\'');
if (startPos == -1 || endPos == -1) {
newSql.append(token);
} else {
String argument = token.substring(startPos, endPos);
try {
if (conn != null && !conn.getUseLegacyDatetimeCode()) {
Timestamp ts = Timestamp.valueOf(argument);
SimpleDateFormat tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
tsdf.setTimeZone(conn.getServerTimezoneTZ());
newSql.append(tsdf.format((Date)ts));
if (ts.getNanos() > 0 && conn.versionMeetsMinimum(5, 6, 4)) {
newSql.append('.');
newSql.append(TimeUtil.formatNanos(ts.getNanos(), true, true));
}
newSql.append('\'');
} else {
StringTokenizer st = new StringTokenizer(argument, " .-:");
try {
String year4 = st.nextToken();
String month2 = st.nextToken();
String day2 = st.nextToken();
String hour = st.nextToken();
String minute = st.nextToken();
String second = st.nextToken();
boolean serverSupportsFractionalSecond = false;
String fractionalSecond = "";
if (st.hasMoreTokens() &&
conn.versionMeetsMinimum(5, 6, 4)) {
serverSupportsFractionalSecond = true;
fractionalSecond = "." + st.nextToken();
}
if (conn != null && !conn.getUseTimezone() && !conn.getUseJDBCCompliantTimezoneShift()) {
newSql.append("'").append(year4).append("-").append(month2).append("-").append(day2).append(" ").append(hour).append(":").append(minute).append(":").append(second).append(fractionalSecond).append("'");
} else {
Calendar sessionCalendar;
if (conn != null) {
sessionCalendar = conn.getCalendarInstanceForSessionOrNew();
} else {
sessionCalendar = new GregorianCalendar();
sessionCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
}
try {
int year4Int = Integer.parseInt(year4);
int month2Int = Integer.parseInt(month2);
int day2Int = Integer.parseInt(day2);
int hourInt = Integer.parseInt(hour);
int minuteInt = Integer.parseInt(minute);
int secondInt = Integer.parseInt(second);
synchronized (sessionCalendar) {
boolean useGmtMillis = conn.getUseGmtMillisForDatetimes();
Timestamp toBeAdjusted = TimeUtil.fastTimestampCreate(useGmtMillis, useGmtMillis ? Calendar.getInstance(TimeZone.getTimeZone("GMT")) : null, sessionCalendar, year4Int, month2Int, day2Int, hourInt, minuteInt, secondInt, 0);
Timestamp inServerTimezone = TimeUtil.changeTimezone(conn, sessionCalendar, null, toBeAdjusted, sessionCalendar.getTimeZone(), conn.getServerTimezoneTZ(), false);
newSql.append("'");
String timezoneLiteral = inServerTimezone.toString();
int indexOfDot = timezoneLiteral.indexOf(".");
if (indexOfDot != -1)
timezoneLiteral = timezoneLiteral.substring(0, indexOfDot);
newSql.append(timezoneLiteral);
}
if (serverSupportsFractionalSecond)
newSql.append(fractionalSecond);
newSql.append("'");
} catch (NumberFormatException nfe) {
throw SQLError.createSQLException("Syntax error in TIMESTAMP escape sequence '" + token + "'.", "S1009", conn.getExceptionInterceptor());
}
}
} catch (NoSuchElementException e) {
throw SQLError.createSQLException("Syntax error for TIMESTAMP escape sequence '" + argument + "'", "42000", conn.getExceptionInterceptor());
}
}
} catch (IllegalArgumentException illegalArgumentException) {
SQLException sqlEx = SQLError.createSQLException("Syntax error for TIMESTAMP escape sequence '" + argument + "'", "42000", conn.getExceptionInterceptor());
sqlEx.initCause(illegalArgumentException);
throw sqlEx;
}
}
}
private static String processConvertToken(String functionToken, boolean serverSupportsConvertFn, MySQLConnection conn) throws SQLException {
int firstIndexOfParen = functionToken.indexOf("(");
if (firstIndexOfParen == -1)
throw SQLError.createSQLException("Syntax error while processing {fn convert (... , ...)} token, missing opening parenthesis in token '" + functionToken + "'.", "42000", conn.getExceptionInterceptor());
int indexOfComma = functionToken.lastIndexOf(",");
if (indexOfComma == -1)
throw SQLError.createSQLException("Syntax error while processing {fn convert (... , ...)} token, missing comma in token '" + functionToken + "'.", "42000", conn.getExceptionInterceptor());
int indexOfCloseParen = functionToken.indexOf(')', indexOfComma);
if (indexOfCloseParen == -1)
throw SQLError.createSQLException("Syntax error while processing {fn convert (... , ...)} token, missing closing parenthesis in token '" + functionToken + "'.", "42000", conn.getExceptionInterceptor());
String expression = functionToken.substring(firstIndexOfParen + 1, indexOfComma);
String type = functionToken.substring(indexOfComma + 1, indexOfCloseParen);
String newType = null;
String trimmedType = type.trim();
if (StringUtils.startsWithIgnoreCase(trimmedType, "SQL_"))
trimmedType = trimmedType.substring(4, trimmedType.length());
if (serverSupportsConvertFn) {
newType = JDBC_CONVERT_TO_MYSQL_TYPE_MAP.get(trimmedType.toUpperCase(Locale.ENGLISH));
} else {
newType = JDBC_NO_CONVERT_TO_MYSQL_EXPRESSION_MAP.get(trimmedType.toUpperCase(Locale.ENGLISH));
if (newType == null)
throw SQLError.createSQLException("Can't find conversion re-write for type '" + type + "' that is applicable for this server version while processing escape tokens.", "S1000", conn.getExceptionInterceptor());
}
if (newType == null)
throw SQLError.createSQLException("Unsupported conversion type '" + type.trim() + "' found while processing escape token.", "S1000", conn.getExceptionInterceptor());
int replaceIndex = newType.indexOf("?");
if (replaceIndex != -1) {
StringBuffer convertRewrite = new StringBuffer(newType.substring(0, replaceIndex));
convertRewrite.append(expression);
convertRewrite.append(newType.substring(replaceIndex + 1, newType.length()));
return convertRewrite.toString();
}
StringBuffer castRewrite = new StringBuffer("CAST(");
castRewrite.append(expression);
castRewrite.append(" AS ");
castRewrite.append(newType);
castRewrite.append(")");
return castRewrite.toString();
}
private static String removeWhitespace(String toCollapse) {
if (toCollapse == null)
return null;
int length = toCollapse.length();
StringBuffer collapsed = new StringBuffer(length);
for (int i = 0; i < length; i++) {
char c = toCollapse.charAt(i);
if (!Character.isWhitespace(c))
collapsed.append(c);
}
return collapsed.toString();
}
}

View file

@ -0,0 +1,9 @@
package com.mysql.jdbc;
class EscapeProcessorResult {
boolean callingStoredFunction = false;
String escapedSql;
byte usesVariables = 0;
}

View file

@ -0,0 +1,126 @@
package com.mysql.jdbc;
public class EscapeTokenizer {
private static final char CHR_ESCAPE = '\\';
private static final char CHR_SGL_QUOTE = '\'';
private static final char CHR_DBL_QUOTE = '"';
private static final char CHR_LF = '\n';
private static final char CHR_CR = '\r';
private static final char CHR_COMMENT = '-';
private static final char CHR_BEGIN_TOKEN = '{';
private static final char CHR_END_TOKEN = '}';
private static final char CHR_VARIABLE = '@';
private String source = null;
private int sourceLength = 0;
private int pos = 0;
private boolean emittingEscapeCode = false;
private boolean sawVariableUse = false;
private int bracesLevel = 0;
private boolean inQuotes = false;
private char quoteChar = '\000';
public EscapeTokenizer(String source) {
this.source = source;
this.sourceLength = source.length();
this.pos = 0;
}
public synchronized boolean hasMoreTokens() {
return (this.pos < this.sourceLength);
}
public synchronized String nextToken() {
StringBuffer tokenBuf = new StringBuffer();
boolean backslashEscape = false;
if (this.emittingEscapeCode) {
tokenBuf.append("{");
this.emittingEscapeCode = false;
}
for (; this.pos < this.sourceLength; this.pos++) {
char c = this.source.charAt(this.pos);
if (c == '\\') {
tokenBuf.append(c);
backslashEscape = !backslashEscape;
continue;
}
if ((c == '\'' || c == '"') && !backslashEscape) {
tokenBuf.append(c);
if (this.inQuotes) {
if (c == this.quoteChar)
if (this.pos + 1 < this.sourceLength && this.source.charAt(this.pos + 1) == this.quoteChar) {
tokenBuf.append(c);
this.pos++;
} else {
this.inQuotes = false;
}
} else {
this.inQuotes = true;
this.quoteChar = c;
}
continue;
}
if (c == '\n' || c == '\r') {
tokenBuf.append(c);
backslashEscape = false;
continue;
}
if (!this.inQuotes && !backslashEscape) {
if (c == '-') {
tokenBuf.append(c);
if (this.pos + 1 < this.sourceLength && this.source.charAt(this.pos + 1) == '-') {
while (++this.pos < this.sourceLength && c != '\n' && c != '\r') {
c = this.source.charAt(this.pos);
tokenBuf.append(c);
}
this.pos--;
}
continue;
}
if (c == '{') {
this.bracesLevel++;
if (this.bracesLevel == 1) {
this.emittingEscapeCode = true;
this.pos++;
return tokenBuf.toString();
}
tokenBuf.append(c);
continue;
}
if (c == '}') {
tokenBuf.append(c);
this.bracesLevel--;
if (this.bracesLevel == 0) {
this.pos++;
return tokenBuf.toString();
}
continue;
}
if (c == '@')
this.sawVariableUse = true;
}
tokenBuf.append(c);
backslashEscape = false;
}
return tokenBuf.toString();
}
boolean sawVariableUse() {
return this.sawVariableUse;
}
}

View file

@ -0,0 +1,7 @@
package com.mysql.jdbc;
import java.sql.SQLException;
public interface ExceptionInterceptor extends Extension {
SQLException interceptException(SQLException paramSQLException, Connection paramConnection);
}

View file

@ -0,0 +1,216 @@
package com.mysql.jdbc;
import com.mysql.jdbc.util.Base64Decoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.security.KeyFactory;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.sql.SQLException;
import java.util.Properties;
import javax.crypto.Cipher;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class ExportControlled {
private static final String SQL_STATE_BAD_SSL_PARAMS = "08000";
protected static boolean enabled() {
return true;
}
protected static void transformSocketToSSLSocket(MysqlIO mysqlIO) throws SQLException {
SocketFactory sslFact = new StandardSSLSocketFactory(getSSLSocketFactoryDefaultOrConfigured(mysqlIO), mysqlIO.socketFactory, mysqlIO.mysqlConnection);
try {
mysqlIO.mysqlConnection = sslFact.connect(mysqlIO.host, mysqlIO.port, null);
((SSLSocket)mysqlIO.mysqlConnection).setEnabledProtocols(new String[] { "TLSv1" });
((SSLSocket)mysqlIO.mysqlConnection).startHandshake();
if (mysqlIO.connection.getUseUnbufferedInput()) {
mysqlIO.mysqlInput = mysqlIO.mysqlConnection.getInputStream();
} else {
mysqlIO.mysqlInput = new BufferedInputStream(mysqlIO.mysqlConnection.getInputStream(), 16384);
}
mysqlIO.mysqlOutput = new BufferedOutputStream(mysqlIO.mysqlConnection.getOutputStream(), 16384);
mysqlIO.mysqlOutput.flush();
mysqlIO.socketFactory = sslFact;
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(mysqlIO.connection, mysqlIO.getLastPacketSentTimeMs(), mysqlIO.getLastPacketReceivedTimeMs(), ioEx, mysqlIO.getExceptionInterceptor());
}
}
public static class StandardSSLSocketFactory implements SocketFactory {
private SSLSocket rawSocket = null;
private final SSLSocketFactory sslFact;
private final SocketFactory existingSocketFactory;
private final Socket existingSocket;
public StandardSSLSocketFactory(SSLSocketFactory sslFact, SocketFactory existingSocketFactory, Socket existingSocket) {
this.sslFact = sslFact;
this.existingSocketFactory = existingSocketFactory;
this.existingSocket = existingSocket;
}
public Socket afterHandshake() throws SocketException, IOException {
this.existingSocketFactory.afterHandshake();
return this.rawSocket;
}
public Socket beforeHandshake() throws SocketException, IOException {
return this.rawSocket;
}
public Socket connect(String host, int portNumber, Properties props) throws SocketException, IOException {
this.rawSocket = (SSLSocket)this.sslFact.createSocket(this.existingSocket, host, portNumber, true);
return this.rawSocket;
}
}
private static SSLSocketFactory getSSLSocketFactoryDefaultOrConfigured(MysqlIO mysqlIO) throws SQLException {
String clientCertificateKeyStoreUrl = mysqlIO.connection.getClientCertificateKeyStoreUrl();
String trustCertificateKeyStoreUrl = mysqlIO.connection.getTrustCertificateKeyStoreUrl();
String clientCertificateKeyStoreType = mysqlIO.connection.getClientCertificateKeyStoreType();
String clientCertificateKeyStorePassword = mysqlIO.connection.getClientCertificateKeyStorePassword();
String trustCertificateKeyStoreType = mysqlIO.connection.getTrustCertificateKeyStoreType();
String trustCertificateKeyStorePassword = mysqlIO.connection.getTrustCertificateKeyStorePassword();
if (StringUtils.isNullOrEmpty(clientCertificateKeyStoreUrl) && StringUtils.isNullOrEmpty(trustCertificateKeyStoreUrl))
if (mysqlIO.connection.getVerifyServerCertificate())
return (SSLSocketFactory)SSLSocketFactory.getDefault();
TrustManagerFactory tmf = null;
KeyManagerFactory kmf = null;
try {
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw SQLError.createSQLException("Default algorithm definitions for TrustManager and/or KeyManager are invalid. Check java security properties file.", "08000", 0, false, mysqlIO.getExceptionInterceptor());
}
if (!StringUtils.isNullOrEmpty(clientCertificateKeyStoreUrl)) {
InputStream ksIS = null;
try {
if (!StringUtils.isNullOrEmpty(clientCertificateKeyStoreType)) {
KeyStore clientKeyStore = KeyStore.getInstance(clientCertificateKeyStoreType);
URL ksURL = new URL(clientCertificateKeyStoreUrl);
char[] password = (clientCertificateKeyStorePassword == null) ? new char[0] : clientCertificateKeyStorePassword.toCharArray();
ksIS = ksURL.openStream();
clientKeyStore.load(ksIS, password);
kmf.init(clientKeyStore, password);
}
} catch (UnrecoverableKeyException uke) {
throw SQLError.createSQLException("Could not recover keys from client keystore. Check password?", "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (NoSuchAlgorithmException nsae) {
throw SQLError.createSQLException("Unsupported keystore algorithm [" + nsae.getMessage() + "]", "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (KeyStoreException kse) {
throw SQLError.createSQLException("Could not create KeyStore instance [" + kse.getMessage() + "]", "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (CertificateException nsae) {
throw SQLError.createSQLException("Could not load client" + clientCertificateKeyStoreType + " keystore from " + clientCertificateKeyStoreUrl, mysqlIO.getExceptionInterceptor());
} catch (MalformedURLException mue) {
throw SQLError.createSQLException(clientCertificateKeyStoreUrl + " does not appear to be a valid URL.", "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (IOException ioe) {
SQLException sqlEx = SQLError.createSQLException("Cannot open " + clientCertificateKeyStoreUrl + " [" + ioe.getMessage() + "]", "08000", 0, false, mysqlIO.getExceptionInterceptor());
sqlEx.initCause(ioe);
throw sqlEx;
} finally {
if (ksIS != null)
try {
ksIS.close();
} catch (IOException e) {}
}
}
if (!StringUtils.isNullOrEmpty(trustCertificateKeyStoreUrl)) {
InputStream ksIS = null;
try {
if (!StringUtils.isNullOrEmpty(trustCertificateKeyStoreType)) {
KeyStore trustKeyStore = KeyStore.getInstance(trustCertificateKeyStoreType);
URL ksURL = new URL(trustCertificateKeyStoreUrl);
char[] password = (trustCertificateKeyStorePassword == null) ? new char[0] : trustCertificateKeyStorePassword.toCharArray();
ksIS = ksURL.openStream();
trustKeyStore.load(ksIS, password);
tmf.init(trustKeyStore);
}
} catch (NoSuchAlgorithmException nsae) {
throw SQLError.createSQLException("Unsupported keystore algorithm [" + nsae.getMessage() + "]", "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (KeyStoreException kse) {
throw SQLError.createSQLException("Could not create KeyStore instance [" + kse.getMessage() + "]", "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (CertificateException nsae) {
throw SQLError.createSQLException("Could not load trust" + trustCertificateKeyStoreType + " keystore from " + trustCertificateKeyStoreUrl, "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (MalformedURLException mue) {
throw SQLError.createSQLException(trustCertificateKeyStoreUrl + " does not appear to be a valid URL.", "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (IOException ioe) {
SQLException sqlEx = SQLError.createSQLException("Cannot open " + trustCertificateKeyStoreUrl + " [" + ioe.getMessage() + "]", "08000", 0, false, mysqlIO.getExceptionInterceptor());
sqlEx.initCause(ioe);
throw sqlEx;
} finally {
if (ksIS != null)
try {
ksIS.close();
} catch (IOException e) {}
}
}
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(StringUtils.isNullOrEmpty(clientCertificateKeyStoreUrl) ? null : kmf.getKeyManagers(), mysqlIO.connection.getVerifyServerCertificate() ? tmf.getTrustManagers() : new X509TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}, }, null);
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException nsae) {
throw SQLError.createSQLException("TLS is not a valid SSL protocol.", "08000", 0, false, mysqlIO.getExceptionInterceptor());
} catch (KeyManagementException kme) {
throw SQLError.createSQLException("KeyManagementException: " + kme.getMessage(), "08000", 0, false, mysqlIO.getExceptionInterceptor());
}
}
public static boolean isSSLEstablished(MysqlIO mysqlIO) {
return SSLSocket.class.isAssignableFrom(mysqlIO.mysqlConnection.getClass());
}
public static RSAPublicKey decodeRSAPublicKey(String key, ExceptionInterceptor interceptor) throws SQLException {
try {
if (key == null)
throw new SQLException("key parameter is null");
int offset = key.indexOf("\n") + 1;
int len = key.indexOf("-----END PUBLIC KEY-----") - offset;
byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len);
X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey)kf.generatePublic(spec);
} catch (Exception ex) {
throw SQLError.createSQLException("Unable to decode public key", "S1009", ex, interceptor);
}
}
public static byte[] encryptWithRSAPublicKey(byte[] source, RSAPublicKey key, ExceptionInterceptor interceptor) throws SQLException {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
cipher.init(1, key);
return cipher.doFinal(source);
} catch (Exception ex) {
throw SQLError.createSQLException(ex.getMessage(), "S1009", ex, interceptor);
}
}
}

View file

@ -0,0 +1,10 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.Properties;
public interface Extension {
void init(Connection paramConnection, Properties paramProperties) throws SQLException;
void destroy();
}

View file

@ -0,0 +1,165 @@
package com.mysql.jdbc;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class FailoverConnectionProxy extends LoadBalancingConnectionProxy {
boolean failedOver;
boolean hasTriedMaster;
private long masterFailTimeMillis;
boolean preferSlaveDuringFailover;
private String primaryHostPortSpec;
private long queriesBeforeRetryMaster;
long queriesIssuedFailedOver;
private int secondsBeforeRetryMaster;
class FailoverInvocationHandler extends LoadBalancingConnectionProxy.ConnectionErrorFiringInvocationHandler {
public FailoverInvocationHandler(Object toInvokeOn) {
super(toInvokeOn);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if (FailoverConnectionProxy.this.failedOver && methodName.indexOf("execute") != -1)
FailoverConnectionProxy.this.queriesIssuedFailedOver++;
return super.invoke(proxy, method, args);
}
}
FailoverConnectionProxy(List<String> hosts, Properties props) throws SQLException {
super(hosts, props);
ConnectionPropertiesImpl connectionProps = new ConnectionPropertiesImpl();
connectionProps.initializeProperties(props);
this.queriesBeforeRetryMaster = (long)connectionProps.getQueriesBeforeRetryMaster();
this.secondsBeforeRetryMaster = connectionProps.getSecondsBeforeRetryMaster();
this.preferSlaveDuringFailover = false;
}
protected LoadBalancingConnectionProxy.ConnectionErrorFiringInvocationHandler createConnectionProxy(Object toProxy) {
return new FailoverInvocationHandler(toProxy);
}
synchronized void dealWithInvocationException(InvocationTargetException e) throws SQLException, Throwable, InvocationTargetException {
Throwable t = e.getTargetException();
if (t != null) {
if (this.failedOver) {
createPrimaryConnection();
if (this.currentConn != null)
throw t;
}
failOver();
throw t;
}
throw e;
}
public synchronized Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if ("setPreferSlaveDuringFailover".equals(methodName)) {
this.preferSlaveDuringFailover = (Boolean)args[0];
} else if ("clearHasTriedMaster".equals(methodName)) {
this.hasTriedMaster = false;
} else {
if ("hasTriedMaster".equals(methodName))
return this.hasTriedMaster;
if ("isMasterConnection".equals(methodName))
return !this.failedOver;
if ("isSlaveConnection".equals(methodName))
return this.failedOver;
if ("setReadOnly".equals(methodName)) {
if (this.failedOver)
return null;
} else {
if ("setAutoCommit".equals(methodName) && this.failedOver && shouldFallBack() && Boolean.TRUE.equals(args[0]) && this.failedOver) {
createPrimaryConnection();
return invoke(proxy, method, args, this.failedOver);
}
if ("hashCode".equals(methodName))
return hashCode();
if ("equals".equals(methodName)) {
if (args[0] instanceof Proxy)
return ((Proxy)args[0]).equals(this);
return equals(args[0]);
}
}
}
return invoke(proxy, method, args, this.failedOver);
}
private synchronized void createPrimaryConnection() throws SQLException {
try {
this.currentConn = createConnectionForHost(this.primaryHostPortSpec);
this.failedOver = false;
this.hasTriedMaster = true;
this.queriesIssuedFailedOver = 0L;
} catch (SQLException sqlEx) {
this.failedOver = true;
if (this.currentConn != null)
this.currentConn.getLog().logWarn("Connection to primary host failed", sqlEx);
}
}
synchronized void invalidateCurrentConnection() throws SQLException {
if (!this.failedOver) {
this.failedOver = true;
this.queriesIssuedFailedOver = 0L;
this.masterFailTimeMillis = System.currentTimeMillis();
}
super.invalidateCurrentConnection();
}
protected synchronized void pickNewConnection() throws SQLException {
if (this.isClosed && this.closedExplicitly)
return;
if (this.primaryHostPortSpec == null)
this.primaryHostPortSpec = (String)this.hostList.remove(0);
if (this.currentConn == null || (this.failedOver && shouldFallBack())) {
createPrimaryConnection();
if (this.currentConn != null)
return;
}
failOver();
}
private synchronized void failOver() throws SQLException {
if (this.failedOver) {
Iterator<Map.Entry<String, ConnectionImpl>> iter = this.liveConnections.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, ConnectionImpl> entry = iter.next();
entry.getValue().close();
}
this.liveConnections.clear();
}
super.pickNewConnection();
if (this.currentConn.getFailOverReadOnly()) {
this.currentConn.setReadOnly(true);
} else {
this.currentConn.setReadOnly(false);
}
this.failedOver = true;
}
private boolean shouldFallBack() {
long secondsSinceFailedOver = (System.currentTimeMillis() - this.masterFailTimeMillis) / 1000L;
if (secondsSinceFailedOver >= (long)this.secondsBeforeRetryMaster) {
this.masterFailTimeMillis = System.currentTimeMillis();
return true;
}
if (this.queriesBeforeRetryMaster != 0L && this.queriesIssuedFailedOver >= this.queriesBeforeRetryMaster)
return true;
return false;
}
}

View file

@ -0,0 +1,644 @@
package com.mysql.jdbc;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.PatternSyntaxException;
public class Field {
private static final int AUTO_INCREMENT_FLAG = 512;
private static final int NO_CHARSET_INFO = -1;
private byte[] buffer;
private int collationIndex = 0;
private String encoding = null;
private int colDecimals;
private short colFlag;
private String collationName = null;
private MySQLConnection connection = null;
private String databaseName = null;
private int databaseNameLength = -1;
private int databaseNameStart = -1;
protected int defaultValueLength = -1;
protected int defaultValueStart = -1;
private String fullName = null;
private String fullOriginalName = null;
private boolean isImplicitTempTable = false;
private long length;
private int mysqlType = -1;
private String name;
private int nameLength;
private int nameStart;
private String originalColumnName = null;
private int originalColumnNameLength = -1;
private int originalColumnNameStart = -1;
private String originalTableName = null;
private int originalTableNameLength = -1;
private int originalTableNameStart = -1;
private int precisionAdjustFactor = 0;
private int sqlType = -1;
private String tableName;
private int tableNameLength;
private int tableNameStart;
private boolean useOldNameMetadata = false;
private boolean isSingleBit;
private int maxBytesPerChar;
private final boolean valueNeedsQuoting;
Field(MySQLConnection conn, byte[] buffer, int databaseNameStart, int databaseNameLength, int tableNameStart, int tableNameLength, int originalTableNameStart, int originalTableNameLength, int nameStart, int nameLength, int originalColumnNameStart, int originalColumnNameLength, long length, int mysqlType, short colFlag, int colDecimals, int defaultValueStart, int defaultValueLength, int charsetIndex) throws SQLException {
this.connection = conn;
this.buffer = buffer;
this.nameStart = nameStart;
this.nameLength = nameLength;
this.tableNameStart = tableNameStart;
this.tableNameLength = tableNameLength;
this.length = length;
this.colFlag = colFlag;
this.colDecimals = colDecimals;
this.mysqlType = mysqlType;
this.databaseNameStart = databaseNameStart;
this.databaseNameLength = databaseNameLength;
this.originalTableNameStart = originalTableNameStart;
this.originalTableNameLength = originalTableNameLength;
this.originalColumnNameStart = originalColumnNameStart;
this.originalColumnNameLength = originalColumnNameLength;
this.defaultValueStart = defaultValueStart;
this.defaultValueLength = defaultValueLength;
this.collationIndex = charsetIndex;
this.sqlType = MysqlDefs.mysqlToJavaType(this.mysqlType);
checkForImplicitTemporaryTable();
boolean isFromFunction = (this.originalTableNameLength == 0);
if (this.mysqlType == 252)
if ((this.connection != null && this.connection.getBlobsAreStrings()) || (this.connection.getFunctionsNeverReturnBlobs() && isFromFunction)) {
this.sqlType = 12;
this.mysqlType = 15;
} else if (this.collationIndex == 63 || !this.connection.versionMeetsMinimum(4, 1, 0)) {
if (this.connection.getUseBlobToStoreUTF8OutsideBMP() && shouldSetupForUtf8StringInBlob()) {
setupForUtf8StringInBlob();
} else {
setBlobTypeBasedOnLength();
this.sqlType = MysqlDefs.mysqlToJavaType(this.mysqlType);
}
} else {
this.mysqlType = 253;
this.sqlType = -1;
}
if (this.sqlType == -6 && this.length == 1L && this.connection.getTinyInt1isBit())
if (conn.getTinyInt1isBit())
if (conn.getTransformedBitIsBoolean()) {
this.sqlType = 16;
} else {
this.sqlType = -7;
}
if (!isNativeNumericType() && !isNativeDateTimeType()) {
this.encoding = this.connection.getEncodingForIndex(this.collationIndex);
if ("UnicodeBig".equals(this.encoding))
this.encoding = "UTF-16";
boolean isBinary = isBinary();
if (this.connection.versionMeetsMinimum(4, 1, 0) && this.mysqlType == 253 && isBinary && this.collationIndex == 63)
if (this.connection != null && this.connection.getFunctionsNeverReturnBlobs() && isFromFunction) {
this.sqlType = 12;
this.mysqlType = 15;
} else if (isOpaqueBinary()) {
this.sqlType = -3;
}
if (this.connection.versionMeetsMinimum(4, 1, 0) && this.mysqlType == 254 && isBinary && this.collationIndex == 63)
if (isOpaqueBinary() && !this.connection.getBlobsAreStrings())
this.sqlType = -2;
if (this.mysqlType == 16) {
this.isSingleBit = (this.length == 0L);
if (this.connection != null && (this.connection.versionMeetsMinimum(5, 0, 21) || this.connection.versionMeetsMinimum(5, 1, 10)) && this.length == 1L)
this.isSingleBit = true;
if (this.isSingleBit) {
this.sqlType = -7;
} else {
this.sqlType = -3;
this.colFlag = (short)(this.colFlag | 0x80);
this.colFlag = (short)(this.colFlag | 0x10);
isBinary = true;
}
}
if (this.sqlType == -4 && !isBinary) {
this.sqlType = -1;
} else if (this.sqlType == -3 && !isBinary) {
this.sqlType = 12;
}
} else {
this.encoding = "US-ASCII";
}
if (!isUnsigned()) {
switch (this.mysqlType) {
case 0:
case 246:
this.precisionAdjustFactor = -1;
break;
case 4:
case 5:
this.precisionAdjustFactor = 1;
break;
}
} else {
switch (this.mysqlType) {
case 4:
case 5:
this.precisionAdjustFactor = 1;
break;
}
}
this.valueNeedsQuoting = determineNeedsQuoting();
}
private boolean shouldSetupForUtf8StringInBlob() throws SQLException {
String includePattern = this.connection.getUtf8OutsideBmpIncludedColumnNamePattern();
String excludePattern = this.connection.getUtf8OutsideBmpExcludedColumnNamePattern();
if (excludePattern != null && !StringUtils.isEmptyOrWhitespaceOnly(excludePattern))
try {
if (getOriginalName().matches(excludePattern)) {
if (includePattern != null && !StringUtils.isEmptyOrWhitespaceOnly(includePattern))
try {
if (getOriginalName().matches(includePattern))
return true;
} catch (PatternSyntaxException pse) {
SQLException sqlEx = SQLError.createSQLException("Illegal regex specified for \"utf8OutsideBmpIncludedColumnNamePattern\"", "S1009", this.connection.getExceptionInterceptor());
if (!this.connection.getParanoid())
sqlEx.initCause(pse);
throw sqlEx;
}
return false;
}
} catch (PatternSyntaxException pse) {
SQLException sqlEx = SQLError.createSQLException("Illegal regex specified for \"utf8OutsideBmpExcludedColumnNamePattern\"", "S1009", this.connection.getExceptionInterceptor());
if (!this.connection.getParanoid())
sqlEx.initCause(pse);
throw sqlEx;
}
return true;
}
private void setupForUtf8StringInBlob() {
if (this.length == 255L || this.length == 65535L) {
this.mysqlType = 15;
this.sqlType = 12;
} else {
this.mysqlType = 253;
this.sqlType = -1;
}
this.collationIndex = 33;
}
Field(MySQLConnection conn, byte[] buffer, int nameStart, int nameLength, int tableNameStart, int tableNameLength, int length, int mysqlType, short colFlag, int colDecimals) throws SQLException {
this(conn, buffer, -1, -1, tableNameStart, tableNameLength, -1, -1, nameStart, nameLength, -1, -1, (long)length, mysqlType, colFlag, colDecimals, -1, -1, -1);
}
Field(String tableName, String columnName, int jdbcType, int length) {
this.tableName = tableName;
this.name = columnName;
this.length = (long)length;
this.sqlType = jdbcType;
this.colFlag = 0;
this.colDecimals = 0;
this.valueNeedsQuoting = determineNeedsQuoting();
}
Field(String tableName, String columnName, int charsetIndex, int jdbcType, int length) {
this.tableName = tableName;
this.name = columnName;
this.length = (long)length;
this.sqlType = jdbcType;
this.colFlag = 0;
this.colDecimals = 0;
this.collationIndex = charsetIndex;
this.valueNeedsQuoting = determineNeedsQuoting();
switch (this.sqlType) {
case -3:
case -2:
this.colFlag = (short)(this.colFlag | 0x80);
this.colFlag = (short)(this.colFlag | 0x10);
break;
}
}
private void checkForImplicitTemporaryTable() {
this.isImplicitTempTable = (this.tableNameLength > 5 && this.buffer[this.tableNameStart] == 35 && this.buffer[this.tableNameStart + 1] == 115 && this.buffer[this.tableNameStart + 2] == 113 && this.buffer[this.tableNameStart + 3] == 108 && this.buffer[this.tableNameStart + 4] == 95);
}
public String getEncoding() throws SQLException {
return this.encoding;
}
public void setEncoding(String javaEncodingName, Connection conn) throws SQLException {
this.encoding = javaEncodingName;
try {
this.collationIndex = CharsetMapping.getCollationIndexForJavaEncoding(javaEncodingName, conn);
} catch (RuntimeException ex) {
SQLException sqlEx = SQLError.createSQLException(ex.toString(), "S1009", null);
sqlEx.initCause(ex);
throw sqlEx;
}
}
public synchronized String getCollation() throws SQLException {
if (this.collationName == null &&
this.connection != null &&
this.connection.versionMeetsMinimum(4, 1, 0))
if (this.connection.getUseDynamicCharsetInfo()) {
java.sql.DatabaseMetaData dbmd = this.connection.getMetaData();
String quotedIdStr = dbmd.getIdentifierQuoteString();
if (" ".equals(quotedIdStr))
quotedIdStr = "";
String csCatalogName = getDatabaseName();
String csTableName = getOriginalTableName();
String csColumnName = getOriginalName();
if (csCatalogName != null && csCatalogName.length() != 0 && csTableName != null && csTableName.length() != 0 && csColumnName != null && csColumnName.length() != 0) {
StringBuffer queryBuf = new StringBuffer(csCatalogName.length() + csTableName.length() + 28);
queryBuf.append("SHOW FULL COLUMNS FROM ");
queryBuf.append(quotedIdStr);
queryBuf.append(csCatalogName);
queryBuf.append(quotedIdStr);
queryBuf.append(".");
queryBuf.append(quotedIdStr);
queryBuf.append(csTableName);
queryBuf.append(quotedIdStr);
java.sql.Statement collationStmt = null;
ResultSet collationRs = null;
try {
collationStmt = this.connection.createStatement();
collationRs = collationStmt.executeQuery(queryBuf.toString());
while (collationRs.next()) {
if (csColumnName.equals(collationRs.getString("Field"))) {
this.collationName = collationRs.getString("Collation");
break;
}
}
} finally {
if (collationRs != null) {
collationRs.close();
collationRs = null;
}
if (collationStmt != null) {
collationStmt.close();
collationStmt = null;
}
}
}
} else {
try {
this.collationName = CharsetMapping.COLLATION_INDEX_TO_COLLATION_NAME[this.collationIndex];
} catch (RuntimeException ex) {
SQLException sqlEx = SQLError.createSQLException(ex.toString(), "S1009", null);
sqlEx.initCause(ex);
throw sqlEx;
}
}
return this.collationName;
}
public String getColumnLabel() throws SQLException {
return getName();
}
public String getDatabaseName() throws SQLException {
if (this.databaseName == null && this.databaseNameStart != -1 && this.databaseNameLength != -1)
this.databaseName = getStringFromBytes(this.databaseNameStart, this.databaseNameLength);
return this.databaseName;
}
int getDecimals() {
return this.colDecimals;
}
public String getFullName() throws SQLException {
if (this.fullName == null) {
StringBuffer fullNameBuf = new StringBuffer(getTableName().length() + 1 + getName().length());
fullNameBuf.append(this.tableName);
fullNameBuf.append('.');
fullNameBuf.append(this.name);
this.fullName = fullNameBuf.toString();
fullNameBuf = null;
}
return this.fullName;
}
public String getFullOriginalName() throws SQLException {
getOriginalName();
if (this.originalColumnName == null)
return null;
if (this.fullName == null) {
StringBuffer fullOriginalNameBuf = new StringBuffer(getOriginalTableName().length() + 1 + getOriginalName().length());
fullOriginalNameBuf.append(this.originalTableName);
fullOriginalNameBuf.append('.');
fullOriginalNameBuf.append(this.originalColumnName);
this.fullOriginalName = fullOriginalNameBuf.toString();
fullOriginalNameBuf = null;
}
return this.fullOriginalName;
}
public long getLength() {
return this.length;
}
public synchronized int getMaxBytesPerCharacter() throws SQLException {
if (this.maxBytesPerChar == 0)
this.maxBytesPerChar = this.connection.getMaxBytesPerChar(Integer.valueOf(this.collationIndex), getEncoding());
return this.maxBytesPerChar;
}
public int getMysqlType() {
return this.mysqlType;
}
public String getName() throws SQLException {
if (this.name == null)
this.name = getStringFromBytes(this.nameStart, this.nameLength);
return this.name;
}
public String getNameNoAliases() throws SQLException {
if (this.useOldNameMetadata)
return getName();
if (this.connection != null && this.connection.versionMeetsMinimum(4, 1, 0))
return getOriginalName();
return getName();
}
public String getOriginalName() throws SQLException {
if (this.originalColumnName == null && this.originalColumnNameStart != -1 && this.originalColumnNameLength != -1)
this.originalColumnName = getStringFromBytes(this.originalColumnNameStart, this.originalColumnNameLength);
return this.originalColumnName;
}
public String getOriginalTableName() throws SQLException {
if (this.originalTableName == null && this.originalTableNameStart != -1 && this.originalTableNameLength != -1)
this.originalTableName = getStringFromBytes(this.originalTableNameStart, this.originalTableNameLength);
return this.originalTableName;
}
public int getPrecisionAdjustFactor() {
return this.precisionAdjustFactor;
}
public int getSQLType() {
return this.sqlType;
}
private String getStringFromBytes(int stringStart, int stringLength) throws SQLException {
if (stringStart == -1 || stringLength == -1)
return null;
String stringVal = null;
if (this.connection != null) {
if (this.connection.getUseUnicode()) {
String javaEncoding = this.connection.getCharacterSetMetadata();
if (javaEncoding == null)
javaEncoding = this.connection.getEncoding();
if (javaEncoding != null) {
SingleByteCharsetConverter converter = null;
if (this.connection != null)
converter = this.connection.getCharsetConverter(javaEncoding);
if (converter != null) {
stringVal = converter.toString(this.buffer, stringStart, stringLength);
} else {
try {
stringVal = StringUtils.toString(this.buffer, stringStart, stringLength, javaEncoding);
} catch (UnsupportedEncodingException ue) {
throw new RuntimeException(Messages.getString("Field.12") + javaEncoding + Messages.getString("Field.13"));
}
}
} else {
stringVal = StringUtils.toAsciiString(this.buffer, stringStart, stringLength);
}
} else {
stringVal = StringUtils.toAsciiString(this.buffer, stringStart, stringLength);
}
} else {
stringVal = StringUtils.toAsciiString(this.buffer, stringStart, stringLength);
}
return stringVal;
}
public String getTable() throws SQLException {
return getTableName();
}
public String getTableName() throws SQLException {
if (this.tableName == null)
this.tableName = getStringFromBytes(this.tableNameStart, this.tableNameLength);
return this.tableName;
}
public String getTableNameNoAliases() throws SQLException {
if (this.connection.versionMeetsMinimum(4, 1, 0))
return getOriginalTableName();
return getTableName();
}
public boolean isAutoIncrement() {
return ((this.colFlag & 0x200) > 0);
}
public boolean isBinary() {
return ((this.colFlag & 0x80) > 0);
}
public boolean isBlob() {
return ((this.colFlag & 0x10) > 0);
}
private boolean isImplicitTemporaryTable() {
return this.isImplicitTempTable;
}
public boolean isMultipleKey() {
return ((this.colFlag & 0x8) > 0);
}
boolean isNotNull() {
return ((this.colFlag & 0x1) > 0);
}
boolean isOpaqueBinary() throws SQLException {
if (this.collationIndex == 63 && isBinary() && (getMysqlType() == 254 || getMysqlType() == 253)) {
if (this.originalTableNameLength == 0 && this.connection != null && !this.connection.versionMeetsMinimum(5, 0, 25))
return false;
return !isImplicitTemporaryTable();
}
return (this.connection.versionMeetsMinimum(4, 1, 0) && "binary".equalsIgnoreCase(getEncoding()));
}
public boolean isPrimaryKey() {
return ((this.colFlag & 0x2) > 0);
}
boolean isReadOnly() throws SQLException {
if (this.connection.versionMeetsMinimum(4, 1, 0)) {
String orgColumnName = getOriginalName();
String orgTableName = getOriginalTableName();
return (orgColumnName == null || orgColumnName.length() <= 0 || orgTableName == null || orgTableName.length() <= 0);
}
return false;
}
public boolean isUniqueKey() {
return ((this.colFlag & 0x4) > 0);
}
public boolean isUnsigned() {
return ((this.colFlag & 0x20) > 0);
}
public void setUnsigned() {
this.colFlag = (short)(this.colFlag | 0x20);
}
public boolean isZeroFill() {
return ((this.colFlag & 0x40) > 0);
}
private void setBlobTypeBasedOnLength() {
if (this.length == 255L) {
this.mysqlType = 249;
} else if (this.length == 65535L) {
this.mysqlType = 252;
} else if (this.length == 16777215L) {
this.mysqlType = 250;
} else if (this.length == 4294967295L) {
this.mysqlType = 251;
}
}
private boolean isNativeNumericType() {
return ((this.mysqlType >= 1 && this.mysqlType <= 5) || this.mysqlType == 8 || this.mysqlType == 13);
}
private boolean isNativeDateTimeType() {
return (this.mysqlType == 10 || this.mysqlType == 14 || this.mysqlType == 12 || this.mysqlType == 11 || this.mysqlType == 7);
}
public void setConnection(MySQLConnection conn) {
this.connection = conn;
if (this.encoding == null || this.collationIndex == 0)
this.encoding = this.connection.getEncoding();
}
void setMysqlType(int type) {
this.mysqlType = type;
this.sqlType = MysqlDefs.mysqlToJavaType(this.mysqlType);
}
protected void setUseOldNameMetadata(boolean useOldNameMetadata) {
this.useOldNameMetadata = useOldNameMetadata;
}
public String toString() {
try {
StringBuffer asString = new StringBuffer();
asString.append(super.toString());
asString.append("[");
asString.append("catalog=");
asString.append(getDatabaseName());
asString.append(",tableName=");
asString.append(getTableName());
asString.append(",originalTableName=");
asString.append(getOriginalTableName());
asString.append(",columnName=");
asString.append(getName());
asString.append(",originalColumnName=");
asString.append(getOriginalName());
asString.append(",mysqlType=");
asString.append(getMysqlType());
asString.append("(");
asString.append(MysqlDefs.typeToName(getMysqlType()));
asString.append(")");
asString.append(",flags=");
if (isAutoIncrement())
asString.append(" AUTO_INCREMENT");
if (isPrimaryKey())
asString.append(" PRIMARY_KEY");
if (isUniqueKey())
asString.append(" UNIQUE_KEY");
if (isBinary())
asString.append(" BINARY");
if (isBlob())
asString.append(" BLOB");
if (isMultipleKey())
asString.append(" MULTI_KEY");
if (isUnsigned())
asString.append(" UNSIGNED");
if (isZeroFill())
asString.append(" ZEROFILL");
asString.append(", charsetIndex=");
asString.append(this.collationIndex);
asString.append(", charsetName=");
asString.append(this.encoding);
asString.append("]");
return asString.toString();
} catch (Throwable t) {
return super.toString();
}
}
protected boolean isSingleBit() {
return this.isSingleBit;
}
protected boolean getvalueNeedsQuoting() {
return this.valueNeedsQuoting;
}
private boolean determineNeedsQuoting() {
boolean retVal = false;
switch (this.sqlType) {
case -7:
case -6:
case -5:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
retVal = false;
break;
default:
retVal = true;
break;
}
return retVal;
}
}

View file

@ -0,0 +1,48 @@
package com.mysql.jdbc;
import java.sql.SQLException;
import java.util.Iterator;
public abstract class IterateBlock<T> {
DatabaseMetaData.IteratorWithCleanup<T> iteratorWithCleanup;
Iterator<T> javaIterator;
boolean stopIterating = false;
IterateBlock(DatabaseMetaData.IteratorWithCleanup<T> i) {
this.iteratorWithCleanup = i;
this.javaIterator = null;
}
IterateBlock(Iterator<T> i) {
this.javaIterator = i;
this.iteratorWithCleanup = null;
}
public void doForAll() throws SQLException {
if (this.iteratorWithCleanup != null) {
try {
while (this.iteratorWithCleanup.hasNext()) {
forEach(this.iteratorWithCleanup.next());
if (this.stopIterating)
break;
}
} finally {
this.iteratorWithCleanup.close();
}
} else {
while (this.javaIterator.hasNext()) {
forEach(this.javaIterator.next());
if (this.stopIterating)
break;
}
}
}
abstract void forEach(T paramT) throws SQLException;
public final boolean fullIteration() {
return !this.stopIterating;
}
}

View file

@ -0,0 +1,137 @@
package com.mysql.jdbc;
import java.io.Reader;
import java.sql.NClob;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
public class JDBC4CallableStatement extends CallableStatement {
public JDBC4CallableStatement(MySQLConnection conn, CallableStatement.CallableStatementParamInfo paramInfo) throws SQLException {
super(conn, paramInfo);
}
public JDBC4CallableStatement(MySQLConnection conn, String sql, String catalog, boolean isFunctionCall) throws SQLException {
super(conn, sql, catalog, isFunctionCall);
}
public void setRowId(int parameterIndex, RowId x) throws SQLException {
JDBC4PreparedStatementHelper.setRowId(this, parameterIndex, x);
}
public void setRowId(String parameterName, RowId x) throws SQLException {
JDBC4PreparedStatementHelper.setRowId(this, getNamedParamIndex(parameterName, false), x);
}
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
JDBC4PreparedStatementHelper.setSQLXML(this, parameterIndex, xmlObject);
}
public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException {
JDBC4PreparedStatementHelper.setSQLXML(this, getNamedParamIndex(parameterName, false), xmlObject);
}
public SQLXML getSQLXML(int parameterIndex) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(parameterIndex);
SQLXML retValue = ((JDBC4ResultSet)rs).getSQLXML(mapOutputParameterIndexToRsIndex(parameterIndex));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public SQLXML getSQLXML(String parameterName) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(0);
SQLXML retValue = ((JDBC4ResultSet)rs).getSQLXML(fixParameterName(parameterName));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public RowId getRowId(int parameterIndex) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(parameterIndex);
RowId retValue = ((JDBC4ResultSet)rs).getRowId(mapOutputParameterIndexToRsIndex(parameterIndex));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public RowId getRowId(String parameterName) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(0);
RowId retValue = ((JDBC4ResultSet)rs).getRowId(fixParameterName(parameterName));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public void setNClob(int parameterIndex, NClob value) throws SQLException {
JDBC4PreparedStatementHelper.setNClob(this, parameterIndex, value);
}
public void setNClob(String parameterName, NClob value) throws SQLException {
JDBC4PreparedStatementHelper.setNClob(this, getNamedParamIndex(parameterName, false), value);
}
public void setNClob(String parameterName, Reader reader) throws SQLException {
setNClob(getNamedParamIndex(parameterName, false), reader);
}
public void setNClob(String parameterName, Reader reader, long length) throws SQLException {
setNClob(getNamedParamIndex(parameterName, false), reader, length);
}
public void setNString(String parameterName, String value) throws SQLException {
setNString(getNamedParamIndex(parameterName, false), value);
}
public Reader getCharacterStream(int parameterIndex) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(parameterIndex);
Reader retValue = rs.getCharacterStream(mapOutputParameterIndexToRsIndex(parameterIndex));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public Reader getCharacterStream(String parameterName) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(0);
Reader retValue = rs.getCharacterStream(fixParameterName(parameterName));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public Reader getNCharacterStream(int parameterIndex) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(parameterIndex);
Reader retValue = ((JDBC4ResultSet)rs).getNCharacterStream(mapOutputParameterIndexToRsIndex(parameterIndex));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public Reader getNCharacterStream(String parameterName) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(0);
Reader retValue = ((JDBC4ResultSet)rs).getNCharacterStream(fixParameterName(parameterName));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public NClob getNClob(int parameterIndex) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(parameterIndex);
NClob retValue = ((JDBC4ResultSet)rs).getNClob(mapOutputParameterIndexToRsIndex(parameterIndex));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public NClob getNClob(String parameterName) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(0);
NClob retValue = ((JDBC4ResultSet)rs).getNClob(fixParameterName(parameterName));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public String getNString(int parameterIndex) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(parameterIndex);
String retValue = ((JDBC4ResultSet)rs).getNString(mapOutputParameterIndexToRsIndex(parameterIndex));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
public String getNString(String parameterName) throws SQLException {
ResultSetInternalMethods rs = getOutputParameters(0);
String retValue = ((JDBC4ResultSet)rs).getNString(fixParameterName(parameterName));
this.outputParamWasNull = rs.wasNull();
return retValue;
}
}

View file

@ -0,0 +1,19 @@
package com.mysql.jdbc;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.util.Properties;
public interface JDBC4ClientInfoProvider {
void initialize(java.sql.Connection paramConnection, Properties paramProperties) throws SQLException;
void destroy() throws SQLException;
Properties getClientInfo(java.sql.Connection paramConnection) throws SQLException;
String getClientInfo(java.sql.Connection paramConnection, String paramString) throws SQLException;
void setClientInfo(java.sql.Connection paramConnection, Properties paramProperties) throws SQLClientInfoException;
void setClientInfo(java.sql.Connection paramConnection, String paramString1, String paramString2) throws SQLClientInfoException;
}

View file

@ -0,0 +1,100 @@
package com.mysql.jdbc;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;
public class JDBC4ClientInfoProviderSP implements JDBC4ClientInfoProvider {
java.sql.PreparedStatement setClientInfoSp;
java.sql.PreparedStatement getClientInfoSp;
java.sql.PreparedStatement getClientInfoBulkSp;
public synchronized void initialize(java.sql.Connection conn, Properties configurationProps) throws SQLException {
String identifierQuote = conn.getMetaData().getIdentifierQuoteString();
String setClientInfoSpName = configurationProps.getProperty("clientInfoSetSPName", "setClientInfo");
String getClientInfoSpName = configurationProps.getProperty("clientInfoGetSPName", "getClientInfo");
String getClientInfoBulkSpName = configurationProps.getProperty("clientInfoGetBulkSPName", "getClientInfoBulk");
String clientInfoCatalog = configurationProps.getProperty("clientInfoCatalog", "");
String catalog = "".equals(clientInfoCatalog) ? conn.getCatalog() : clientInfoCatalog;
this.setClientInfoSp = ((Connection)conn).clientPrepareStatement("CALL " + identifierQuote + catalog + identifierQuote + "." + identifierQuote + setClientInfoSpName + identifierQuote + "(?, ?)");
this.getClientInfoSp = ((Connection)conn).clientPrepareStatement("CALL" + identifierQuote + catalog + identifierQuote + "." + identifierQuote + getClientInfoSpName + identifierQuote + "(?)");
this.getClientInfoBulkSp = ((Connection)conn).clientPrepareStatement("CALL " + identifierQuote + catalog + identifierQuote + "." + identifierQuote + getClientInfoBulkSpName + identifierQuote + "()");
}
public synchronized void destroy() throws SQLException {
if (this.setClientInfoSp != null) {
this.setClientInfoSp.close();
this.setClientInfoSp = null;
}
if (this.getClientInfoSp != null) {
this.getClientInfoSp.close();
this.getClientInfoSp = null;
}
if (this.getClientInfoBulkSp != null) {
this.getClientInfoBulkSp.close();
this.getClientInfoBulkSp = null;
}
}
public synchronized Properties getClientInfo(java.sql.Connection conn) throws SQLException {
ResultSet rs = null;
Properties props = new Properties();
try {
this.getClientInfoBulkSp.execute();
rs = this.getClientInfoBulkSp.getResultSet();
while (rs.next())
props.setProperty(rs.getString(1), rs.getString(2));
} finally {
if (rs != null)
rs.close();
}
return props;
}
public synchronized String getClientInfo(java.sql.Connection conn, String name) throws SQLException {
ResultSet rs = null;
String clientInfo = null;
try {
this.getClientInfoSp.setString(1, name);
this.getClientInfoSp.execute();
rs = this.getClientInfoSp.getResultSet();
if (rs.next())
clientInfo = rs.getString(1);
} finally {
if (rs != null)
rs.close();
}
return clientInfo;
}
public synchronized void setClientInfo(java.sql.Connection conn, Properties properties) throws SQLClientInfoException {
try {
Enumeration<?> propNames = properties.propertyNames();
while (propNames.hasMoreElements()) {
String name = (String)propNames.nextElement();
String value = properties.getProperty(name);
setClientInfo(conn, name, value);
}
} catch (SQLException sqlEx) {
SQLClientInfoException clientInfoEx = new SQLClientInfoException();
clientInfoEx.initCause(sqlEx);
throw clientInfoEx;
}
}
public synchronized void setClientInfo(java.sql.Connection conn, String name, String value) throws SQLClientInfoException {
try {
this.setClientInfoSp.setString(1, name);
this.setClientInfoSp.setString(2, value);
this.setClientInfoSp.execute();
} catch (SQLException sqlEx) {
SQLClientInfoException clientInfoEx = new SQLClientInfoException();
clientInfoEx.initCause(sqlEx);
throw clientInfoEx;
}
}
}

View file

@ -0,0 +1,57 @@
package com.mysql.jdbc;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
public class JDBC4CommentClientInfoProvider implements JDBC4ClientInfoProvider {
private Properties clientInfo;
public synchronized void initialize(java.sql.Connection conn, Properties configurationProps) throws SQLException {
this.clientInfo = new Properties();
}
public synchronized void destroy() throws SQLException {
this.clientInfo = null;
}
public synchronized Properties getClientInfo(java.sql.Connection conn) throws SQLException {
return this.clientInfo;
}
public synchronized String getClientInfo(java.sql.Connection conn, String name) throws SQLException {
return this.clientInfo.getProperty(name);
}
public synchronized void setClientInfo(java.sql.Connection conn, Properties properties) throws SQLClientInfoException {
this.clientInfo = new Properties();
Enumeration<?> propNames = properties.propertyNames();
while (propNames.hasMoreElements()) {
String name = (String)propNames.nextElement();
this.clientInfo.put(name, properties.getProperty(name));
}
setComment(conn);
}
public synchronized void setClientInfo(java.sql.Connection conn, String name, String value) throws SQLClientInfoException {
this.clientInfo.setProperty(name, value);
setComment(conn);
}
private synchronized void setComment(java.sql.Connection conn) {
StringBuffer commentBuf = new StringBuffer();
Iterator<Map.Entry<Object, Object>> elements = this.clientInfo.entrySet().iterator();
while (elements.hasNext()) {
if (commentBuf.length() > 0)
commentBuf.append(", ");
Map.Entry entry = elements.next();
commentBuf.append("" + entry.getKey());
commentBuf.append("=");
commentBuf.append("" + entry.getValue());
}
((Connection)conn).setStatementComment(commentBuf.toString());
}
}

View file

@ -0,0 +1,125 @@
package com.mysql.jdbc;
import java.sql.Array;
import java.sql.NClob;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Struct;
import java.util.Properties;
public class JDBC4Connection extends ConnectionImpl {
private JDBC4ClientInfoProvider infoProvider;
public JDBC4Connection(String hostToConnectTo, int portToConnectTo, Properties info, String databaseToConnectTo, String url) throws SQLException {
super(hostToConnectTo, portToConnectTo, info, databaseToConnectTo, url);
}
public SQLXML createSQLXML() throws SQLException {
return new JDBC4MysqlSQLXML(getExceptionInterceptor());
}
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
throw SQLError.notImplemented();
}
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
throw SQLError.notImplemented();
}
public Properties getClientInfo() throws SQLException {
return getClientInfoProviderImpl().getClientInfo(this);
}
public String getClientInfo(String name) throws SQLException {
return getClientInfoProviderImpl().getClientInfo(this, name);
}
public boolean isValid(int timeout) throws SQLException {
synchronized (getConnectionMutex()) {
if (isClosed())
return false;
try {
try {
pingInternal(false, timeout * 1000);
} catch (Throwable t) {
try {
abortInternal();
} catch (Throwable ignoreThrown) {}
return false;
}
} catch (Throwable t) {
return false;
}
return true;
}
}
public void setClientInfo(Properties properties) throws SQLClientInfoException {
try {
getClientInfoProviderImpl().setClientInfo(this, properties);
} catch (SQLClientInfoException ciEx) {
throw ciEx;
} catch (SQLException sqlEx) {
SQLClientInfoException clientInfoEx = new SQLClientInfoException();
clientInfoEx.initCause(sqlEx);
throw clientInfoEx;
}
}
public void setClientInfo(String name, String value) throws SQLClientInfoException {
try {
getClientInfoProviderImpl().setClientInfo(this, name, value);
} catch (SQLClientInfoException ciEx) {
throw ciEx;
} catch (SQLException sqlEx) {
SQLClientInfoException clientInfoEx = new SQLClientInfoException();
clientInfoEx.initCause(sqlEx);
throw clientInfoEx;
}
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
checkClosed();
return iface.isInstance(this);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), "S1009", getExceptionInterceptor());
}
}
public java.sql.Blob createBlob() {
return new Blob(getExceptionInterceptor());
}
public java.sql.Clob createClob() {
return new Clob(getExceptionInterceptor());
}
public NClob createNClob() {
return new JDBC4NClob(getExceptionInterceptor());
}
protected JDBC4ClientInfoProvider getClientInfoProviderImpl() throws SQLException {
synchronized (getConnectionMutex()) {
if (this.infoProvider == null) {
try {
try {
this.infoProvider = (JDBC4ClientInfoProvider)Util.getInstance(getClientInfoProvider(), new Class<?>[0], new Object[0], getExceptionInterceptor());
} catch (SQLException sqlEx) {
if (sqlEx.getCause() instanceof ClassCastException)
this.infoProvider = (JDBC4ClientInfoProvider)Util.getInstance("com.mysql.jdbc." + getClientInfoProvider(), new Class<?>[0], new Object[0], getExceptionInterceptor());
}
} catch (ClassCastException cce) {
throw SQLError.createSQLException(Messages.getString("JDBC4Connection.ClientInfoNotImplemented", new Object[] { getClientInfoProvider() }), "S1009", getExceptionInterceptor());
}
this.infoProvider.initialize(this, this.props);
}
return this.infoProvider;
}
}
}

View file

@ -0,0 +1,61 @@
package com.mysql.jdbc;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
public class JDBC4DatabaseMetaData extends DatabaseMetaData {
public JDBC4DatabaseMetaData(MySQLConnection connToSet, String databaseToSet) {
super(connToSet, databaseToSet);
}
public RowIdLifetime getRowIdLifetime() throws SQLException {
return RowIdLifetime.ROWID_UNSUPPORTED;
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), "S1009", this.conn.getExceptionInterceptor());
}
}
public boolean autoCommitFailureClosesAllResultSets() throws SQLException {
return false;
}
public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException {
Field[] fields = createProcedureColumnsFields();
return getProcedureOrFunctionColumns(fields, catalog, schemaPattern, procedureNamePattern, columnNamePattern, true, this.conn.getGetProceduresReturnsFunctions());
}
public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException {
Field[] fields = createFieldMetadataForGetProcedures();
return getProceduresAndOrFunctions(fields, catalog, schemaPattern, procedureNamePattern, true, this.conn.getGetProceduresReturnsFunctions());
}
protected int getJDBC4FunctionNoTableConstant() {
return 1;
}
protected int getColumnType(boolean isOutParam, boolean isInParam, boolean isReturnParam, boolean forGetFunctionColumns) {
return getProcedureOrFunctionColumnType(isOutParam, isInParam, isReturnParam, forGetFunctionColumns);
}
protected static int getProcedureOrFunctionColumnType(boolean isOutParam, boolean isInParam, boolean isReturnParam, boolean forGetFunctionColumns) {
if (isInParam && isOutParam)
return forGetFunctionColumns ? 2 : 2;
if (isInParam)
return forGetFunctionColumns ? 1 : 1;
if (isOutParam)
return forGetFunctionColumns ? 3 : 4;
if (isReturnParam)
return forGetFunctionColumns ? 4 : 5;
return forGetFunctionColumns ? 0 : 0;
}
}

View file

@ -0,0 +1,72 @@
package com.mysql.jdbc;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
public class JDBC4DatabaseMetaDataUsingInfoSchema extends DatabaseMetaDataUsingInfoSchema {
public JDBC4DatabaseMetaDataUsingInfoSchema(MySQLConnection connToSet, String databaseToSet) throws SQLException {
super(connToSet, databaseToSet);
}
public RowIdLifetime getRowIdLifetime() throws SQLException {
return RowIdLifetime.ROWID_UNSUPPORTED;
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), "S1009", this.conn.getExceptionInterceptor());
}
}
protected ResultSet getProcedureColumnsNoISParametersView(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException {
Field[] fields = createProcedureColumnsFields();
return getProcedureOrFunctionColumns(fields, catalog, schemaPattern, procedureNamePattern, columnNamePattern, true, this.conn.getGetProceduresReturnsFunctions());
}
protected String getRoutineTypeConditionForGetProcedures() {
return this.conn.getGetProceduresReturnsFunctions() ? "" : "ROUTINE_TYPE = 'PROCEDURE' AND ";
}
protected String getRoutineTypeConditionForGetProcedureColumns() {
return this.conn.getGetProceduresReturnsFunctions() ? "" : "ROUTINE_TYPE = 'PROCEDURE' AND ";
}
protected int getJDBC4FunctionConstant(DatabaseMetaDataUsingInfoSchema.JDBC4FunctionConstant constant) {
switch (constant) {
case FUNCTION_COLUMN_IN:
return 1;
case FUNCTION_COLUMN_INOUT:
return 2;
case FUNCTION_COLUMN_OUT:
return 3;
case FUNCTION_COLUMN_RETURN:
return 4;
case FUNCTION_COLUMN_RESULT:
return 5;
case FUNCTION_COLUMN_UNKNOWN:
return 0;
case FUNCTION_NO_NULLS:
return 0;
case FUNCTION_NULLABLE:
return 1;
case FUNCTION_NULLABLE_UNKNOWN:
return 2;
}
return -1;
}
protected int getJDBC4FunctionNoTableConstant() {
return 1;
}
protected int getColumnType(boolean isOutParam, boolean isInParam, boolean isReturnParam, boolean forGetFunctionColumns) {
return JDBC4DatabaseMetaData.getProcedureOrFunctionColumnType(isOutParam, isInParam, isReturnParam, forGetFunctionColumns);
}
}

View file

@ -0,0 +1,84 @@
package com.mysql.jdbc;
import java.sql.Array;
import java.sql.NClob;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Struct;
import java.util.Properties;
public class JDBC4LoadBalancedMySQLConnection extends LoadBalancedMySQLConnection implements JDBC4MySQLConnection {
public JDBC4LoadBalancedMySQLConnection(LoadBalancingConnectionProxy proxy) throws SQLException {
super(proxy);
}
private JDBC4Connection getJDBC4Connection() {
return (JDBC4Connection)this.proxy.currentConn;
}
public SQLXML createSQLXML() throws SQLException {
return getJDBC4Connection().createSQLXML();
}
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return getJDBC4Connection().createArrayOf(typeName, elements);
}
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return getJDBC4Connection().createStruct(typeName, attributes);
}
public Properties getClientInfo() throws SQLException {
return getJDBC4Connection().getClientInfo();
}
public String getClientInfo(String name) throws SQLException {
return getJDBC4Connection().getClientInfo(name);
}
public boolean isValid(int timeout) throws SQLException {
synchronized (this.proxy) {
return getJDBC4Connection().isValid(timeout);
}
}
public void setClientInfo(Properties properties) throws SQLClientInfoException {
getJDBC4Connection().setClientInfo(properties);
}
public void setClientInfo(String name, String value) throws SQLClientInfoException {
getJDBC4Connection().setClientInfo(name, value);
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
checkClosed();
return iface.isInstance(this);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), "S1009", getExceptionInterceptor());
}
}
public java.sql.Blob createBlob() {
return getJDBC4Connection().createBlob();
}
public java.sql.Clob createClob() {
return getJDBC4Connection().createClob();
}
public NClob createNClob() {
return getJDBC4Connection().createNClob();
}
protected JDBC4ClientInfoProvider getClientInfoProviderImpl() throws SQLException {
synchronized (this.proxy) {
return getJDBC4Connection().getClientInfoProviderImpl();
}
}
}

View file

@ -0,0 +1,37 @@
package com.mysql.jdbc;
import java.sql.Array;
import java.sql.NClob;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Struct;
import java.util.Properties;
public interface JDBC4MySQLConnection extends MySQLConnection {
SQLXML createSQLXML() throws SQLException;
Array createArrayOf(String paramString, Object[] paramArrayOfObject) throws SQLException;
Struct createStruct(String paramString, Object[] paramArrayOfObject) throws SQLException;
Properties getClientInfo() throws SQLException;
String getClientInfo(String paramString) throws SQLException;
boolean isValid(int paramInt) throws SQLException;
void setClientInfo(Properties paramProperties) throws SQLClientInfoException;
void setClientInfo(String paramString1, String paramString2) throws SQLClientInfoException;
boolean isWrapperFor(Class<?> paramClass) throws SQLException;
<T> T unwrap(Class<T> paramClass) throws SQLException;
java.sql.Blob createBlob();
java.sql.Clob createClob();
NClob createNClob();
}

View file

@ -0,0 +1,441 @@
package com.mysql.jdbc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.SQLException;
import java.sql.SQLXML;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXResult;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class JDBC4MysqlSQLXML implements SQLXML {
private XMLInputFactory inputFactory;
private XMLOutputFactory outputFactory;
private String stringRep;
private ResultSetInternalMethods owningResultSet;
private int columnIndexOfXml;
private boolean fromResultSet;
private boolean isClosed = false;
private boolean workingWithResult;
private DOMResult asDOMResult;
private SAXResult asSAXResult;
private SimpleSaxToReader saxToReaderConverter;
private StringWriter asStringWriter;
private ByteArrayOutputStream asByteArrayOutputStream;
private ExceptionInterceptor exceptionInterceptor;
protected JDBC4MysqlSQLXML(ResultSetInternalMethods owner, int index, ExceptionInterceptor exceptionInterceptor) {
this.owningResultSet = owner;
this.columnIndexOfXml = index;
this.fromResultSet = true;
this.exceptionInterceptor = exceptionInterceptor;
}
protected JDBC4MysqlSQLXML(ExceptionInterceptor exceptionInterceptor) {
this.fromResultSet = false;
this.exceptionInterceptor = exceptionInterceptor;
}
public synchronized void free() throws SQLException {
this.stringRep = null;
this.asDOMResult = null;
this.asSAXResult = null;
this.inputFactory = null;
this.outputFactory = null;
this.owningResultSet = null;
this.workingWithResult = false;
this.isClosed = true;
}
public synchronized String getString() throws SQLException {
checkClosed();
checkWorkingWithResult();
if (this.fromResultSet)
return this.owningResultSet.getString(this.columnIndexOfXml);
return this.stringRep;
}
private synchronized void checkClosed() throws SQLException {
if (this.isClosed)
throw SQLError.createSQLException("SQLXMLInstance has been free()d", this.exceptionInterceptor);
}
private synchronized void checkWorkingWithResult() throws SQLException {
if (this.workingWithResult)
throw SQLError.createSQLException("Can't perform requested operation after getResult() has been called to write XML data", "S1009", this.exceptionInterceptor);
}
public synchronized void setString(String str) throws SQLException {
checkClosed();
checkWorkingWithResult();
this.stringRep = str;
this.fromResultSet = false;
}
public synchronized boolean isEmpty() throws SQLException {
checkClosed();
checkWorkingWithResult();
if (!this.fromResultSet)
return (this.stringRep == null || this.stringRep.length() == 0);
return false;
}
public synchronized InputStream getBinaryStream() throws SQLException {
checkClosed();
checkWorkingWithResult();
return this.owningResultSet.getBinaryStream(this.columnIndexOfXml);
}
public synchronized Reader getCharacterStream() throws SQLException {
checkClosed();
checkWorkingWithResult();
return this.owningResultSet.getCharacterStream(this.columnIndexOfXml);
}
public synchronized Source getSource(Class clazz) throws SQLException {
checkClosed();
checkWorkingWithResult();
if (clazz == null || clazz.equals(SAXSource.class)) {
InputSource inputSource = null;
if (this.fromResultSet) {
inputSource = new InputSource(this.owningResultSet.getCharacterStream(this.columnIndexOfXml));
} else {
inputSource = new InputSource(new StringReader(this.stringRep));
}
return new SAXSource(inputSource);
}
if (clazz.equals(DOMSource.class))
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
InputSource inputSource = null;
if (this.fromResultSet) {
inputSource = new InputSource(this.owningResultSet.getCharacterStream(this.columnIndexOfXml));
} else {
inputSource = new InputSource(new StringReader(this.stringRep));
}
return new DOMSource(builder.parse(inputSource));
} catch (Throwable t) {
SQLException sqlEx = SQLError.createSQLException(t.getMessage(), "S1009", this.exceptionInterceptor);
sqlEx.initCause(t);
throw sqlEx;
}
if (clazz.equals(StreamSource.class)) {
Reader reader = null;
if (this.fromResultSet) {
reader = this.owningResultSet.getCharacterStream(this.columnIndexOfXml);
} else {
reader = new StringReader(this.stringRep);
}
return new StreamSource(reader);
}
if (clazz.equals(StAXSource.class))
try {
Reader reader = null;
if (this.fromResultSet) {
reader = this.owningResultSet.getCharacterStream(this.columnIndexOfXml);
} else {
reader = new StringReader(this.stringRep);
}
return new StAXSource(this.inputFactory.createXMLStreamReader(reader));
} catch (XMLStreamException ex) {
SQLException sqlEx = SQLError.createSQLException(ex.getMessage(), "S1009", this.exceptionInterceptor);
sqlEx.initCause(ex);
throw sqlEx;
}
throw SQLError.createSQLException("XML Source of type \"" + clazz.toString() + "\" Not supported.", "S1009", this.exceptionInterceptor);
}
public synchronized OutputStream setBinaryStream() throws SQLException {
checkClosed();
checkWorkingWithResult();
this.workingWithResult = true;
return setBinaryStreamInternal();
}
private synchronized OutputStream setBinaryStreamInternal() throws SQLException {
this.asByteArrayOutputStream = new ByteArrayOutputStream();
return this.asByteArrayOutputStream;
}
public synchronized Writer setCharacterStream() throws SQLException {
checkClosed();
checkWorkingWithResult();
this.workingWithResult = true;
return setCharacterStreamInternal();
}
private synchronized Writer setCharacterStreamInternal() throws SQLException {
this.asStringWriter = new StringWriter();
return this.asStringWriter;
}
public synchronized Result setResult(Class clazz) throws SQLException {
checkClosed();
checkWorkingWithResult();
this.workingWithResult = true;
this.asDOMResult = null;
this.asSAXResult = null;
this.saxToReaderConverter = null;
this.stringRep = null;
this.asStringWriter = null;
this.asByteArrayOutputStream = null;
if (clazz == null || clazz.equals(SAXResult.class)) {
this.saxToReaderConverter = new SimpleSaxToReader();
this.asSAXResult = new SAXResult(this.saxToReaderConverter);
return this.asSAXResult;
}
if (clazz.equals(DOMResult.class)) {
this.asDOMResult = new DOMResult();
return this.asDOMResult;
}
if (clazz.equals(StreamResult.class))
return new StreamResult(setCharacterStreamInternal());
if (clazz.equals(StAXResult.class))
try {
if (this.outputFactory == null)
this.outputFactory = XMLOutputFactory.newInstance();
return new StAXResult(this.outputFactory.createXMLEventWriter(setCharacterStreamInternal()));
} catch (XMLStreamException ex) {
SQLException sqlEx = SQLError.createSQLException(ex.getMessage(), "S1009", this.exceptionInterceptor);
sqlEx.initCause(ex);
throw sqlEx;
}
throw SQLError.createSQLException("XML Result of type \"" + clazz.toString() + "\" Not supported.", "S1009", this.exceptionInterceptor);
}
private Reader binaryInputStreamStreamToReader(ByteArrayOutputStream out) {
try {
String encoding = "UTF-8";
try {
ByteArrayInputStream bIn = new ByteArrayInputStream(out.toByteArray());
XMLStreamReader reader = this.inputFactory.createXMLStreamReader(bIn);
int eventType = 0;
while ((eventType = reader.next()) != 8) {
if (eventType == 7) {
String possibleEncoding = reader.getEncoding();
if (possibleEncoding != null) {
encoding = possibleEncoding;
break;
}
break;
}
}
} catch (Throwable t) {}
return new StringReader(new String(out.toByteArray(), encoding));
} catch (UnsupportedEncodingException badEnc) {
throw new RuntimeException(badEnc);
}
}
protected String readerToString(Reader reader) throws SQLException {
StringBuffer buf = new StringBuffer();
int charsRead = 0;
char[] charBuf = new char[512];
try {
while ((charsRead = reader.read(charBuf)) != -1)
buf.append(charBuf, 0, charsRead);
} catch (IOException ioEx) {
SQLException sqlEx = SQLError.createSQLException(ioEx.getMessage(), "S1009", this.exceptionInterceptor);
sqlEx.initCause(ioEx);
throw sqlEx;
}
return buf.toString();
}
protected synchronized Reader serializeAsCharacterStream() throws SQLException {
checkClosed();
if (this.workingWithResult) {
if (this.stringRep != null)
return new StringReader(this.stringRep);
if (this.asDOMResult != null)
return new StringReader(domSourceToString());
if (this.asStringWriter != null)
return new StringReader(this.asStringWriter.toString());
if (this.asSAXResult != null)
return this.saxToReaderConverter.toReader();
if (this.asByteArrayOutputStream != null)
return binaryInputStreamStreamToReader(this.asByteArrayOutputStream);
}
return this.owningResultSet.getCharacterStream(this.columnIndexOfXml);
}
protected String domSourceToString() throws SQLException {
try {
DOMSource source = new DOMSource(this.asDOMResult.getNode());
Transformer identity = TransformerFactory.newInstance().newTransformer();
StringWriter stringOut = new StringWriter();
Result result = new StreamResult(stringOut);
identity.transform(source, result);
return stringOut.toString();
} catch (Throwable t) {
SQLException sqlEx = SQLError.createSQLException(t.getMessage(), "S1009", this.exceptionInterceptor);
sqlEx.initCause(t);
throw sqlEx;
}
}
protected synchronized String serializeAsString() throws SQLException {
checkClosed();
if (this.workingWithResult) {
if (this.stringRep != null)
return this.stringRep;
if (this.asDOMResult != null)
return domSourceToString();
if (this.asStringWriter != null)
return this.asStringWriter.toString();
if (this.asSAXResult != null)
return readerToString(this.saxToReaderConverter.toReader());
if (this.asByteArrayOutputStream != null)
return readerToString(binaryInputStreamStreamToReader(this.asByteArrayOutputStream));
}
return this.owningResultSet.getString(this.columnIndexOfXml);
}
class SimpleSaxToReader extends DefaultHandler {
StringBuffer buf = new StringBuffer();
public void startDocument() throws SAXException {
this.buf.append("<?xml version='1.0' encoding='UTF-8'?>");
}
public void endDocument() throws SAXException {}
public void startElement(String namespaceURI, String sName, String qName, Attributes attrs) throws SAXException {
this.buf.append("<");
this.buf.append(qName);
if (attrs != null)
for (int i = 0; i < attrs.getLength(); i++) {
this.buf.append(" ");
this.buf.append(attrs.getQName(i)).append("=\"");
escapeCharsForXml(attrs.getValue(i), true);
this.buf.append("\"");
}
this.buf.append(">");
}
public void characters(char[] buf, int offset, int len) throws SAXException {
if (!this.inCDATA) {
escapeCharsForXml(buf, offset, len, false);
} else {
this.buf.append(buf, offset, len);
}
}
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
characters(ch, start, length);
}
private boolean inCDATA = false;
public void startCDATA() throws SAXException {
this.buf.append("<![CDATA[");
this.inCDATA = true;
}
public void endCDATA() throws SAXException {
this.inCDATA = false;
this.buf.append("]]>");
}
public void comment(char[] ch, int start, int length) throws SAXException {
this.buf.append("<!--");
for (int i = 0; i < length; i++)
this.buf.append(ch[start + i]);
this.buf.append("-->");
}
Reader toReader() {
return new StringReader(this.buf.toString());
}
private void escapeCharsForXml(String str, boolean isAttributeData) {
if (str == null)
return;
int strLen = str.length();
for (int i = 0; i < strLen; i++)
escapeCharsForXml(str.charAt(i), isAttributeData);
}
private void escapeCharsForXml(char[] buf, int offset, int len, boolean isAttributeData) {
if (buf == null)
return;
for (int i = 0; i < len; i++)
escapeCharsForXml(buf[offset + i], isAttributeData);
}
private void escapeCharsForXml(char c, boolean isAttributeData) {
switch (c) {
case '<':
this.buf.append("&lt;");
break;
case '>':
this.buf.append("&gt;");
break;
case '&':
this.buf.append("&amp;");
break;
case '"':
if (!isAttributeData) {
this.buf.append("\"");
} else {
this.buf.append("&quot;");
}
break;
case '\r':
this.buf.append("&#xD;");
break;
default:
if ((c >= '\001' && c <= '\037' && c != '\t' && c != '\n') || (c >= '\u007F' && c <= '\u009F') || c == '' || (isAttributeData && (c == '\t' || c == '\n'))) {
this.buf.append("&#x");
this.buf.append(Integer.toHexString(c).toUpperCase());
this.buf.append(";");
} else {
this.buf.append(c);
}
break;
}
}
}
}

View file

@ -0,0 +1,13 @@
package com.mysql.jdbc;
import java.sql.NClob;
public class JDBC4NClob extends Clob implements NClob {
JDBC4NClob(ExceptionInterceptor exceptionInterceptor) {
super(exceptionInterceptor);
}
JDBC4NClob(String charDataInit, ExceptionInterceptor exceptionInterceptor) {
super(charDataInit, exceptionInterceptor);
}
}

View file

@ -0,0 +1,32 @@
package com.mysql.jdbc;
import java.sql.NClob;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
public class JDBC4PreparedStatement extends PreparedStatement {
public JDBC4PreparedStatement(MySQLConnection conn, String catalog) throws SQLException {
super(conn, catalog);
}
public JDBC4PreparedStatement(MySQLConnection conn, String sql, String catalog) throws SQLException {
super(conn, sql, catalog);
}
public JDBC4PreparedStatement(MySQLConnection conn, String sql, String catalog, PreparedStatement.ParseInfo cachedParseInfo) throws SQLException {
super(conn, sql, catalog, cachedParseInfo);
}
public void setRowId(int parameterIndex, RowId x) throws SQLException {
JDBC4PreparedStatementHelper.setRowId(this, parameterIndex, x);
}
public void setNClob(int parameterIndex, NClob value) throws SQLException {
JDBC4PreparedStatementHelper.setNClob(this, parameterIndex, value);
}
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
JDBC4PreparedStatementHelper.setSQLXML(this, parameterIndex, xmlObject);
}
}

View file

@ -0,0 +1,41 @@
package com.mysql.jdbc;
import java.io.Reader;
import java.sql.NClob;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
public class JDBC4PreparedStatementHelper {
static void setRowId(PreparedStatement pstmt, int parameterIndex, RowId x) throws SQLException {
throw SQLError.notImplemented();
}
static void setNClob(PreparedStatement pstmt, int parameterIndex, NClob value) throws SQLException {
if (value == null) {
pstmt.setNull(parameterIndex, 2011);
} else {
pstmt.setNCharacterStream(parameterIndex, value.getCharacterStream(), value.length());
}
}
static void setNClob(PreparedStatement pstmt, int parameterIndex, Reader reader) throws SQLException {
pstmt.setNCharacterStream(parameterIndex, reader);
}
static void setNClob(PreparedStatement pstmt, int parameterIndex, Reader reader, long length) throws SQLException {
if (reader == null) {
pstmt.setNull(parameterIndex, 2011);
} else {
pstmt.setNCharacterStream(parameterIndex, reader, length);
}
}
static void setSQLXML(PreparedStatement pstmt, int parameterIndex, SQLXML xmlObject) throws SQLException {
if (xmlObject == null) {
pstmt.setNull(parameterIndex, 2009);
} else {
pstmt.setCharacterStream(parameterIndex, ((JDBC4MysqlSQLXML)xmlObject).serializeAsCharacterStream());
}
}
}

View file

@ -0,0 +1,292 @@
package com.mysql.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.NClob;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLXML;
import java.sql.Struct;
public class JDBC4ResultSet extends ResultSetImpl {
public JDBC4ResultSet(long updateCount, long updateID, MySQLConnection conn, StatementImpl creatorStmt) {
super(updateCount, updateID, conn, creatorStmt);
}
public JDBC4ResultSet(String catalog, Field[] fields, RowData tuples, MySQLConnection conn, StatementImpl creatorStmt) throws SQLException {
super(catalog, fields, tuples, conn, creatorStmt);
}
public Reader getNCharacterStream(int columnIndex) throws SQLException {
checkColumnBounds(columnIndex);
String fieldEncoding = this.fields[columnIndex - 1].getEncoding();
if (fieldEncoding == null || !fieldEncoding.equals("UTF-8"))
throw new SQLException("Can not call getNCharacterStream() when field's charset isn't UTF-8");
return getCharacterStream(columnIndex);
}
public Reader getNCharacterStream(String columnName) throws SQLException {
return getNCharacterStream(findColumn(columnName));
}
public NClob getNClob(int columnIndex) throws SQLException {
checkColumnBounds(columnIndex);
String fieldEncoding = this.fields[columnIndex - 1].getEncoding();
if (fieldEncoding == null || !fieldEncoding.equals("UTF-8"))
throw new SQLException("Can not call getNClob() when field's charset isn't UTF-8");
if (!this.isBinaryEncoded) {
String asString = getStringForNClob(columnIndex);
if (asString == null)
return null;
return new JDBC4NClob(asString, getExceptionInterceptor());
}
return getNativeNClob(columnIndex);
}
public NClob getNClob(String columnName) throws SQLException {
return getNClob(findColumn(columnName));
}
protected NClob getNativeNClob(int columnIndex) throws SQLException {
String stringVal = getStringForNClob(columnIndex);
if (stringVal == null)
return null;
return getNClobFromString(stringVal, columnIndex);
}
private String getStringForNClob(int columnIndex) throws SQLException {
String asString = null;
String forcedEncoding = "UTF-8";
try {
byte[] asBytes = null;
if (!this.isBinaryEncoded) {
asBytes = getBytes(columnIndex);
} else {
asBytes = getNativeBytes(columnIndex, true);
}
if (asBytes != null)
asString = new String(asBytes, forcedEncoding);
} catch (UnsupportedEncodingException uee) {
throw SQLError.createSQLException("Unsupported character encoding " + forcedEncoding, "S1009", getExceptionInterceptor());
}
return asString;
}
private final NClob getNClobFromString(String stringVal, int columnIndex) throws SQLException {
return new JDBC4NClob(stringVal, getExceptionInterceptor());
}
public String getNString(int columnIndex) throws SQLException {
checkColumnBounds(columnIndex);
String fieldEncoding = this.fields[columnIndex - 1].getEncoding();
if (fieldEncoding == null || !fieldEncoding.equals("UTF-8"))
throw new SQLException("Can not call getNString() when field's charset isn't UTF-8");
return getString(columnIndex);
}
public String getNString(String columnName) throws SQLException {
return getNString(findColumn(columnName));
}
public void updateNCharacterStream(int columnIndex, Reader x, int length) throws SQLException {
throw new NotUpdatable();
}
public void updateNCharacterStream(String columnName, Reader reader, int length) throws SQLException {
updateNCharacterStream(findColumn(columnName), reader, length);
}
public void updateNClob(String columnName, NClob nClob) throws SQLException {
updateNClob(findColumn(columnName), nClob);
}
public void updateRowId(int columnIndex, RowId x) throws SQLException {
throw new NotUpdatable();
}
public void updateRowId(String columnName, RowId x) throws SQLException {
updateRowId(findColumn(columnName), x);
}
public int getHoldability() throws SQLException {
throw SQLError.notImplemented();
}
public RowId getRowId(int columnIndex) throws SQLException {
throw SQLError.notImplemented();
}
public RowId getRowId(String columnLabel) throws SQLException {
return getRowId(findColumn(columnLabel));
}
public SQLXML getSQLXML(int columnIndex) throws SQLException {
checkColumnBounds(columnIndex);
return new JDBC4MysqlSQLXML(this, columnIndex, getExceptionInterceptor());
}
public SQLXML getSQLXML(String columnLabel) throws SQLException {
return getSQLXML(findColumn(columnLabel));
}
public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException {
throw new NotUpdatable();
}
public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException {
updateAsciiStream(findColumn(columnLabel), x);
}
public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException {
throw new NotUpdatable();
}
public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException {
updateAsciiStream(findColumn(columnLabel), x, length);
}
public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException {
throw new NotUpdatable();
}
public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException {
updateBinaryStream(findColumn(columnLabel), x);
}
public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException {
throw new NotUpdatable();
}
public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException {
updateBinaryStream(findColumn(columnLabel), x, length);
}
public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException {
throw new NotUpdatable();
}
public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException {
updateBlob(findColumn(columnLabel), inputStream);
}
public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException {
throw new NotUpdatable();
}
public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException {
updateBlob(findColumn(columnLabel), inputStream, length);
}
public void updateCharacterStream(int columnIndex, Reader x) throws SQLException {
throw new NotUpdatable();
}
public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException {
updateCharacterStream(findColumn(columnLabel), reader);
}
public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException {
throw new NotUpdatable();
}
public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException {
updateCharacterStream(findColumn(columnLabel), reader, length);
}
public void updateClob(int columnIndex, Reader reader) throws SQLException {
throw new NotUpdatable();
}
public void updateClob(String columnLabel, Reader reader) throws SQLException {
updateClob(findColumn(columnLabel), reader);
}
public void updateClob(int columnIndex, Reader reader, long length) throws SQLException {
throw new NotUpdatable();
}
public void updateClob(String columnLabel, Reader reader, long length) throws SQLException {
updateClob(findColumn(columnLabel), reader, length);
}
public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException {
throw new NotUpdatable();
}
public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException {
updateNCharacterStream(findColumn(columnLabel), reader);
}
public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException {
throw new NotUpdatable();
}
public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException {
updateNCharacterStream(findColumn(columnLabel), reader, length);
}
public void updateNClob(int columnIndex, NClob nClob) throws SQLException {
throw new NotUpdatable();
}
public void updateNClob(int columnIndex, Reader reader) throws SQLException {
throw new NotUpdatable();
}
public void updateNClob(String columnLabel, Reader reader) throws SQLException {
updateNClob(findColumn(columnLabel), reader);
}
public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException {
throw new NotUpdatable();
}
public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException {
updateNClob(findColumn(columnLabel), reader, length);
}
public void updateNString(int columnIndex, String nString) throws SQLException {
throw new NotUpdatable();
}
public void updateNString(String columnLabel, String nString) throws SQLException {
updateNString(findColumn(columnLabel), nString);
}
public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException {
throw new NotUpdatable();
}
public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException {
updateSQLXML(findColumn(columnLabel), xmlObject);
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
checkClosed();
return iface.isInstance(this);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), "S1009", getExceptionInterceptor());
}
}
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
if (type == null)
throw SQLError.createSQLException("Type parameter can not be null", "S1009", getExceptionInterceptor());
if (type.equals(Struct.class))
throw new SQLFeatureNotSupportedException();
if (type.equals(RowId.class))
return (T)getRowId(columnIndex);
if (type.equals(NClob.class))
return (T)getNClob(columnIndex);
if (type.equals(SQLXML.class))
return (T)getSQLXML(columnIndex);
return super.<T>getObject(columnIndex, type);
}
}

Some files were not shown because too many files have changed in this diff Show more