Reads primary key information from current RS row and generates a

corresponding Identity, and returns a proxy from the Identity.

@throws PersistenceBrokerException
if there was an error creating the proxy class
335409
protected Object getProxyFromResultSet() throws PersistenceBrokerException
    {
        // 1. get Identity of current row:
        Identity oid = getIdentityFromResultSet();

        // 2. return a Proxy instance:
        return getBroker().createProxy(getItemProxyClass(), oid);
    }
1374359
@Override
    protected RDBMSEntityReader getReader()
    {
        if (reader == null)
        {
            reader = new RDBMSEntityReader(getJPAQuery(), kunderaQuery, kunderaMetadata);
        }
        return reader;
    }
886275
public void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("executeInsert: " + obj);
        }
        final StatementManagerIF sm = broker.serviceStatementManager();
        PreparedStatement stmt = null;
        try
        {
            stmt = sm.getInsertStatement(cld);
            if (stmt == null)
            {
                logger.error("getInsertStatement returned a null statement");
                throw new PersistenceBrokerException("getInsertStatement returned a null statement");
            }
            // before bind values perform autoincrement sequence columns
            assignAutoincrementSequences(cld, obj);
            sm.bindInsert(stmt, cld, obj);
            if (logger.isDebugEnabled())
                logger.debug("executeInsert: " + stmt);
            stmt.executeUpdate();
            // after insert read and assign identity columns
            assignAutoincrementIdentityColumns(cld, obj);

            // Harvest any return values.
            harvestReturnValues(cld.getInsertProcedure(), obj, stmt);
        }
        catch (PersistenceBrokerException e)
        {
            logger.error("PersistenceBrokerException during the execution of the insert: " + e.getMessage(), e);
            throw e;
        }
        catch(SequenceManagerException e)
        {
            throw new PersistenceBrokerException("Error while try to assign identity value", e);
        }
        catch (SQLException e)
        {
            final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();
            throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
        }
        finally
        {
            sm.closeResources(stmt, null);
        }
    }
508192
public PreparedStatement getSelectByPKStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException
    {
        try
        {
            return cds.getStatementsForClass(m_conMan).getSelectByPKStmt(m_conMan.getConnection());
        }
        catch (SQLException e)
        {
            throw new PersistenceBrokerSQLException("Could not build statement ask for", e);
        }
        catch (LookupException e)
        {
            throw new PersistenceBrokerException("Used ConnectionManager instance could not obtain a connection", e);
        }
    }
877716
private void marshalKey() {

    Key parent = null;

    ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata();
    if (parentKeyMetadata != null) {
      DatastoreKey parentDatastoreKey = (DatastoreKey) getFieldValue(parentKeyMetadata);
      if (parentDatastoreKey != null) {
        parent = parentDatastoreKey.nativeKey();
      }
    }

    IdentifierMetadata identifierMetadata = entityMetadata.getIdentifierMetadata();
    IdClassMetadata idClassMetadata = identifierMetadata.getIdClassMetadata();
    DataType identifierType = identifierMetadata.getDataType();
    Object idValue = getFieldValue(identifierMetadata);

    // If ID value is null, we don't have to worry about if it is a simple
    // type of a complex type. Otherwise, we need to see if the ID is a
    // complex type, and if it is, extract the real ID.
    if (idValue != null && idClassMetadata != null) {
      try {
        idValue = idClassMetadata.getReadMethod().invoke(idValue);
      } catch (Throwable t) {
        throw new EntityManagerException(t);
      }
    }

    boolean validId = isValidId(idValue, identifierType);
    boolean autoGenerateId = identifierMetadata.isAutoGenerated();

    if (validId) {
      if (identifierType == DataType.STRING) {
        createCompleteKey(parent, (String) idValue);
      } else {
        createCompleteKey(parent, (long) idValue);
      }
    } else {
      if (intent.isKeyRequired()) {
        throw new EntityManagerException(String
            .format("Identifier is not set or valid for entity of type %s", entity.getClass()));
      }
      if (!autoGenerateId) {
        String pattern = "Identifier is not set or valid for entity of type %s. Auto generation "
            + "of ID is explicitly turned off. ";
        throw new EntityManagerException(String.format(pattern, entity.getClass()));
      } else {
        if (identifierType == DataType.STRING) {
          createCompleteKey(parent);
        } else {
          createIncompleteKey(parent);
        }
      }
    }
  }
801609
public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException
    {
        return getKeyValues(cld, oid, true);
    }
