Add tableGenerator to table info.

@param appMetadata
@param persistenceUnit
@param tableInfos
@param entityMetadata
@param isCompositeId
423649
private void addTableGenerator(ApplicationMetadata appMetadata, String persistenceUnit, List<TableInfo> tableInfos,
            EntityMetadata entityMetadata)
    {
        Metamodel metamodel = appMetadata.getMetamodel(persistenceUnit);
        IdDiscriptor keyValue = ((MetamodelImpl) metamodel).getKeyValue(entityMetadata.getEntityClazz().getName());
        if (keyValue != null && keyValue.getTableDiscriptor() != null)
        {
            TableInfo tableGeneratorDiscriptor = new TableInfo(keyValue.getTableDiscriptor().getTable(),
                    "CounterColumnType", String.class, keyValue.getTableDiscriptor().getPkColumnName());
            if (!tableInfos.contains(tableGeneratorDiscriptor))
            {
                tableGeneratorDiscriptor.addColumnInfo(getJoinColumn(tableGeneratorDiscriptor,
                        keyValue.getTableDiscriptor().getValueColumnName(), Long.class));
                tableInfos.add(tableGeneratorDiscriptor);
            }
        }
    }
688762
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> relations)
    {
        String tableName = HBaseUtils.getHTableName(entityMetadata.getSchema(), entityMetadata.getTableName());
        try
        {
            handler.writeData(tableName, entityMetadata, entity, id, relations, showQuery);
        }
        catch (IOException e)
        {
            throw new PersistenceException(e);
        }
    }
527518
protected void processMetadataInitialization(HttpServletRequest request) throws ServletException {

        // In case the hosted IdP metadata weren't initialized, let's do it now
        if (manager.getHostedIdpName() == null) {

            synchronized (IdpMetadataManager.class) {

                if (manager.getHostedIdpName() == null) {

                    try {

                        log.info(
                                "No default metadata configured, generating with default values, please pre-configure metadata for production use");

                        // Defaults
                        String alias = generator.getEntityAlias();
                        String baseURL = getDefaultBaseURL(request);

                        // Use default baseURL if not set
                        if (generator.getEntityBaseURL() == null) {
                            log.warn(
                                    "Generated default entity base URL {} based on values in the first server request. Please set property entityBaseURL on MetadataGenerator bean to fixate the value.",
                                    baseURL);
                            generator.setEntityBaseURL(baseURL);
                        } else {
                            baseURL = generator.getEntityBaseURL();
                        }

                        // Use default entityID if not set
                        if (generator.getEntityId() == null) {
                            generator.setEntityId(getDefaultEntityID(baseURL, alias));
                        }

                        // Ensure supported nameID formats in uaa are listed in the metadata
                        Collection<String> supportedNameID = Arrays.asList(NameIDType.EMAIL, NameIDType.PERSISTENT,
                                NameIDType.UNSPECIFIED);
                        generator.setNameID(supportedNameID);

                        EntityDescriptor descriptor = generator.generateMetadata();
                        ExtendedMetadata extendedMetadata = generator.generateExtendedMetadata();

                        log.info("Created default metadata for system with entityID: " + descriptor.getEntityID());
                        MetadataMemoryProvider memoryProvider = new MetadataMemoryProvider(descriptor);
                        memoryProvider.initialize();
                        MetadataProvider metadataProvider = new ExtendedMetadataDelegate(memoryProvider,
                                extendedMetadata);

                        manager.addMetadataProvider(metadataProvider);
                        manager.setHostedIdpName(descriptor.getEntityID());
                        manager.refreshMetadata();

                    } catch (MetadataProviderException e) {
                        log.error("Error generating system metadata", e);
                        throw new ServletException("Error generating system metadata", e);
                    }

                }

            }

        }

    }
