/*
解析Sql语句中的注释信息
185065
private Map<String, String> parseComment(String sql) {
		Map<String, String> commentMap = new HashMap<String, String>();
		try {
		while (StringUtils.contains(sql, "/*") && StringUtils.contains(sql, "*/")) {
			String comment = StringUtils.substringBetween(sql, "/*", "*/");
			comment = comment.toUpperCase().trim();

			if (StringUtils.isNotEmpty(comment)) {
				if (comment.contains("NO_CACHE")) {
					commentMap.put("CACHE", "FALSE");
				}
				String commentItems[] = comment.split(",");
				for (String commentItem : commentItems) {
					if (commentItem != null && commentItem.contains("=")) {
						String value[] = commentItem.trim().split("=");
						if (value != null && value.length == 2) {
							commentMap.put(value[0].trim(), value[1].trim());
						}
					}
				}
			}

			sql = StringUtils.substringBefore(sql, "/*") + StringUtils.substringAfter(sql, "*/");
		}
		} catch (Exception e) {
			logger.error("Parse sql comment fail:" + sql);
		}
		return commentMap;
	}
1271446
public function count() {
        $sql    = $this->getSQL();
        $values = $this->values;
        if ($sql) {
            try {
                $ids = array_keys($this->datas);
                if ($this->batch && count($this->datas) > 1) {
                    unset($ids[0]);
                    $sqlValues = [];
                    foreach ($ids as $idx) {
                        $d       = $this->datas[ $idx ];
                        $vstring = [];
                        foreach ($d as $ff => $vv) {
                            if ($vv instanceof ImmutableValue) { // a immutable value
                                $vv->setDialect($this->dialect);
                                $vstring [] = $this->sanitize($vv->__toString());
                            } else if ($vv instanceof Query) { // a sub-select SQL as a value
                                $vv->setBindValues($values);
                                $vv->setDialect($this->dialect);
                                $vstring [] = '(' . $vv->__toString() . ')';
                            } else {
                                $vstring [] = $values->addValue($ff, $vv);
                            }
                        }
                        $sqlValues[] = '(' . implode(' , ', $vstring) . ')';
                    }
                    $this->sql = $sql = $sql . ',' . implode(' , ', $sqlValues);
                }

                $statement = $this->dialect->prepare($sql);

                foreach ($values as $value) {
                    list ($name, $val, $type) = $value;
                    if (!$statement->bindValue($name, $val, $type)) {
                        $this->errorSQL    = $sql;
                        $this->errorValues = $values->__toString();
                        $this->error       = 'can not bind the value ' . $val . '[' . $type . '] to the argument:' . $name;

                        return false;
                    }
                }

                $rst = $statement->execute();
                if ($rst) {
                    if ($this->keySet) {
                        $this->fillAutoIds();
                    } else {
                        $this->ids [] = $this->dialect->lastInsertId($this->keyField);
                    }

                    return $statement->rowCount();
                } else {
                    $this->dumpSQL($statement);
                }

                if ($statement) {
                    $statement->closeCursor();
                    $statement = null;
                }
            } catch (\PDOException $e) {
                $this->exception   = $e;
                $this->error       = $e->getMessage();
                $this->errorSQL    = $sql;
                $this->errorValues = $values->__toString();

                return false;
            }
        } else {
            $this->error       = 'Can not generate the insert SQL';
            $this->errorSQL    = '';
            $this->errorValues = $values->__toString();
        }

        return false;
    }
473693
public function getSql() : ?string 
    {
        if ( ! $this->hasSql()) {
            $this->setSql($this->getDefaultSql());
        }
        return $this->sql;
    }
755788
function (sql) {
            var values = this.__opts.values;
            if (isArray(values) && !values.length) {
                return " ()";
            } else {
                return this._super(arguments);
            }
        }