142435
static void demo(PersistenceManager persistenceManager)
    {

        try {
            // Fetch an account.  Notice that the id is now a long rather than an integer.
            Account account = persistenceManager.findById(Account.class, 1L);
            assert account != null;
            assert account.getAccountId() == 1L;

            // This example creates a new account and attempts to save it without an identifier.
            Account account2 = new Account();
            persistenceManager.saveEntity(account2);

            // The account ID was not auto incremented.
            // This is because we removed the generator from the @Identifier annotation.
            assert 0 == account2.getAccountId();
        } catch (OnyxException e)
        {
            e.printStackTrace();
        }
    }
248560
public PersistenceBrokerInternal createPersistenceBroker(PBKey pbKey) throws PBFactoryException
    {
        if (log.isDebugEnabled()) log.debug("Obtain broker from pool, used PBKey is " + pbKey);
        PersistenceBrokerInternal broker = null;

        /*
        try to find a valid PBKey, if given key does not full match
        */
        pbKey = BrokerHelper.crossCheckPBKey(pbKey);

        try
        {
            /*
            get a pooled PB instance, the pool is reponsible to create new
            PB instances if not found in pool
            */
            broker = ((PersistenceBrokerInternal) brokerPool.borrowObject(pbKey));
            /*
            now warp pooled PB instance with a handle to avoid PB corruption
            of closed PB instances.
            */
            broker = wrapRequestedBrokerInstance(broker);

        }
        catch (Exception e)
        {
            try
            {
                // if something going wrong, tryto close broker
                if(broker != null) broker.close();
            }
            catch (Exception ignore)
            {
                //ignore it
            }
            throw new PBFactoryException("Borrow broker from pool failed, using PBKey " + pbKey, e);
        }
        return broker;
    }
62552
public static long getMaxIdForClass(
            PersistenceBroker brokerForClass, ClassDescriptor cldForOriginalOrExtent, FieldDescriptor original)
            throws PersistenceBrokerException
    {
        FieldDescriptor field = null;
        if (!original.getClassDescriptor().equals(cldForOriginalOrExtent))
        {
            // check if extent match not the same table
            if (!original.getClassDescriptor().getFullTableName().equals(
                    cldForOriginalOrExtent.getFullTableName()))
            {
                // we have to look for id's in extent class table
                field = cldForOriginalOrExtent.getFieldDescriptorByName(original.getAttributeName());
            }
        }
        else
        {
            field = original;
        }
        if (field == null)
        {
            // if null skip this call
            return 0;
        }

        String column = field.getColumnName();
        long result = 0;
        ResultSet rs = null;
        Statement stmt = null;
        StatementManagerIF sm = brokerForClass.serviceStatementManager();
        String table = cldForOriginalOrExtent.getFullTableName();
        // String column = cld.getFieldDescriptorByName(fieldName).getColumnName();
        String sql = SM_SELECT_MAX + column + SM_FROM + table;
        try
        {
            //lookup max id for the current class
            stmt = sm.getGenericStatement(cldForOriginalOrExtent, Query.NOT_SCROLLABLE);
            rs = stmt.executeQuery(sql);
            rs.next();
            result = rs.getLong(1);
        }
        catch (Exception e)
        {
            log.warn("Cannot lookup max value from table " + table + " for column " + column +
                    ", PB was " + brokerForClass + ", using jdbc-descriptor " +
                    brokerForClass.serviceConnectionManager().getConnectionDescriptor(), e);
        }
        finally
        {
            try
            {
                sm.closeResources(stmt, rs);
            }
            catch (Exception ignore)
            {
                // ignore it
           }
        }
        return result;
    }
513350
@SuppressWarnings("unchecked")
    protected void fillIdentityPrimaryKeys(Object entity, ResultSet rs) throws SQLException {
        BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass());
        int size = beanDesc.getPropertyDescSize();

        for(int i=0; i < size; i++){
            PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i);
            PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class);
            if(primaryKey != null && primaryKey.generationType() == GenerationType.IDENTITY){
                if(rs.next()){
                    Class<?> propertyType = propertyDesc.getPropertyType();
                    @SuppressWarnings("rawtypes")
                    ValueType valueType = MirageUtil.getValueType(propertyType, propertyDesc, dialect, valueTypes);

                    if(valueType != null){
                         propertyDesc.setValue(entity, valueType.get(propertyType, rs, 1));
                    }
                }
            }
        }
    }