559007
public static void generate(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
		InsertType insertResultType = detectInsertType(method);

		// if true, field must be associate to ben attributes
		TypeName returnType = method.getReturnClass();

		AssertKripton.failWithInvalidMethodSignException(insertResultType == null, method);

		// generate method code
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC);

		ParameterSpec parameterSpec;
		for (Pair<String, TypeName> item : method.getParameters()) {
			parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
			methodBuilder.addParameter(parameterSpec);
		}
		methodBuilder.returns(returnType);

		// fail if we use jql to INSERT_BEAN with operation of INSERT-FOR-SELECT
		// AssertKripton.failWithInvalidMethodSignException(insertResultType ==
		// InsertType.INSERT_BEAN && method.jql.containsSelectOperation, method,
		// "INSERT-FROM-SELECT SQL can not be used with method sign");

		// generate inner code
		methodBuilder.addComment("Specialized Insert - $L - BEGIN", insertResultType.getClass().getSimpleName());
		insertResultType.generate(classBuilder, methodBuilder, method, returnType);
		methodBuilder.addComment("Specialized Insert - $L - END", insertResultType.getClass().getSimpleName());

		MethodSpec methodSpec = methodBuilder.build();
		classBuilder.addMethod(methodSpec);

		if (method.contentProviderEntryPathEnabled) {
			// we need to generate insert for content provider to
			generateInsertForContentProvider(classBuilder, method, insertResultType);
		}

	}
1045795
private static <T, ID> void addCreateTableStatements(DatabaseType databaseType, TableInfo<T, ID> tableInfo,
			List<String> statements, List<String> queriesAfter, boolean ifNotExists, boolean logDetails)
			throws SQLException {
		StringBuilder sb = new StringBuilder(256);
		if (logDetails) {
			logger.info("creating table '{}'", tableInfo.getTableName());
		}
		sb.append("CREATE TABLE ");
		if (ifNotExists && databaseType.isCreateIfNotExistsSupported()) {
			sb.append("IF NOT EXISTS ");
		}
		databaseType.appendEscapedEntityName(sb, tableInfo.getTableName());
		sb.append(" (");
		List<String> additionalArgs = new ArrayList<String>();
		List<String> statementsBefore = new ArrayList<String>();
		List<String> statementsAfter = new ArrayList<String>();
		// our statement will be set here later
		boolean first = true;
		for (FieldType fieldType : tableInfo.getFieldTypes()) {
			// skip foreign collections
			if (fieldType.isForeignCollection()) {
				continue;
			} else if (first) {
				first = false;
			} else {
				sb.append(", ");
			}
			String columnDefinition = fieldType.getColumnDefinition();
			if (columnDefinition == null) {
				// we have to call back to the database type for the specific create syntax
				databaseType.appendColumnArg(tableInfo.getTableName(), sb, fieldType, additionalArgs, statementsBefore,
						statementsAfter, queriesAfter);
			} else {
				// hand defined field
				databaseType.appendEscapedEntityName(sb, fieldType.getColumnName());
				sb.append(' ').append(columnDefinition).append(' ');
			}
		}
		// add any sql that sets any primary key fields
		databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,
				queriesAfter);
		// add any sql that sets any unique fields
		databaseType.addUniqueComboSql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, statementsAfter,
				queriesAfter);
		for (String arg : additionalArgs) {
			// we will have spat out one argument already so we don't have to do the first dance
			sb.append(", ").append(arg);
		}
		sb.append(") ");
		databaseType.appendCreateTableSuffix(sb);
		statements.addAll(statementsBefore);
		statements.add(sb.toString());
		statements.addAll(statementsAfter);
		addCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, false, logDetails);
		addCreateIndexStatements(databaseType, tableInfo, statements, ifNotExists, true, logDetails);
	}