328774
function selectByIdWhereSql () {
    // get id column
    var idColumn = this.model.columnName('id')
    // every where statement will begin with the alias and column name
    var columnSql = `${this.alias}.${this.quoteName(idColumn)}`
    // sql for where query
    var sql
    // if ids are array build in query
    if (Array.isArray(this.args.where.id)) {
        var i = 0
        // get placeholder for each in value
        var placeholders = _.map(this.args.where.id, id => {
            // get param name
            var paramName = `id${i}`
            // increment param counter
            i++
            // set value for param placeholder
            this.params[paramName] = id
            // create placeholder
            return this.unhexId(`:${paramName}`)
        })
        // return where sql
        sql = `WHERE ${columnSql} IN(${placeholders.join(', ')})`
    }
    // otherwise build equals query
    else {
        // set value for param placeholder
        this.params.id = this.args.where.id
        // get place holder
        var placeholder = this.unhexId(':id')
        // return where sql
        sql = `WHERE ${columnSql} = ${placeholder}`
    }
    // and deleted check if d column exists and set in args
    if (defined(this.model.columns.d) && typeof this.args.where.isDeleted === 'boolean') {
        sql += ` AND ${this.alias}.d = ${this.args.where.isDeleted ? 1 : 0}`
    }

    return sql
}
1303170
function QueryWhere(data)
{
	//Initialize the string
	var sql = '';

	//Check the type
	if(typeof data === 'string')
	{
		//Return the where
		return data;
	}

	//Get all data
	for(var key in data)
	{
		//Save data value
		var value = data[key];

		//Check the data type
		if(typeof value === 'string' || value instanceof String)
		{
			//Add the quotes
			value = '"' + value + '"';
		}

		//Check if is necessary add the AND
		if(sql !== '')
		{
			//Add the AND
			sql = sql + ' AND ';
		}

		//Add the key=value
		sql = sql + key + '=' + value;
	}

	//Return the string
	return sql;
}
931070
function parseSchemaInfo(resultset) {
            for (var i = 0; i < resultset.rs.rows.length; i++) {
                var row = resultset.rs.rows.item(i);
                if (row.name.indexOf('sqlite_autoindex') > -1 || row.name == '__WebKitDatabaseInfoTable__') continue;
                if (row.type == 'table') {
                    tables.push(row.tbl_name);
                } else if (row.type == 'index') {
                    if (!(row.tbl_name in indexes)) {
                        indexes[row.tbl_name] = [];
                    }
                    indexes[row.tbl_name].push(row.name);
                }
            }
            return;
        }
899998
@SuppressWarnings("unchecked")
    public <N extends Object> List<N> findOneColumn(String sql, List<?> params, final int mapperColumnIndex) {

        if (sql == null) {
            recordLog(" param sql is null!");
        }

        // 查询
        return findBySQL(sql, params, new RowMapper<N>() {
            public N mapRow(ResultSet rs, int count) throws SQLException {
                return (N) (rs.getObject(mapperColumnIndex));
            }
        });
    }
1053584
function _DBParameter($sql)
	{
		$savelog = $this->conn->LogSQL(false);
		if (is_array($sql)) {
		global $ADODB_FETCH_MODE;

			$sql1 = $sql[0];
			$key = $sql[1];
			if (sizeof($sql)>2) $pos = $sql[2];
			else $pos = 1;
			if (sizeof($sql)>3) $coef = $sql[3];
			else $coef = false;
			$ret = false;
			$save = $ADODB_FETCH_MODE;
			$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
			if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);

			$rs = $this->conn->Execute($sql1);

			if (isset($savem)) $this->conn->SetFetchMode($savem);
			$ADODB_FETCH_MODE = $save;
			if ($rs) {
				while (!$rs->EOF) {
					$keyf = reset($rs->fields);
					if (trim($keyf) == $key) {
						$ret = $rs->fields[$pos];
						if ($coef) $ret *= $coef;
						break;
					}
					$rs->MoveNext();
				}
				$rs->Close();
			}
			$this->conn->LogSQL($savelog);
			return $ret;
		} else {
			if (strncmp($sql,'=',1) == 0) {
				$fn = substr($sql,1);
				return $this->$fn();
			}
			$sql = str_replace('$DATABASE',$this->conn->database,$sql);
			$ret = $this->conn->GetOne($sql);
			$this->conn->LogSQL($savelog);

			return $ret;
		}
	}
776351
function length$1(callback) {
    var self = this;

    var promise = new Promise$1(function (resolve, reject) {
        self.ready().then(function () {
            var dbInfo = self._dbInfo;
            dbInfo.db.transaction(function (t) {
                // Ahhh, SQL makes this one soooooo easy.
                tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
                    var result = results.rows.item(0).c;
                    resolve(result);
                }, function (t, error) {
                    reject(error);
                });
            });
        })["catch"](reject);
    });

    executeCallback(promise, callback);
    return promise;
}
355093
public function getSql()
    {
        $sqlTemplate = "SELECT %s FROM %s %s";
        $fieldsCompiled = implode(',', $this->getFields());
        return trim(sprintf(
            $sqlTemplate,
            $fieldsCompiled,
            $this->getTable(),
            $this->getWhereStatement()
        ));
    }