698915
function resolvePrimaryKey(row, context) {
    const resAttrNode = context.resourceAttrNode;
    const indexKey = resAttrNode.resolvedPrimaryKey[resAttrNode.primaryDataSource];

    function dereferenceKeyAttr(keyAttr) {
        const keyVal = row[keyAttr];
        if (keyVal === undefined) {
            const attrPath = context.attrPath.length > 0 ? context.attrPath.join('.') : '{root}';
            throw new DataError(
                `Result-row of "${attrPath}" (DataSource "${
                    resAttrNode.primaryDataSource
                }") misses primary key attribute "${keyAttr}"`
            );
        }
        return keyVal;
    }

    if (indexKey.length === 1) {
        context.primaryKey = '' + dereferenceKeyAttr(indexKey[0]);
    } else {
        context.primaryKey = indexKey.map(dereferenceKeyAttr).join(keySeparator);
    }

    // link rows from secondary DataSources by primary key:
    // row from joinVia-DataSource is passed via context here
    context.secondaryRows = context.secondaryRows || {};

    Object.keys(resAttrNode.dataSources).forEach(dataSourceName => {
        if (dataSourceName === resAttrNode.primaryDataSource) return;
        if (resAttrNode.joinVia && dataSourceName === resAttrNode.joinVia) return;
        if (!('resultId' in resAttrNode.dataSources[dataSourceName])) return;

        const secondaryResult = context.rawResults[resAttrNode.dataSources[dataSourceName].resultId];
        if (typeof secondaryResult.indexedData[context.primaryKey] === 'undefined') {
            context.api.log.debug(
                new DataError(
                    `Secondary DataSource "${dataSourceName}" of "` +
                        (context.attrPath.length > 0 ? context.attrPath.join('.') : '{root}') +
                        `": row with key "${context.primaryKey}" not found`
                )
            );
            context.secondaryRows[dataSourceName] = null;
        } else {
            context.secondaryRows[dataSourceName] = secondaryResult.indexedData[context.primaryKey];
        }
    });
}
468276
@Override
	public Map<String, Object> createRecord(final ResultSet rs) throws SQLException {
		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		Map<String, Object> record = new LinkedHashMap<>(columnCount);
		for (int i = 1; i <= columnCount; i++) {
			record.put(caseFormat.convert(rsmd.getColumnLabel(i)), getValue(rs, rsmd, i));
		}
		return record;
	}
531770
private User userFromResultSet(final ResultSet rs) throws SQLException {
      String niceName = Strings.nullToEmpty(rs.getString(3)).trim();
      String displayName = Strings.nullToEmpty(rs.getString(4)).trim();
      String useDisplayName = displayName.isEmpty() ? niceName : displayName;
      return new User(rs.getLong(1), rs.getString(2), useDisplayName, niceName, rs.getString(5), rs.getTimestamp(6).getTime(), rs.getString(7), ImmutableList.of());
   }
1280980
protected PersistenceBrokerInternal createNewBrokerInstance(PBKey key) throws PBFactoryException
    {
        if (key == null) throw new PBFactoryException("Could not create new broker with PBkey argument 'null'");
        // check if the given key really exists
        if (MetadataManager.getInstance().connectionRepository().getDescriptor(key) == null)
        {
            throw new PBFactoryException("Given PBKey " + key + " does not match in metadata configuration");
        }
        if (log.isEnabledFor(Logger.INFO))
        {
            // only count created instances when INFO-Log-Level
            log.info("Create new PB instance for PBKey " + key +
                    ", already created persistence broker instances: " + instanceCount);
            // useful for testing
            ++this.instanceCount;
        }

        PersistenceBrokerInternal instance = null;
        Class[] types = {PBKey.class, PersistenceBrokerFactoryIF.class};
        Object[] args = {key, this};
        try
        {
            instance = (PersistenceBrokerInternal) ClassHelper.newInstance(implementationClass, types, args);
            OjbConfigurator.getInstance().configure(instance);
            instance = (PersistenceBrokerInternal) InterceptorFactory.getInstance().createInterceptorFor(instance);
        }
        catch (Exception e)
        {
            log.error("Creation of a new PB instance failed", e);
            throw new PBFactoryException("Creation of a new PB instance failed", e);
        }
        return instance;
    }
1031895
public static QueryRunner createProxy(final DataSourceFactory dataSourceFactory) {
        final QueryRunnerInterceptor handler = new QueryRunnerInterceptor(dataSourceFactory);

        final Enhancer e = new Enhancer();

        // make sure we're Serializable and have a write replace method
        e.setInterfaces(new Class[] { Serializable.class, IWriteReplace.class });
        e.setSuperclass(QueryRunner.class);
        e.setCallback(handler);
        e.setNamingPolicy(new DefaultNamingPolicy() {
            @Override
            public String getClassName(final String prefix,
                                       final String source,
                                       final Object key,
                                       final Predicate names) {
                return super.getClassName("PROXY_" + prefix, source, key, names);
            }
        });

        LOG.trace("Created proxy for an EntityManager");

        return (QueryRunner)e.create();

    }