1302730
public static void generateGenericExecSQL(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method) {

		boolean nullable;
		final List<String> paramsList = new ArrayList<String>();
		final List<String> contentValueList = new ArrayList<String>();
		final One<Boolean> columnsToUpdate = new One<Boolean>(true);

		String sql = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public void onWhereStatementBegin(Where_stmtContext ctx) {
				super.onWhereStatementBegin(ctx);

				columnsToUpdate.value0 = false;
			}

			@Override
			public void onWhereStatementEnd(Where_stmtContext ctx) {
				super.onWhereStatementEnd(ctx);

				columnsToUpdate.value0 = true;
			}

			@Override
			public String onColumnName(String columnName) {
				String resolvedName = currentSchema.findColumnNameByPropertyName(method, columnName);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(resolvedName != null, method, columnName);

				return resolvedName;

			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				String propertyName = method.findParameterAliasByName(bindParameterName);

				if (columnsToUpdate.value0) {
					contentValueList.add(propertyName);
				} else {
					paramsList.add(propertyName);
				}
				return "?";
			}
		});

		// update/insert columns
		final SQLiteEntity entity = method.getEntity();
		for (String item : contentValueList) {
			// ASSERT: property is always in entity
			String propertyName = method.findParameterNameByAlias(item);
			TypeName paramType = method.findParameterTypeByAliasOrName(item);

			SQLProperty property = entity.get(item);

			if (propertyName == null)
				throw (new PropertyNotFoundException(method, propertyName, paramType));

			Pair<String, TypeName> methodParam = new Pair<String, TypeName>(propertyName, paramType);

			// check same type
			TypeUtility.checkTypeCompatibility(method, methodParam, property);
			// check nullabliity
			// nullable = TypeUtility.isNullable(method, methodParam, property);
			//
			// if (nullable) {
			// // it use raw method param's typeName
			// methodBuilder.beginControlFlow("if ($L!=null)", methodParam.value0);
			// }

			if (method.isLogEnabled()) {
				methodBuilder.addCode("_contentValues.put($S, ", property.columnName);
			} else {
				methodBuilder.addCode("_contentValues.put(");
			}

			// it does not need to be converted in string
			SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, methodParam.value0, methodParam.value1,
					property);
			methodBuilder.addCode(");\n");
			// if (nullable) {
			// methodBuilder.nextControlFlow("else");
			//
			// if (method.isLogEnabled()) {
			// methodBuilder.addStatement("_contentValues.putNull($S)", property.columnName);
			// } else {
			// methodBuilder.addStatement("_contentValues.putNull()");
			// }
			//
			// methodBuilder.endControlFlow();
			// }

		}

		// where condition
		methodBuilder.addComment("build where condition");
		{
			// String separator = "";
			TypeName paramType;
			String realName;

			for (String item : paramsList) {
				methodBuilder.addCode("_contentValues.addWhereArgs(");

				paramType = method.findParameterTypeByAliasOrName(item);
				realName = method.findParameterNameByAlias(item);

				AssertKripton.assertTrueOrUnknownPropertyInJQLException(paramType != null, method, item);

				// code for query arguments
				nullable = TypeUtility.isNullable(paramType);
				if (nullable) {
					methodBuilder.addCode("($L==null?\"\":", realName);
				}

				// check for string conversion
				TypeUtility.beginStringConversion(methodBuilder, paramType);

				SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, realName, paramType, null);

				// check for string conversion
				TypeUtility.endStringConversion(methodBuilder, paramType);

				if (nullable) {
					methodBuilder.addCode(")");
				}

				methodBuilder.addCode(");\n");
			}
		}

		// log for where parames
		SqlBuilderHelper.generateLog(method, methodBuilder);

		// log
		methodBuilder.addCode("\n");
		methodBuilder.addStatement("database().execSQL($S, _contentValues.whereArgsAsArray())", sql);
	}
1110406
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        if (!isUpdate)
        {
            r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
                    .insert(populateRmap(entityMetadata, entity)).run(connection);
        }
        else
        {
            r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
                    .update(populateRmap(entityMetadata, entity)).run(connection);
        }
    }
1302361
protected void update(List<TableInfo> tableInfos)
    {
        try
        {
            createOrUpdateKeyspace(tableInfos);
        }
        catch (Exception ex)
        {
            log.error("Error occurred while creating {}, Caused by: .", databaseName, ex);
            throw new SchemaGenerationException(ex);
        }
    }
