use of org.eclipse.persistence.internal.sessions.ArrayRecord in project eclipselink by eclipse-ee4j.
the class DatabaseAccessor method fetchRow.
/**
* Return a new DatabaseRow.<p>
* Populate the row from the data in cursor. The fields representing the results
* and the order of the results are stored in fields.
* <p><b>NOTE</b>:
* Make sure that the field name is set. An empty field name placeholder is
* used in the sortFields() method when the number of fields defined does not
* match the number of column names available on the database.
* PERF: This method must be highly optimized.
*/
public AbstractRecord fetchRow(Vector<DatabaseField> fields, DatabaseField[] fieldsArray, ResultSet resultSet, ResultSetMetaData metaData, AbstractSession session) throws DatabaseException {
int size = fieldsArray.length;
Object[] values = new Object[size];
// PERF: Pass platform and optimize data flag.
DatabasePlatform platform = getPlatform();
boolean optimizeData = platform.shouldOptimizeDataConversion();
for (int index = 0; index < size; index++) {
DatabaseField field = fieldsArray[index];
// Field can be null for fetch groups.
if (field != null) {
values[index] = getObject(resultSet, field, metaData, index + 1, platform, optimizeData, session);
} else {
values[index] = null;
}
}
// Row creation is optimized through sharing the same fields for the entire result set.
return new ArrayRecord(fields, fieldsArray, values);
}
use of org.eclipse.persistence.internal.sessions.ArrayRecord in project eclipselink by eclipse-ee4j.
the class FailoverBase method prepare.
@Before
public void prepare() {
DatabaseLogin login = new DatabaseLogin();
login.useDirectDriverConnect();
login.setDriverClass(EmulatedDriver.class);
login.setConnectionString("jdbc:emulateddriver");
login.getPlatform().setPingSQL("SELECT 1");
Project p = new Project(login);
ClassDescriptor cd = Address.descriptor();
p.addDescriptor(cd);
session = createSession(p);
SessionLog log = new DefaultSessionLog(new OutputStreamWriter(System.out));
int logLevel = AbstractSessionLog.translateStringToLoggingLevel(System.getProperty(PersistenceUnitProperties.LOGGING_LEVEL, "INFO"));
session.setSessionLog(log);
session.setLogLevel(logLevel);
session.login();
// this will actually store the results on the driver for subsequent connections.
EmulatedConnection con = (EmulatedConnection) ((DatabaseSessionImpl) session).getAccessor().getConnection();
Vector<DatabaseField> pingFields = new Vector<DatabaseField>() {
{
add(new DatabaseField("1"));
}
};
con.putRows("SELECT 1", new Vector() {
{
add(new ArrayRecord(pingFields, pingFields.toArray(new DatabaseField[0]), new Object[] { "1" }));
}
});
con.putRows(Address.getSQL(), Address.getData(cd));
}
use of org.eclipse.persistence.internal.sessions.ArrayRecord in project eclipselink by eclipse-ee4j.
the class ObjectBuilder method buildObjectFromResultSetInternal.
/**
* INTERNAL:
* Builds a working copy clone directly from a result set.
* PERF: This method is optimized for a specific case of building objects
* so can avoid many of the normal checks, only queries that have this criteria
* can use this method of building objects.
*/
private Object buildObjectFromResultSetInternal(ObjectBuildingQuery query, JoinedAttributeManager joinManager, ResultSet resultSet, AbstractSession executionSession, DatabaseAccessor accessor, ResultSetMetaData metaData, DatabasePlatform platform, Vector fieldsList, DatabaseField[] fieldsArray) throws SQLException {
ClassDescriptor descriptor = this.descriptor;
int pkFieldsSize = descriptor.getPrimaryKeyFields().size();
DatabaseMapping primaryKeyMapping = null;
AbstractRecord row = null;
Object[] values = null;
Object primaryKey;
if (isSimple && pkFieldsSize == 1) {
primaryKeyMapping = this.primaryKeyMappings.get(0);
primaryKey = primaryKeyMapping.valueFromResultSet(resultSet, query, executionSession, accessor, metaData, 1, platform);
} else {
values = new Object[fieldsArray.length];
row = new ArrayRecord(fieldsList, fieldsArray, values);
accessor.populateRow(fieldsArray, values, resultSet, metaData, executionSession, 0, pkFieldsSize);
primaryKey = extractPrimaryKeyFromRow(row, executionSession);
}
UnitOfWorkImpl unitOfWork = null;
AbstractSession session = executionSession;
boolean isolated = !descriptor.getCachePolicy().isSharedIsolation();
if (session.isUnitOfWork()) {
unitOfWork = (UnitOfWorkImpl) executionSession;
isolated |= unitOfWork.wasTransactionBegunPrematurely() && descriptor.shouldIsolateObjectsInUnitOfWorkEarlyTransaction();
}
CacheKey cacheKey = session.getIdentityMapAccessorInstance().getIdentityMapManager().acquireLock(primaryKey, descriptor.getJavaClass(), false, descriptor, query.isCacheCheckComplete());
CacheKey cacheKeyToUse = cacheKey;
CacheKey parentCacheKey = null;
Object object = cacheKey.getObject();
try {
// Found locally in the unit of work, or session query and found in the session.
if (object != null) {
return object;
}
if ((unitOfWork != null) && !isolated) {
// Need to lookup in the session.
session = unitOfWork.getParentIdentityMapSession(query);
parentCacheKey = session.getIdentityMapAccessorInstance().getIdentityMapManager().acquireLock(primaryKey, descriptor.getJavaClass(), false, descriptor, query.isCacheCheckComplete());
cacheKeyToUse = parentCacheKey;
object = parentCacheKey.getObject();
}
// If the object is not in the cache, it needs to be built, this is building in the unit of work if isolated.
if (object == null) {
object = buildNewInstance();
if (unitOfWork == null) {
cacheKey.setObject(object);
} else {
if (isolated) {
cacheKey.setObject(object);
unitOfWork.getCloneMapping().put(object, object);
} else {
parentCacheKey.setObject(object);
}
}
List<DatabaseMapping> mappings = descriptor.getMappings();
int size = mappings.size();
if (isSimple) {
int shift = descriptor.getTables().size() * pkFieldsSize;
if (primaryKeyMapping != null) {
// simple primary key - set pk directly through the mapping
primaryKeyMapping.setAttributeValueInObject(object, primaryKey);
} else {
// composite primary key - set pk using pkRow
boolean isTargetProtected = session.isProtectedSession();
for (int index = 0; index < pkFieldsSize; index++) {
DatabaseMapping mapping = mappings.get(index);
mapping.readFromRowIntoObject(row, joinManager, object, cacheKeyToUse, query, session, isTargetProtected);
}
}
// set the rest using mappings directly
for (int index = pkFieldsSize; index < size; index++) {
DatabaseMapping mapping = mappings.get(index);
mapping.readFromResultSetIntoObject(resultSet, object, query, session, accessor, metaData, index + shift, platform);
}
} else {
boolean isTargetProtected = session.isProtectedSession();
accessor.populateRow(fieldsArray, values, resultSet, metaData, session, pkFieldsSize, fieldsArray.length);
for (int index = 0; index < size; index++) {
DatabaseMapping mapping = mappings.get(index);
mapping.readFromRowIntoObject(row, joinManager, object, cacheKeyToUse, query, session, isTargetProtected);
}
}
((PersistenceEntity) object)._persistence_setId(primaryKey);
if ((unitOfWork != null) && isolated) {
ObjectChangePolicy policy = descriptor.getObjectChangePolicy();
policy.setChangeListener(object, unitOfWork, descriptor);
}
}
if ((unitOfWork != null) && !isolated) {
// Need to clone the object in the unit of work.
// TODO: Doesn't work all the time
// With one setup (jpa2.performance tests) produces a shallow clone (which is good enough for isSimple==true case only),
// in other (jpa.advanced tests) - just a brand new empty object.
Object clone = instantiateWorkingCopyClone(object, unitOfWork);
((PersistenceEntity) clone)._persistence_setId(cacheKey.getKey());
unitOfWork.getCloneMapping().put(clone, clone);
unitOfWork.getCloneToOriginals().put(clone, object);
cacheKey.setObject(clone);
ObjectChangePolicy policy = descriptor.getObjectChangePolicy();
policy.setChangeListener(clone, unitOfWork, descriptor);
object = clone;
}
} finally {
cacheKey.release();
if (parentCacheKey != null) {
parentCacheKey.release();
}
}
return object;
}
use of org.eclipse.persistence.internal.sessions.ArrayRecord in project eclipselink by eclipse-ee4j.
the class ClearDatabaseSchemaTest method resetMySQL.
private void resetMySQL(AbstractSession session) {
ArrayRecord record = null;
try {
record = (ArrayRecord) session.executeSQL("select DATABASE()").get(0);
session.executeNonSelectingSQL("drop database " + record.get("DATABASE()"));
} catch (DatabaseException x) {
AbstractSessionLog.getLog().warning("Failed to drop database");
// Using System.err since session log may not print out the stack trace
x.printStackTrace(System.err);
} finally {
if (record != null) {
session.executeNonSelectingSQL("create database " + record.get("DATABASE()"));
} else {
DatabaseLogin databaseLogin = (DatabaseLogin) session.getDatasourceLogin();
String url = databaseLogin.getDatabaseURL();
Properties properties = new Properties();
properties.put("user", databaseLogin.getUserName());
properties.put("password", databaseLogin.getPassword());
int databaseNameSeparatorIndex = url.lastIndexOf('/');
String databaseName = url.substring(databaseNameSeparatorIndex + 1);
int propertiesIndex = databaseName.indexOf('?');
if (propertiesIndex > 0) {
for (String propertyString : databaseName.substring(propertiesIndex + 1).split("&")) {
String[] propertyDetails = propertyString.split("=");
properties.put(propertyDetails[0].trim(), propertyDetails[1].trim());
}
databaseName = databaseName.substring(0, propertiesIndex);
}
url = url.substring(0, databaseNameSeparatorIndex);
try (Connection connection = DriverManager.getConnection(url, properties)) {
connection.prepareStatement("create database " + databaseName).execute();
} catch (SQLException e) {
// Using System.err since session log may not print out the stack trace
e.printStackTrace(System.err);
}
}
}
// unused for now but kept here for alternate option
// Vector<ArrayRecord> result = session.executeSQL("SELECT concat('ALTER TABLE ', C.TABLE_SCHEMA, '.', C.TABLE_NAME, ' DROP FOREIGN KEY ', C.CONSTRAINT_NAME) "
// + "FROM information_schema.TABLE_CONSTRAINTS C "
// + "WHERE C.TABLE_SCHEMA = (SELECT SCHEMA()) and C.CONSTRAINT_TYPE = 'FOREIGN KEY'");
// List<String> toRetry = execStatements(session, result);
// result = session.executeSQL("SELECT concat('DROP TABLE IF EXISTS ', T.TABLE_SCHEMA, '.', T.TABLE_NAME) "
// + "FROM information_schema.TABLES T WHERE T.TABLE_SCHEMA = (SELECT SCHEMA())");
// toRetry.addAll(execStatements(session, result));
// assertTrue(toRetry + " statements failed", toRetry.isEmpty());
}
use of org.eclipse.persistence.internal.sessions.ArrayRecord in project eclipselink by eclipse-ee4j.
the class Address method getData.
static Vector<DatabaseRecord> getData(ClassDescriptor desc) {
Vector<DatabaseRecord> rows = new Vector<>();
Vector<DatabaseField> fields = desc.getAllFields();
DatabaseField[] fieldsArray = fields.toArray(new DatabaseField[0]);
rows.add(new ArrayRecord(fields, fieldsArray, new Object[] { 51, "Calgary", "Canada", "J5J2B5", "ALB", "1111 Moose Rd." }));
rows.add(new ArrayRecord(fields, fieldsArray, new Object[] { 52, "Metcalfe", "Canada", "Y4F7V6", "ONT", "2 Anderson Rd." }));
rows.add(new ArrayRecord(fields, fieldsArray, new Object[] { 53, "Montreal", "Canada", "Q2S5Z5", "QUE", "1 Habs Place" }));
return rows;
}
Aggregations