1126034
private Object[] readIdentities(Class pObjClass, Hashtable pMapping, 
                                    Hashtable pWhere, ObjectMapper pOM) 
        throws SQLException {
        sCacheUn++;
        // Build SQL query string
        if (pWhere == null)
            pWhere = new Hashtable();
	
        String[] keys = new String[pWhere.size()];
        int i = 0;
        for (Enumeration en = pWhere.keys(); en.hasMoreElements(); i++) {
            keys[i] = (String) en.nextElement();
        }

        // Get SQL for reading identity column
        String sql = pOM.buildIdentitySQL(keys)
            + buildWhereClause(keys, pMapping);

        // Log?
        mLog.logDebug(sql + " (" + pWhere + ")");

        // Prepare statement and set values
        PreparedStatement statement = mConnection.prepareStatement(sql);	
        for (int j = 0; j < keys.length; j++) {
            Object key =  pWhere.get(keys[j]);
	    
            if (key instanceof Integer)
                statement.setInt(j + 1, ((Integer) key).intValue());
            else if (key instanceof BigDecimal)
                statement.setBigDecimal(j + 1, (BigDecimal) key);
            else
                statement.setString(j + 1, key.toString());
        }
	
        // Execute query
        ResultSet rs = null;
        try {
            rs = statement.executeQuery();
        }
        catch (SQLException e) {
            mLog.logError(sql + " (" + pWhere + ")", e);
            throw e;
        }
        Vector result = new Vector();

        // Map query to objects
        while (rs.next()) {
            Object obj = null;
	    
            try {
                obj = pObjClass.newInstance();
            }
            catch (IllegalAccessException iae) {
                iae.printStackTrace();
            }
            catch (InstantiationException ie) {
                ie.printStackTrace();
            }
	    
            // Map it
            pOM.mapColumnProperty(rs, 1, 
                                  pOM.getProperty(pOM.getPrimaryKey()), obj);
            result.addElement(obj);
        }

        // Return array of identifiers
        return result.toArray((Object[]) Array.newInstance(pObjClass, 
                                                           result.size()));
    }
27653
public static Map<String, String> populatePersistenceUnitProperties(PropertyReader reader)
    {

        String dbType = reader.getProperty(EthConstants.DATABASE_TYPE);
        String host = reader.getProperty(EthConstants.DATABASE_HOST);
        String port = reader.getProperty(EthConstants.DATABASE_PORT);
        String dbName = reader.getProperty(EthConstants.DATABASE_NAME);

        propertyNullCheck(dbType, host, port, dbName);

        String username = reader.getProperty(EthConstants.DATABASE_USERNAME);
        String pswd = reader.getProperty(EthConstants.DATABASE_PASSWORD);

        Map<String, String> props = new HashMap<>();

        props.put(EthConstants.KUNDERA_CLIENT_LOOKUP_CLASS, getKunderaClientToLookupClass(dbType));
        props.put(EthConstants.KUNDERA_NODES, host);
        props.put(EthConstants.KUNDERA_PORT, port);
        props.put(EthConstants.KUNDERA_KEYSPACE, dbName);
        props.put(EthConstants.KUNDERA_DIALECT, dbType);

        if (username != null && !username.isEmpty() && pswd != null)
        {
            props.put(EthConstants.KUNDERA_USERNAME, username);
            props.put(EthConstants.KUNDERA_PASSWORD, pswd);
        }

        if (dbType.equalsIgnoreCase(CASSANDRA))
        {
            props.put(CQL_VERSION, _3_0_0);
        }

        boolean schemaAutoGen = Boolean.parseBoolean(reader.getProperty(EthConstants.SCHEMA_AUTO_GENERATE));
        boolean schemaDropExisting = Boolean.parseBoolean(reader.getProperty(EthConstants.SCHEMA_DROP_EXISTING));

        if (schemaAutoGen)
        {
            if (schemaDropExisting)
            {
                props.put(EthConstants.KUNDERA_DDL_AUTO_PREPARE, "create");
            }
            else
            {
                props.put(EthConstants.KUNDERA_DDL_AUTO_PREPARE, "update");
            }
        }
        LOGGER.info("Kundera properties : " + props);
        return props;
    }