通过xmlSql创建sqlSource

@param ms
@param xmlSql
@return
355249
public SqlSource createSqlSource(MappedStatement ms, String xmlSql) {
        return languageDriver.createSqlSource(ms.getConfiguration(), "<script>\n\t" + xmlSql + "</script>", null);
    }
1274991
protected ExposedParsedSql getParsedSql(String sql) {
		if (getCacheLimit() <= 0) {
			return new ExposedParsedSql( NamedParameterUtils.parseSqlStatement(sql) );
		}
		synchronized (this.parsedSqlCache) {
			ExposedParsedSql parsedSql = this.parsedSqlCache.get(sql);
			if (parsedSql == null) {
				parsedSql = new ExposedParsedSql( NamedParameterUtils.parseSqlStatement(sql) );
				this.parsedSqlCache.put(sql, parsedSql);
			}
			return parsedSql;
		}
	}
898482
public static String validateXMLAgainstSchema(final String xml) {
		// Validate XML against schema
		if (xml != null && !xml.equals("")) {
			// Wrap XML with a root element (if required)
			String testXML = wrapXMLInRootElement(xml);
			try {
				// Create SAX Parser Factory
				SAXParserFactory spf = SAXParserFactory.newInstance();
				spf.setNamespaceAware(true);
				spf.setValidating(true);

				// Create SAX Parser
				SAXParser parser = spf.newSAXParser();
				parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
						XMLConstants.W3C_XML_SCHEMA_NS_URI);

				// Set schema location
				Object schema = DebugValidateXML.class.getResource(getSchemaPath()).toString();
				parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schema);

				// Setup the handler to throw an exception when an error occurs
				DefaultHandler handler = new DefaultHandler() {
					@Override
					public void warning(final SAXParseException e) throws SAXException {
						LOG.warn("XML Schema warning: " + e.getMessage(), e);
						super.warning(e);
					}

					@Override
					public void fatalError(final SAXParseException e) throws SAXException {
						throw e;
					}

					@Override
					public void error(final SAXParseException e) throws SAXException {
						throw e;
					}
				};

				// Validate the XML
				InputSource xmlSource = new InputSource(new StringReader(testXML));
				parser.parse(xmlSource, handler);

			} catch (SAXParseException e) {
				return "At line " + e.getLineNumber() + ", column: " + e.getColumnNumber()
						+ " ==> " + e.getMessage();
			} catch (Exception e) {
				return e.getMessage();
			}
		}

		return null;
	}
313035
private static DataSource getDataSource(String params)
            throws JspException {
        DataSourceWrapper dataSource = new DataSourceWrapper();

        String[] paramString = new String[4];
        int escCount = 0;
        int aryCount = 0;
        int begin = 0;

        for (int index = 0; index < params.length(); index++) {
            char nextChar = params.charAt(index);
            if (TOKEN.indexOf(nextChar) != -1) {
                if (escCount == 0) {
                    paramString[aryCount] = params.substring(begin, index).trim();
                    begin = index + 1;
                    if (++aryCount > 4) {
                        throw new JspTagException(
                            Resources.getMessage("JDBC_PARAM_COUNT"));
                    }
                }
            }
            if (ESCAPE.indexOf(nextChar) != -1) {
                escCount++;
            } else {
                escCount = 0;
            }
        }
        paramString[aryCount] = params.substring(begin).trim();

	// use the JDBC URL from the parameter string
        dataSource.setJdbcURL(paramString[0]);

	// try to load a driver if it's present
        if (paramString[1] != null) {
            try {
                dataSource.setDriverClassName(paramString[1]);
            } catch (Exception ex) {
                throw new JspTagException(
                    Resources.getMessage("DRIVER_INVALID_CLASS",
					 ex.toString()), ex);
            }
	}

	// set the username and password
        dataSource.setUserName(paramString[2]);
        dataSource.setPassword(paramString[3]);

	return dataSource;
    }
16878
public void processMappedStatement(MappedStatement ms){
        MapperTemplate mapperTemplate = isMapperMethod(ms.getId());
        if(mapperTemplate != null && ms.getSqlSource() instanceof ProviderSqlSource) {
            setSqlSource(ms, mapperTemplate);
        }
    }
1287297
@Override
    public SqlInfo buildSqlInfo(BuildSource source) {
        String valueText = XmlNodeHelper.getNodeAttrText(source.getNode(), ZealotConst.ATTR_VALUE);
        String matchText = XmlNodeHelper.getNodeAttrText(source.getNode(), ZealotConst.ATTR_MATCH);
        if (StringHelper.isBlank(matchText)) {
            return this.doBuildSqlInfo(source, valueText);
        } else {
            /* 如果match匹配成功，则生成数据库sql条件和参数 */
            Boolean isTrue = (Boolean) ParseHelper.parseExpressWithException(matchText, source.getParamObj());
            if (isTrue) {
                return this.doBuildSqlInfo(source, valueText);
            }
        }
        return source.getSqlInfo();
    }