1273528
private void createCellsAndAddToRow(Object entity, MetamodelImpl metaModel, Set<Attribute> attributes,
            HBaseRow hbaseRow, EntityMetadata m, int count, String prefix)
    {
        AbstractAttribute idCol = (AbstractAttribute) m.getIdAttribute();
        for (Attribute attribute : attributes)
        {
            AbstractAttribute absAttrib = (AbstractAttribute) attribute;
            Class clazz = absAttrib.getBindableJavaType();
            if (metaModel.isEmbeddable(clazz))
            {
                Set<Attribute> attribEmbeddables = metaModel.embeddable(absAttrib.getBindableJavaType())
                        .getAttributes();
                Object embeddedField = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
                if (attribute.isCollection() && embeddedField != null)
                {
                    int newCount = count + 1;
                    String newPrefix = prefix != "" ? prefix + absAttrib.getJPAColumnName() + HBaseUtils.DELIM
                            : absAttrib.getJPAColumnName() + HBaseUtils.DELIM;
                    List listOfEmbeddables = (List) embeddedField;
                    addColumnForCollectionSize(hbaseRow, listOfEmbeddables.size(), newPrefix, m.getTableName());
                    for (Object obj : listOfEmbeddables)
                    {
                        createCellsAndAddToRow(obj, metaModel, attribEmbeddables, hbaseRow, m, newCount++, newPrefix);
                    }
                }
                else if (embeddedField != null)
                {
                    String newPrefix = prefix != "" ? prefix + absAttrib.getJPAColumnName() + HBaseUtils.DOT
                            : absAttrib.getJPAColumnName() + HBaseUtils.DOT;
                    createCellsAndAddToRow(embeddedField, metaModel, attribEmbeddables, hbaseRow, m, count, newPrefix);
                }
            }
            else if (!attribute.isCollection() && !attribute.isAssociation())
            {
                String columnFamily = absAttrib.getTableName() != null ? absAttrib.getTableName() : m.getTableName();
                String columnName = absAttrib.getJPAColumnName();
                columnName = count != -1 ? prefix + columnName + HBaseUtils.DELIM + count : prefix + columnName;
                Object value = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
                HBaseCell hbaseCell = new HBaseCell(columnFamily, columnName, value);
                if (!idCol.getName().equals(attribute.getName()) && value != null)
                {
                    hbaseRow.addCell(hbaseCell);
                }
            }
        }
    }
1175195
private Object onTableGenerator(EntityMetadata m, Client<?> client, IdDiscriptor keyValue, Object e)
    {
        Object tablegenerator = getAutoGenClazz(client);   
        if (tablegenerator instanceof TableGenerator)
        {
            Object generatedId = ((TableGenerator) tablegenerator).generate(keyValue.getTableDiscriptor(),
                    (ClientBase) client, m.getIdAttribute().getJavaType().getSimpleName());
            try
            {
                generatedId = PropertyAccessorHelper.fromSourceToTargetClass(m.getIdAttribute().getJavaType(),
                        generatedId.getClass(), generatedId);
                PropertyAccessorHelper.setId(e, m, generatedId);
                return generatedId;
            }
            catch (IllegalArgumentException iae)
            {
                log.error("Unknown integral data type for ids : " + m.getIdAttribute().getJavaType());
                throw new KunderaException("Unknown integral data type for ids : " + m.getIdAttribute().getJavaType(),
                        iae);
            }
        }
        throw new IllegalArgumentException(GenerationType.class.getSimpleName() + "." + GenerationType.TABLE
                + " Strategy not supported by this client :" + client.getClass().getName());
    }
1246768
private static void setSchemaAndPU(Class<?> clazz, EntityMetadata metadata)
    {
        Table table = clazz.getAnnotation(Table.class);
        if (table != null)
        {
            metadata.setTableName(!StringUtils.isBlank(table.name()) ? table.name() : clazz.getSimpleName());
            String schemaStr = table.schema();

            MetadataUtils.setSchemaAndPersistenceUnit(metadata, schemaStr,
                    em.getEntityManagerFactory().getProperties());
        }
        else
        {
            metadata.setTableName(clazz.getSimpleName());
            metadata.setSchema((String) em.getEntityManagerFactory().getProperties().get("kundera.keyspace"));
        }

        if (metadata.getPersistenceUnit() == null)
        {
            metadata.setPersistenceUnit(getPersistenceUnit());
        }
    }
