return a prepared Select Statement for the given ClassDescriptor
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);
        }
    }
344497
public PreparedStatement prepareStatement(final String _string,
                                              final int _returnGeneratedKeys)
        throws SQLException
    {

        return getConnection().prepareStatement(_string, _returnGeneratedKeys);
    }
704293
public static void newSelectKeyMappedStatement(MappedStatement ms, EntityColumn column, Class<?> entityClass, Boolean executeBefore, String identity) {
        String keyId = ms.getId() + SelectKeyGenerator.SELECT_KEY_SUFFIX;
        if (ms.getConfiguration().hasKeyGenerator(keyId)) {
            return;
        }
        //defaults
        Configuration configuration = ms.getConfiguration();
        KeyGenerator keyGenerator;
        String IDENTITY = (column.getGenerator() == null || "".equals(column.getGenerator())) ? identity : column.getGenerator();
        if ("JDBC".equalsIgnoreCase(IDENTITY)) {
            keyGenerator = new Jdbc3KeyGenerator();
        } else {
            SqlSource sqlSource = new RawSqlSource(configuration, IDENTITY, entityClass);

            MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, keyId, sqlSource, SqlCommandType.SELECT);
            statementBuilder.resource(ms.getResource());
            statementBuilder.fetchSize(null);
            statementBuilder.statementType(StatementType.STATEMENT);
            statementBuilder.keyGenerator(new NoKeyGenerator());
            statementBuilder.keyProperty(column.getProperty());
            statementBuilder.keyColumn(null);
            statementBuilder.databaseId(null);
            statementBuilder.lang(configuration.getDefaultScriptingLanuageInstance());
            statementBuilder.resultOrdered(false);
            statementBuilder.resulSets(null);
            statementBuilder.timeout(configuration.getDefaultStatementTimeout());

            List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
            ParameterMap.Builder inlineParameterMapBuilder = new ParameterMap.Builder(
                    configuration,
                    statementBuilder.id() + "-Inline",
                    entityClass,
                    parameterMappings);
            statementBuilder.parameterMap(inlineParameterMapBuilder.build());

            List<ResultMap> resultMaps = new ArrayList<ResultMap>();
            ResultMap.Builder inlineResultMapBuilder = new ResultMap.Builder(
                    configuration,
                    statementBuilder.id() + "-Inline",
                    column.getJavaType(),
                    new ArrayList<ResultMapping>(),
                    null);
            resultMaps.add(inlineResultMapBuilder.build());
            statementBuilder.resultMaps(resultMaps);
            statementBuilder.resultSetType(null);

            statementBuilder.flushCacheRequired(false);
            statementBuilder.useCache(false);
            statementBuilder.cache(null);

            MappedStatement statement = statementBuilder.build();
            try {
                configuration.addMappedStatement(statement);
            } catch (Exception e) {
                //ignore
            }
            MappedStatement keyStatement = configuration.getMappedStatement(keyId, false);
            //如果单独设置了 order，使用 column 提供的，否则使用全局的
            keyGenerator = new SelectKeyGenerator(keyStatement, column.getOrder() != ORDER.DEFAULT ? (column.getOrder() == ORDER.BEFORE) : executeBefore);
            try {
                configuration.addKeyGenerator(keyId, keyGenerator);
            } catch (Exception e) {
                //ignore
            }
        }
        //keyGenerator
        try {
            MetaObject msObject = MetaObjectUtil.forObject(ms);
            msObject.setValue("keyGenerator", keyGenerator);
            msObject.setValue("keyProperties", column.getTable().getKeyProperties());
            msObject.setValue("keyColumns", column.getTable().getKeyColumns());
        } catch (Exception e) {
            //ignore
        }
    }
146558
protected SqlForClass getSqlForClass(ClassDescriptor cld)
    {
        SqlForClass result = (SqlForClass) sqlForClass.get(cld);
        if(result == null)
        {
            result = newInstanceSqlForClass();
            sqlForClass.put(cld, result);
        }
        return result;
    }