1077926
public MappedStatement getCountMappedStatement(MappedStatement ms) {
    	
    	String newMsId = ms.getId() + PAGE_COUNT_SUFFIX;
    	
    	MappedStatement statement = null;
    	Configuration configuration = ms.getConfiguration();
	
    	try {
    		statement = configuration.getMappedStatement(newMsId);
    		if(statement != null)return statement;
		} catch (Exception e) {}
    	
    	synchronized (configuration) {   
    		
    		if(configuration.hasStatement(newMsId))return configuration.getMappedStatement(newMsId);
    		
    		MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), newMsId, ms.getSqlSource(), ms.getSqlCommandType());
    		builder.resource(ms.getResource());
    		builder.fetchSize(ms.getFetchSize());
    		builder.statementType(ms.getStatementType());
    		builder.keyGenerator(ms.getKeyGenerator());
    		if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
    			StringBuilder keyProperties = new StringBuilder();
    			for (String keyProperty : ms.getKeyProperties()) {
    				keyProperties.append(keyProperty).append(",");
    			}
    			keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
    			builder.keyProperty(keyProperties.toString());
    		}
    		builder.timeout(ms.getTimeout());
    		builder.parameterMap(ms.getParameterMap());
    		//count查询返回值int
    		 List<ResultMap> resultMaps = new ArrayList<ResultMap>();
             String id = newMsId + "-Inline";
             ResultMap resultMap = new ResultMap.Builder(configuration, id, Long.class, new ArrayList<ResultMapping>(0)).build();
             resultMaps.add(resultMap);
             builder.resultMaps(resultMaps);
             
    		builder.resultSetType(ms.getResultSetType());
    		builder.cache(ms.getCache());
    		builder.flushCacheRequired(ms.isFlushCacheRequired());
    		builder.useCache(ms.isUseCache());
    		
    		statement = builder.build();
    		configuration.addMappedStatement(statement);
    		return statement;
    	}
    	
    }