1098162
private static int getIndexOfFrom(String sql) {
		int parenDepth = 0;
		char c;
		for (int i = start, end = sql.length() - 5; i < end; i++) {
			c = sql.charAt(i);
			if (c >= SIZE) {
				continue ;
			}
			
			c = charTable[c];
			if (c == NULL) {
				continue ;
			}
			
			if (c == '(') {
				parenDepth++;
				continue ;
			}
			
			if (c == ')') {
				if (parenDepth == 0) {
					throw new RuntimeException("Can not match left paren '(' for right paren ')': " + sql);
				}
				parenDepth--;
				continue ;
			}
			if (parenDepth > 0) {
				continue ;
			}
			
			if (c == 'f'
				&& charTable[sql.charAt(i + 1)] == 'r'
				&& charTable[sql.charAt(i + 2)] == 'o'
				&& charTable[sql.charAt(i + 3)] == 'm') {
				c = sql.charAt(i + 4);
				// 测试用例： "select count(*)from(select * from account limit 3) as t"
				if (charTable[c] == ' ' || c == '(') {		// 判断 from 后方字符
					c = sql.charAt(i - 1);
					if (charTable[c] == ' ' || c == ')') {	// 判断 from 前方字符
						return i;
					}
				}
			}
		}
		return -1;
	}
681601
public static String getSQL(String sql, StatementParameter param) {
		int i = 0;
		while (sql.indexOf('?') > -1) {
			if (param == null) {
				throw new InvalidParamDataAccessException("没有设置参数.");
			}
			if (i >= param.size()) {
				return sql;
			}
			Class<?> type = param.getType(i);
			Object obj = param.getObject(i);
			String value = getValue(type, obj);
			sql = sql.substring(0, sql.indexOf('?')) + value + sql.substring(sql.indexOf('?') + 1, sql.length());
			i++;
		}
		return sql;//
	}
446785
public function getQuery()
    {
        $sql = $this->prepareSelectString();
        $sql .= $this->prepareJoinString();
        $sql .= $this->prepareWhereString();
        $sql .= $this->prepareGroupByString();
        $sql .= $this->prepareHavingString();
        $sql .= $this->prepareOrderByString();
        $sql .= $this->prepareLimitString();

        return $sql;
    }
93766
public final function queryLine($sql, $_)
    {
        $params = func_get_args();
        if ($this->debug)
        {
            var_dump($params);
        }
        array_shift($params);
        $stm = $this->prepare($sql);
        if ($stm->execute($params))
        {
            $ret = $stm->fetch();
            $stm->closeCursor();
            return $ret;
        }
        else
        {
            \Swoole\Error::info("SQL Error", implode(", ", $this->errorInfo()) . "<hr />$sql");
            return false;
        }
    }
58656
public function execute($sql) {

        //如果开启了调试模式，那么把所有对数据库写操作的语句记录下来
        if ( SQL_LOG &&
            (strpos($sql, 'INSERT') !== false
                || strpos($sql, 'DELETE') !== false
                || strpos($sql, 'REPLACE') !== false
                    || strpos($sql, 'UPDATE') !== false)) {
            Log::info($sql, 'sql');
        }
        if ( $this->link == null ) $this->connect();
        try {
            $result = $this->link->query($sql);
        } catch ( PDOException $e ) {
            $exception = new DBException("SQL错误:" . $e->getMessage());
            $exception->setCode($e->getCode());
            $exception->setQuery($sql);
            if ( APP_DEBUG ) {
                __print($sql);
            }
            throw $exception;
        }
        return $result;
    }
871027
function _query($sql,$inputarr=false)
	{
		$this->_errorMsg = false;

		if (is_array($sql)) $sql = $sql[1];

		$insert = false;
		// handle native driver flaw for retrieving the last insert ID
		if(preg_match('/^\W*insert[\s\w()",.]+values\s*\((?:[^;\']|\'\'|(?:(?:\'\')*\'[^\']+\'(?:\'\')*))*;?$/i', $sql)) {
			$insert = true;
			$sql .= '; '.$this->identitySQL; // select scope_identity()
		}
		if($inputarr) {
			$rez = sqlsrv_query($this->_connectionID, $sql, $inputarr);
		} else {
			$rez = sqlsrv_query($this->_connectionID,$sql);
		}

		if ($this->debug) ADOConnection::outp("<hr>running query: ".var_export($sql,true)."<hr>input array: ".var_export($inputarr,true)."<hr>result: ".var_export($rez,true));

		if(!$rez) {
			$rez = false;
		} else if ($insert) {
			// retrieve the last insert ID (where applicable)
			while ( sqlsrv_next_result($rez) ) {
				sqlsrv_fetch($rez);
				$this->lastInsertID = sqlsrv_get_field($rez, 0);
			}
		}
		return $rez;
	}