9361
public void bindUpdate(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws java.sql.SQLException
    {
        if (cld.getUpdateProcedure() != null)
        {
            this.bindProcedure(stmt, cld, obj, cld.getUpdateProcedure());
        }
        else
        {
            int index = 1;
            ValueContainer[] values, valuesSnapshot;
            // first take a snapshot of current locking values
            valuesSnapshot = cld.getCurrentLockingValues(obj);
            cld.updateLockingValues(obj); // BRJ
            values = getNonKeyValues(m_broker, cld, obj);

            // parameters for SET-clause
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
                index++;
            }
            // parameters for WHERE-clause pk
            values = getKeyValues(m_broker, cld, obj);
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
                index++;
            }
            // parameters for WHERE-clause locking
            // take old locking values
            values = valuesSnapshot;
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
                index++;
            }
        }
    }
58836
public @Nonnull
    ClassDescriptor getClassDescriptor(@SlashedClassName String className) {
        assert className.indexOf('.') == -1;
        ClassDescriptor classDescriptor = classDescriptorMap.get(className);
        if (classDescriptor == null) {
            if (MODULE_INFO.getClassName().equals(className)) {
                // don't allow module info to be added to the map,
                // which could be used to check referenced classes
                return MODULE_INFO;
            }
            classDescriptor = new ClassDescriptor(className);
            classDescriptorMap.put(className, classDescriptor);
        }
        return classDescriptor;
    }
429880
public <T> T queryForObject(String sql, Class<T> requiredType) throws SQLException {
		return queryForObject(sql, getSingleColumnRowMapper(requiredType));
	}
1230186
public static String selectCount(Class<?> entityClass) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass);
        if (pkColumns.size() == 1) {
            sql.append("COUNT(").append(pkColumns.iterator().next().getColumn()).append(") ");
        } else {
            sql.append("COUNT(*) ");
        }
        return sql.toString();
    }
1309086
private int bindStatement(PreparedStatement stmt, int index, ExistsCriteria crit, ClassDescriptor cld) throws SQLException
    {
        Query subQuery = (Query) crit.getValue();

        // if query has criteria, bind them
        if (subQuery.getCriteria() != null && !subQuery.getCriteria().isEmpty())
        {
            return bindStatement(stmt, subQuery.getCriteria(), cld.getRepository().getDescriptorFor(subQuery.getSearchClass()), index);

            // otherwise, just ignore it
        }
        else
        {
            return index;
        }
    }
735229
public void bindDelete(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws SQLException
    {
        if (cld.getDeleteProcedure() != null)
        {
            this.bindProcedure(stmt, cld, obj, cld.getDeleteProcedure());
        }
        else
        {
            int index = 1;
            ValueContainer[] values, currentLockingValues;

            currentLockingValues = cld.getCurrentLockingValues(obj);
            // parameters for WHERE-clause pk
            values = getKeyValues(m_broker, cld, obj);
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
                index++;
            }

            // parameters for WHERE-clause locking
            values = currentLockingValues;
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, index, values[i].getValue(), values[i].getJdbcType().getType());
                index++;
            }
        }
    }