808120
@Override
    public void init(DataGenerator dataGenerator) throws Exception
    {
        try
        {
            this.dataGenerator = dataGenerator;
            this.cluster = cassA6XManager.registerCluster(config.getCluster(), config.getHost(), config.getHostPort());
            this.keyspace = cassA6XManager.registerKeyspace(config.getCluster(), config.getKeyspace(), config.getHost(), config.getHostPort());

            AstyanaxConfigurationImpl aci = (AstyanaxConfigurationImpl) this.keyspace.getConfig();
            aci.setDefaultReadConsistencyLevel(ConsistencyLevel.valueOf(config.getReadConsistencyLevel()))
               .setDefaultWriteConsistencyLevel(ConsistencyLevel.valueOf(config.getWriteConsistencyLevel()));

            CF = new ColumnFamily<>(config.getCfname(), StringSerializer.get(), IntegerSerializer.get(), StringSerializer.get());

            if (config.getCreateSchema())
            {
                logger.info("Trying to upsert schema");
                preInit();
            }
        }
        catch (ConnectionException e)
        {
            logger.error("Failed to initialize Astyanax driver");
            throw e;
        }

        logger.info("Registered keyspace : " + this.keyspace.getKeyspaceName());
        logger.info("Initialized CassAstyanaxPlugin");
    }
9946
public int insertMetaBeanById(String tableName, MicroMetaBean microMetaBean) {
		//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
		JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
		final MicroMetaBean insertBean=microMetaBean;
		String timeName=getTimeName();
		String sql = "insert into " + tableName +"(id,meta_content,meta_key,meta_name,meta_type,remark,create_time,update_time) values(?,?,?,?,?,?,"+timeName+","+timeName+") ";
		List paramList=new ArrayList();
		paramList.add(insertBean.getId());
		paramList.add(insertBean.getMeta_content());
		paramList.add(insertBean.getMeta_key());
		paramList.add(insertBean.getMeta_name());
		paramList.add(insertBean.getMeta_type());
		paramList.add(insertBean.getRemark());
		logger.debug(sql);
		logger.debug(paramList.toArray());
		Integer retStatus=jdbcTemplate.update(sql,paramList.toArray());

		return retStatus;
	}
547860
public void tableGenerator(String name, String tableName, String pkColumnName, String valueColumnName,
			String pkColumnValue, Integer initialValue, Integer allocationSize) {
		checkReadOnly();
		addGenerator(new TableIdGenerator(name, tableName, pkColumnName, valueColumnName, pkColumnValue, initialValue,
				allocationSize));
	}
186448
private TableDefinition addAutoTable(ApplicationDefinition appDef, String tableName) {
        m_logger.debug("Adding implicit table '{}' to application '{}'", tableName, appDef.getAppName());
        Tenant tenant = Tenant.getTenant(appDef);
        TableDefinition tableDef = new TableDefinition(appDef);
        tableDef.setTableName(tableName);
        appDef.addTable(tableDef);
        SchemaService.instance().defineApplication(tenant, appDef);
        appDef = SchemaService.instance().getApplication(tenant, appDef.getAppName());
        return appDef.getTableDef(tableName);
    }