244215
public String selectCountByExample(MappedStatement ms) {
        Class<?> entityClass = getEntityClass(ms);
        StringBuilder sql = new StringBuilder("SELECT ");
        if (isCheckExampleEntityClass()) {
            sql.append(SqlHelper.exampleCheck(entityClass));
        }
        sql.append(SqlHelper.exampleCountColumn(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
        sql.append(SqlHelper.exampleWhereClause());
        sql.append(SqlHelper.exampleForUpdate());
        return sql.toString();
    }
1285232
public static SchemaItem parse(String sql) {
        try {
            SQLStatementParser parser = new MySqlStatementParser(sql);
            SQLSelectStatement statement = (SQLSelectStatement) parser.parseStatement();
            MySqlSelectQueryBlock sqlSelectQueryBlock = (MySqlSelectQueryBlock) statement.getSelect().getQuery();

            SchemaItem schemaItem = new SchemaItem();
            schemaItem.setSql(SQLUtils.toMySqlString(sqlSelectQueryBlock));
            SQLTableSource sqlTableSource = sqlSelectQueryBlock.getFrom();
            List<TableItem> tableItems = new ArrayList<>();
            SqlParser.visitSelectTable(schemaItem, sqlTableSource, tableItems, null);
            tableItems.forEach(tableItem -> schemaItem.getAliasTableItems().put(tableItem.getAlias(), tableItem));

            List<FieldItem> fieldItems = collectSelectQueryFields(sqlSelectQueryBlock);
            fieldItems.forEach(fieldItem -> schemaItem.getSelectFields().put(fieldItem.getFieldName(), fieldItem));

            schemaItem.init();

            if (schemaItem.getAliasTableItems().isEmpty() || schemaItem.getSelectFields().isEmpty()) {
                throw new ParserException("Parse sql error");
            }
            return schemaItem;
        } catch (Exception e) {
            throw new ParserException();
        }
    }
496164
public static XAConnection createXAConnection(final DatabaseType databaseType, final XADataSource xaDataSource, final Connection connection) {
        switch (databaseType) {
            case MySQL:
                return new MySQLXAConnectionWrapper().wrap(xaDataSource, connection);
            case PostgreSQL:
                return new PostgreSQLXAConnectionWrapper().wrap(xaDataSource, connection);
            case H2:
                return new H2XAConnectionWrapper().wrap(xaDataSource, connection);
            default:
                throw new UnsupportedOperationException(String.format("Cannot support database type: `%s`", databaseType));
        }
    }
203104
public String toXml(Object source, String rootName, boolean hasNull) {
        if (source == null) {
            log.warn("传入的source为null，返回null");
            return null;
        }

        if (rootName == null) {
            XmlNode xmlNode = source.getClass().getDeclaredAnnotation(XmlNode.class);
            rootName = xmlNode == null ? null : xmlNode.name();
        }

        if (rootName == null) {
            rootName = DEFAULT_ROOT;
        }

        Long start = System.currentTimeMillis();
        Element root = DocumentHelper.createElement(rootName);
        buildDocument(root, source, source.getClass(), !hasNull);
        Long end = System.currentTimeMillis();
        log.debug("解析xml用时" + (end - start) + "ms");
        return root.asXML();
    }
1277992
public void setSqlSource(MappedStatement ms, MapperTemplate mapperTemplate) {
        try {
            if (mapperTemplate != null) {
                mapperTemplate.setSqlSource(ms);
            }
        } catch (Exception e) {
            throw new MapperException(e);
        }
    }
848331
public static DataSource createDataSource(String dbName ,boolean initSpatial, String h2Parameters) throws SQLException {
        // Create H2 memory DataSource
        org.h2.Driver driver = org.h2.Driver.load();
        OsgiDataSourceFactory dataSourceFactory = new OsgiDataSourceFactory(driver);
        Properties properties = new Properties();
        String databasePath = initDBFile(dbName, h2Parameters);
        properties.setProperty(DataSourceFactory.JDBC_URL, databasePath);
        properties.setProperty(DataSourceFactory.JDBC_USER, "sa");
        properties.setProperty(DataSourceFactory.JDBC_PASSWORD, "sa");
        DataSource dataSource = dataSourceFactory.createDataSource(properties);
        // Init spatial ext
        if(initSpatial) {
            try (Connection connection = dataSource.getConnection()) {
                H2GISFunctions.load(connection);
            }
        }
        return dataSource;
    }
721847
public static SqlInfo getSqlInfo(String nameSpace, String zealotId, Object paramObj) {
        if (StringHelper.isBlank(nameSpace) || StringHelper.isBlank(zealotId)) {
            throw new ValidFailException("请输入有效的nameSpace或者zealotId的值!");
        }

        // 获取nameSpace文档中的指定sql的zealotId的节点对应的Node节点，如果是debug模式，则实时获取；否则从缓存中获取.
        Node zealotNode = NormalConfig.getInstance().isDebug() ? XmlNodeHelper.getNodeBySpaceAndId(nameSpace, zealotId)
                : AbstractZealotConfig.getZealots().get(StringHelper.concat(nameSpace, ZealotConst.SP_AT, zealotId));
        if (zealotNode == null) {
            throw new NodeNotFoundException("未找到nameSpace为:" + nameSpace + ",zealotId为:" + zealotId + "的节点!");
        }

        // 生成新的SqlInfo信息并打印出来.
        SqlInfo sqlInfo = buildNewSqlInfo(nameSpace, zealotNode, paramObj);
        SqlInfoPrinter.newInstance().printZealotSqlInfo(sqlInfo, true, nameSpace, zealotId);
        return sqlInfo;
    }
188210
public Object sqlToJava(Object source)
    {
        if (source instanceof java.sql.Timestamp)
        {
         	return new java.util.Date( ((java.sql.Timestamp) source).getTime());  
        }
        else
        {
         	return source;   
        }
    }
1109579
@Override
    VoltXMLElement voltGetStatementXML(Session session)
    throws org.hsqldb_voltpatches.HSQLInterface.HSQLParseException
    {
        VoltXMLElement xml;
        switch (type) {

        case StatementTypes.INSERT :
            xml = new VoltXMLElement("insert");

            assert(insertExpression != null || queryExpression != null);

            if (queryExpression == null) {
            if (insertExpression.nodes.length > 1) {
                throw new org.hsqldb_voltpatches.HSQLInterface.HSQLParseException(
                    "VoltDB does not support multiple rows in the INSERT statement VALUES clause. Use separate INSERT statements.");
            }
                voltAppendTargetColumns(session, insertColumnMap, insertExpression.nodes[0].nodes, xml);
            } else {
                voltAppendTargetColumns(session, insertColumnMap, null, xml);
                VoltXMLElement child = voltGetXMLExpression(queryExpression, parameters, session);
                xml.children.add(child);
            }
            break;

        case StatementTypes.UPDATE_CURSOR :
        case StatementTypes.UPDATE_WHERE :
            xml = new VoltXMLElement("update");
            voltAppendTargetColumns(session, updateColumnMap, updateExpressions, xml);
            voltAppendChildScans(session, xml);
            voltAppendCondition(session, xml);
            break;

        case StatementTypes.DELETE_CURSOR :
        case StatementTypes.DELETE_WHERE :
            xml = new VoltXMLElement("delete");
            // DELETE has no target columns
            voltAppendChildScans(session, xml);
            voltAppendCondition(session, xml);
            voltAppendSortAndSlice(session, xml);
            break;

        case StatementTypes.MIGRATE_WHERE :
            xml = new VoltXMLElement("migrate");
            voltAppendChildScans(session, xml);
            voltAppendCondition(session, xml);
            break;

        default:
            throw new org.hsqldb_voltpatches.HSQLInterface.HSQLParseException(
                "VoltDB does not support DML statements of type " + type);
        }

        voltAppendParameters(session, xml, parameters);
        xml.attributes.put("table", targetTable.getName().name);
        return xml;
    }
495729
function create( &$xmls ) {
		$table = $xmls->dict->TableName($this->parent->name);
		$table_field_count = count($this->parent->fields);
		$tables = $xmls->db->MetaTables();
		$sql = array();

		$ukeys = $xmls->db->MetaPrimaryKeys( $table );
		if( !empty( $this->parent->indexes ) and !empty( $ukeys ) ) {
			foreach( $this->parent->indexes as $indexObj ) {
				if( !in_array( $indexObj->name, $ukeys ) ) $ukeys[] = $indexObj->name;
			}
		}

		// eliminate any columns that aren't in the table
		foreach( $this->data as $row ) {
			$table_fields = $this->parent->fields;
			$fields = array();
			$rawfields = array(); // Need to keep some of the unprocessed data on hand.

			foreach( $row as $field_id => $field_data ) {
				if( !array_key_exists( $field_id, $table_fields ) ) {
					if( is_numeric( $field_id ) ) {
						$field_id = reset( array_keys( $table_fields ) );
					} else {
						continue;
					}
				}

				$name = $table_fields[$field_id]['NAME'];

				switch( $table_fields[$field_id]['TYPE'] ) {
					case 'I':
					case 'I1':
					case 'I2':
					case 'I4':
					case 'I8':
						$fields[$name] = intval($field_data);
						break;
					case 'C':
					case 'C2':
					case 'X':
					case 'X2':
					default:
						$fields[$name] = $xmls->db->qstr( $field_data );
						$rawfields[$name] = $field_data;
				}

				unset($table_fields[$field_id]);

			}

			// check that at least 1 column is specified
			if( empty( $fields ) ) {
				continue;
			}

			// check that no required columns are missing
			if( count( $fields ) < $table_field_count ) {
				foreach( $table_fields as $field ) {
					if( isset( $field['OPTS'] ) and ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) {
							continue(2);
						}
				}
			}

			// The rest of this method deals with updating existing data records.

			if( !in_array( $table, $tables ) or ( $mode = $xmls->existingData() ) == XMLS_MODE_INSERT ) {
				// Table doesn't yet exist, so it's safe to insert.
				logMsg( "$table doesn't exist, inserting or mode is INSERT" );
			$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
				continue;
		}

			// Prepare to test for potential violations. Get primary keys and unique indexes
			$mfields = array_merge( $fields, $rawfields );
			$keyFields = array_intersect( $ukeys, array_keys( $mfields ) );

			if( empty( $ukeys ) or count( $keyFields ) == 0 ) {
				// No unique keys in schema, so safe to insert
				logMsg( "Either schema or data has no unique keys, so safe to insert" );
				$sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')';
				continue;
			}

			// Select record containing matching unique keys.
			$where = '';
			foreach( $ukeys as $key ) {
				if( isset( $mfields[$key] ) and $mfields[$key] ) {
					if( $where ) $where .= ' AND ';
					$where .= $key . ' = ' . $xmls->db->qstr( $mfields[$key] );
				}
			}
			$records = $xmls->db->Execute( 'SELECT * FROM ' . $table . ' WHERE ' . $where );
			switch( $records->RecordCount() ) {
				case 0:
					// No matching record, so safe to insert.
					logMsg( "No matching records. Inserting new row with unique data" );
					$sql[] = $xmls->db->GetInsertSQL( $records, $mfields );
					break;
				case 1:
					// Exactly one matching record, so we can update if the mode permits.
					logMsg( "One matching record..." );
					if( $mode == XMLS_MODE_UPDATE ) {
						logMsg( "...Updating existing row from unique data" );
						$sql[] = $xmls->db->GetUpdateSQL( $records, $mfields );
					}
					break;
				default:
					// More than one matching record; the result is ambiguous, so we must ignore the row.
					logMsg( "More than one matching record. Ignoring row." );
			}
		}
		return $sql;
	}