1028498
private OJBIterator getRsIteratorFromQuery(Query query, ClassDescriptor cld, RsIteratorFactory factory)
        throws PersistenceBrokerException
    {
        query.setFetchSize(1);
        if (query instanceof QueryBySQL)
        {
            if(logger.isDebugEnabled()) logger.debug("Creating SQL-RsIterator for class ["+cld.getClassNameOfObject()+"]");
            return factory.createRsIterator((QueryBySQL) query, cld, this);
        }

        if (!cld.isExtent() || !query.getWithExtents())
        {
            // no extents just use the plain vanilla RsIterator
            if(logger.isDebugEnabled()) logger.debug("Creating RsIterator for class ["+cld.getClassNameOfObject()+"]");

            return factory.createRsIterator(query, cld, this);
        }

        if(logger.isDebugEnabled()) logger.debug("Creating ChainingIterator for class ["+cld.getClassNameOfObject()+"]");

        ChainingIterator chainingIter = new ChainingIterator();

        // BRJ: add base class iterator
        if (!cld.isInterface())
        {
            if(logger.isDebugEnabled()) logger.debug("Adding RsIterator for class ["+cld.getClassNameOfObject()+"] to ChainingIterator");

            chainingIter.addIterator(factory.createRsIterator(query, cld, this));
        }

        Iterator extents = getDescriptorRepository().getAllConcreteSubclassDescriptors(cld).iterator();
        while (extents.hasNext())
        {
            ClassDescriptor extCld = (ClassDescriptor) extents.next();

            // read same table only once
            if (chainingIter.containsIteratorForTable(extCld.getFullTableName()))
            {
                if(logger.isDebugEnabled()) logger.debug("Skipping class ["+extCld.getClassNameOfObject()+"]");
            }
            else
            {
                if(logger.isDebugEnabled()) logger.debug("Adding RsIterator of class ["+extCld.getClassNameOfObject()+"] to ChainingIterator");

                // add the iterator to the chaining iterator.
                chainingIter.addIterator(factory.createRsIterator(query, extCld, this));
            }
        }

        return chainingIter;
    }
1148215
private function prepareConstructor()
    {
        $table_descriptor = $this->getStorageDescriptor();

        $fragment = new CNabuPHPConstructorBuilder($this);
        $fragment->addComment(
                "Instantiates the class. If you fill enough parameters to identify an instance "
              . "serialized in the storage, then the instance is deserialized from the storage.");
        if ($table_descriptor->hasPrimaryConstraint()) {
            foreach ($table_descriptor->getPrimaryConstraintFieldNames() as $field_name) {
                if (nb_strEndsWith($field_name, '_id')) {
                    $var_name = substr($field_name, 0, strlen($field_name) - 3);
                } else {
                    $var_name = $field_name;
                }
                $fragment->addParam(
                        $var_name, null, true, false, 'mixed',
                        "An instance of $this->class_name or another object descending from "
                      . "\\nabu\\data\\CNabuDataObject which contains a field named $field_name,"
                      . " or a valid ID.");
                $fragment->addFragment(
                        array(
                            "if (\$$var_name) {",
                            "    \$this->transferMixedValue(\$$var_name, '$field_name');",
                            "}",
                            ''
                        )
                );
            }
        }
        $fragment->addFragment('parent::__construct();');

        if ($this->is_translated) {
            $list_name = preg_replace('/Base$/', 'LanguageList', $this->class_name);
            $list_ns = preg_replace('/\\\\base/', '', $this->class_namespace);
            $fragment->addFragment('$this->__translatedConstruct();');
            $fragment->addFragment("\$this->translations_list = new $list_name();");
            $this->getDocument()->addUse("\\$list_ns\\$list_name");
        }

        $this->addFragment($fragment);
    }
518821
public int executeUpdateSQL(
        String sqlStatement,
        ClassDescriptor cld,
        ValueContainer[] values1,
        ValueContainer[] values2)
        throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
            logger.debug("executeUpdateSQL: " + sqlStatement);

        int result;
        int index;
        PreparedStatement stmt = null;
        final StatementManagerIF sm = broker.serviceStatementManager();
        try
        {
            stmt = sm.getPreparedStatement(cld, sqlStatement,
                    Query.NOT_SCROLLABLE, StatementManagerIF.FETCH_SIZE_NOT_APPLICABLE, isStoredProcedure(sqlStatement));
            index = sm.bindValues(stmt, values1, 1);
            sm.bindValues(stmt, values2, index);
            result = stmt.executeUpdate();
        }
        catch (PersistenceBrokerException e)
        {
            logger.error("PersistenceBrokerException during the execution of the Update SQL query: " + e.getMessage(), e);
            throw e;
        }
        catch (SQLException e)
        {
            ValueContainer[] tmp = addValues(values1, values2);
            throw ExceptionHelper.generateException(e, sqlStatement, cld, tmp, logger, null);
        }
        finally
        {
            sm.closeResources(stmt, null);
        }
        return result;
    }