643334
private void searchAndAddToResults(EntityMetadata m, String persistenceUnit, ConsistencyLevel consistencyLevel,
            String columnFamilyName, List<SearchResult> searchResults, IndexExpression expression, boolean isRowKeyQuery)
    {
        SearchResult searchResult = new SearchResult();

        byte[] superColumnName = expression.getValue();
        String superColumnNameStr = null;
        String rowKey = null;
        try
        {
            rowKey = ByteBufferUtil.string(ByteBuffer.wrap(expression.getColumn_name()),
                    Charset.forName(Constants.CHARSET_UTF8));
            superColumnNameStr = new String(expression.getValue(), Charset.forName(Constants.CHARSET_UTF8));
        }
        catch (CharacterCodingException e)
        {
            log.error("Error while retrieving records {}, Caused by:", e);
            throw new PersistenceException(e);
        }
        Object pk = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), superColumnName);
        IndexOperator condition = expression.getOp();

        if (log.isInfoEnabled())
        {
            log.info("RowKey: {} ; Super column Name: {} on condition.", rowKey, superColumnNameStr, condition);
        }

        // TODO: Second check unnecessary but unavoidable as filter clause
        // property is incorrectly passed as column name

        // Search based on Primary key
        if (isRowKeyQuery
                && (rowKey.equals(m.getIdAttribute().getName()) || rowKey.equals(((DefaultSingularAttribute) m
                        .getIdAttribute()).getJPAColumnName())))
        {
            if (searchResults.isEmpty())
            {
                searchResult.setPrimaryKey(pk);
                searchResults.add(searchResult);
            }
            else
            {
                SearchResult existing = searchResults.get(0);
                if (existing.getPrimaryKey() != null && existing.getPrimaryKey().equals(superColumnNameStr))
                {
                    searchResults.add(searchResult);
                }
                else
                {
                    searchResults.remove(0);
                }
            }
        }
        else
        {
            // Search results in the form of thrift super columns
            List<SuperColumn> thriftSuperColumns = new ArrayList<SuperColumn>();

            switch (condition)
            {
            // EQUAL Operator
            case EQ:
                SuperColumn thriftSuperColumn = getSuperColumnForRow(consistencyLevel, columnFamilyName, rowKey,
                        superColumnName, persistenceUnit);

                if (thriftSuperColumn != null)
                    thriftSuperColumns.add(thriftSuperColumn);
                break;

            // LIKE operation not available
            // Greater than operator
            case GT:
                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,
                        thriftSuperColumns, superColumnName, new byte[0]);
                break;
            // Less than Operator
            case LT:
                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,
                        thriftSuperColumns, new byte[0], superColumnName);
                break;
            // Greater than-equals to operator
            case GTE:
                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,
                        thriftSuperColumns, superColumnName, new byte[0]);
                break;
            // Less than equal to operator
            case LTE:
                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,
                        thriftSuperColumns, new byte[0], superColumnName);
                break;

            default:
                throw new QueryHandlerException(condition
                        + " comparison operator not supported currently for Cassandra Inverted Index.");
            }

            // Construct search results out of these thrift columns
            for (SuperColumn thriftSuperColumn : thriftSuperColumns)
            {

                for (Column column : thriftSuperColumn.getColumns())
                {
                    byte[] columnName = column.getName();
                    searchResult.setPrimaryKey(PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(),
                            columnName));
                    byte[] columnValue = column.getValue();
                    String ecValue = UTF8Type.instance.compose(ByteBuffer.wrap(columnValue));

                    if (ecValue != null && !"".equals(ecValue.trim()))
                    {
                        searchResult.setEmbeddedColumnName(rowKey.substring(0,
                                rowKey.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER)));
                        searchResult.addEmbeddedColumnValue(ecValue);
                    }
                }

                if (searchResults.isEmpty())
                {
                    searchResults.add(searchResult);
                }
                else
                {
                    SearchResult existing = searchResults.get(0);
                    if (existing.getPrimaryKey() != null
                            && existing.getPrimaryKey().equals(searchResult.getPrimaryKey()))
                    {
                        searchResults.add(searchResult);
                    }
                    else
                    {
                        searchResults.remove(0);
                    }
                }

            }
        }
    }
410539
void insert(boolean readOnly, int generation) throws PersistException {
        if (mAllProperties == null) {
            throw new IllegalStateException();
        }

        mStoredLayout.setGeneration(generation);

        if (readOnly) {
            return;
        }

        try {
            mStoredLayout.insert();
        } catch (UniqueConstraintException e) {
            // If existing record logically matches, update to allow replication.
            StoredLayout existing = mStoredLayout.prepare();
            mStoredLayout.copyPrimaryKeyProperties(existing);
            try {
                existing.load();
            } catch (FetchException e2) {
                throw e2.toPersistException();
            }
            if (existing.getGeneration() != generation ||
                !existing.getStorableTypeName().equals(getStorableTypeName()) ||
                !Arrays.equals(existing.getExtraData(), mStoredLayout.getExtraData()))
            {
                throw e;
            }
            mStoredLayout.setVersionNumber(existing.getVersionNumber());
            mStoredLayout.update();
        }

        for (LayoutProperty property : mAllProperties) {
            property.insert();
        }
    }