131098
public void bindDelete(PreparedStatement stmt, Identity oid, ClassDescriptor cld) throws SQLException
    {
        Object[] pkValues = oid.getPrimaryKeyValues();
        FieldDescriptor[] pkFields = cld.getPkFields();
        int i = 0;
        try
        {
            for (; i < pkValues.length; i++)
            {
                setObjectForStatement(stmt, i + 1, pkValues[i], pkFields[i].getJdbcType().getType());
            }
        }
        catch (SQLException e)
        {
            m_log.error("bindDelete failed for: " + oid.toString() + ", while set value '" +
                    pkValues[i] + "' for column " + pkFields[i].getColumnName());
            throw e;
        }
    }
1282884
def _select(self, tree, allow_select_scan):
        
        tablename = tree.table
        desc = self.describe(tablename, require=True)
        kwargs = {}
        if tree.consistent:
            kwargs["consistent"] = True

        visitor = Visitor(self.reserved_words)

        selection = SelectionExpression.from_selection(tree.attrs)
        if selection.is_count:
            kwargs["select"] = "COUNT"

        if tree.keys_in:
            if tree.limit:
                raise SyntaxError("Cannot use LIMIT with KEYS IN")
            elif tree.using:
                raise SyntaxError("Cannot use USING with KEYS IN")
            elif tree.order:
                raise SyntaxError("Cannot use DESC/ASC with KEYS IN")
            elif tree.where:
                raise SyntaxError("Cannot use WHERE with KEYS IN")
            keys = list(self._iter_where_in(tree))
            kwargs["attributes"] = selection.build(visitor)
            kwargs["alias"] = visitor.attribute_names
            return self.connection.batch_get(tablename, keys=keys, **kwargs)

        if tree.limit:
            if tree.scan_limit:
                kwargs["limit"] = Limit(
                    scan_limit=resolve(tree.scan_limit[2]),
                    item_limit=resolve(tree.limit[1]),
                    strict=True,
                )
            else:
                kwargs["limit"] = Limit(item_limit=resolve(tree.limit[1]), strict=True)
        elif tree.scan_limit:
            kwargs["limit"] = Limit(scan_limit=resolve(tree.scan_limit[2]))

        (action, query_kwargs, index) = self._build_query(desc, tree, visitor)
        if action == "scan" and not allow_select_scan:
            raise SyntaxError(
                "No index found for query. Please use a SCAN query, or "
                "set allow_select_scan=True\nopt allow_select_scan true"
            )
        order_by = None
        if tree.order_by:
            order_by = tree.order_by[0]
        reverse = tree.order == "DESC"
        if tree.order:
            if action == "scan" and not tree.order_by:
                raise SyntaxError(
                    "No index found for query, "
                    "cannot use ASC or DESC without "
                    "ORDER BY <field>"
                )
            if action == "query":
                if order_by is None or order_by == index.range_key:
                    kwargs["desc"] = reverse

        kwargs.update(query_kwargs)

        # This is a special case for when we're querying an index and selecting
        # fields that aren't projected into the index.
        # We will change the query to only fetch the primary keys, and then
        # fill in the selected attributes after the fact.
        fetch_attrs_after = False
        if index is not None and not index.projects_all_attributes(
            selection.all_fields
        ):
            kwargs["attributes"] = [
                visitor.get_field(a) for a in desc.primary_key_attributes
            ]
            fetch_attrs_after = True
        else:
            kwargs["attributes"] = selection.build(visitor)
        kwargs["expr_values"] = visitor.expression_values
        kwargs["alias"] = visitor.attribute_names

        method = getattr(self.connection, action + "2")
        result = method(tablename, **kwargs)

        # If the queried index didn't project the selected attributes, we need
        # to do a BatchGetItem to fetch all the data.
        if fetch_attrs_after:
            if not isinstance(result, list):
                result = list(result)
            # If no results, no need to batch_get
            if not result:
                return result
            visitor = Visitor(self.reserved_words)
            kwargs = {"keys": [desc.primary_key(item) for item in result]}
            kwargs["attributes"] = selection.build(visitor)
            kwargs["alias"] = visitor.attribute_names
            result = self.connection.batch_get(tablename, **kwargs)

        def order(items):
            """ Sort the items by the specified keys """
            if order_by is None:
                return items
            if index is None or order_by != index.range_key:
                if not isinstance(items, list):
                    items = list(items)
                items.sort(key=lambda x: x.get(order_by), reverse=reverse)
            return items

        # Save the data to a file
        if tree.save_file:
            if selection.is_count:
                raise Exception("Cannot use count(*) with SAVE")
            count = 0
            result = order(selection.convert(item, True) for item in result)
            filename = tree.save_file[0]
            if filename[0] in ['"', "'"]:
                filename = unwrap(filename)
            # If it's still an iterator, convert to a list so we can iterate
            # multiple times.
            if not isinstance(result, list):
                result = list(result)
            remainder, ext = os.path.splitext(filename)
            if ext.lower() in [".gz", ".gzip"]:
                ext = os.path.splitext(remainder)[1]
                opened = gzip.open(filename, "wb")
            else:
                opened = open(filename, "wb")
            if ext.lower() == ".csv":
                if selection.all_keys:
                    headers = selection.all_keys
                else:
                    # Have to do this to get all the headers :(
                    result = list(result)
                    all_headers = set()
                    for item in result:
                        all_headers.update(item.keys())
                    headers = list(all_headers)
                with opened as ofile:
                    writer = csv.DictWriter(
                        ofile, fieldnames=headers, extrasaction="ignore"
                    )
                    writer.writeheader()
                    for item in result:
                        count += 1
                        writer.writerow(item)
            elif ext.lower() == ".json":
                with opened as ofile:
                    for item in result:
                        count += 1
                        ofile.write(self._encoder.encode(item))
                        ofile.write("\n")
            else:
                with opened as ofile:
                    for item in result:
                        count += 1
                        pickle.dump(item, ofile)
            return count
        elif not selection.is_count:
            result = order(selection.convert(item) for item in result)

        return result
359147
Object _getDataService(T session, Class cls) throws DataServiceException {
		String dataServiceClassName = cls.getName();
		DataService dataServiceAnno = (DataService) cls.getAnnotation(DataService.class);
		IDataServiceResolver resolver = getResolver(dataServiceAnno.resolver());
		Scope scope = resolver.getScope(cls);
		Object dataService = null;
		Map<String, Object> sessionBeans = getSessionBeans(session);
		logger.debug("{} : scope : {}", dataServiceClassName, scope);
		if (scope.equals(Scope.SESSION)) {
			dataService = sessionBeans.get(dataServiceClassName);
			logger.debug("{} : scope : session is in session : {}", dataServiceClassName, (dataService != null));
		}
		if (dataService == null) {
			dataService = resolver.resolveDataService(cls);
			if (scope.equals(Scope.SESSION)) {
				logger.debug("Store {} scope session in session", dataServiceClassName);
				sessionBeans.put(dataServiceClassName, dataService);
			}
		}
		return dataService;
	}
1289008
public void bindInsert(PreparedStatement stmt, ClassDescriptor cld, Object obj) throws java.sql.SQLException
    {
        ValueContainer[] values;
        cld.updateLockingValues(obj); // BRJ : provide useful defaults for locking fields

        if (cld.getInsertProcedure() != null)
        {
            this.bindProcedure(stmt, cld, obj, cld.getInsertProcedure());
        }
        else
        {
            values = getAllValues(cld, obj);
            for (int i = 0; i < values.length; i++)
            {
                setObjectForStatement(stmt, i + 1, values[i].getValue(), values[i].getJdbcType().getType());
            }
        }
    }