输入已经完成,开始创建语句信息
生成prepare语句
生成sql语句
生成params参数数组
生成表个数/表名

@return string
@throws MysqlException
169486
public function create(): string
    {
        switch ($this->operation) {
            case 'exist':
                // 判断是否存在满足条件的记录
                return $this->createExist();
            case 'query':
            case 'repair':
            case 'optimize':
            case 'call':
                // 直接SQL查询
                return $this->createQuery();
            case 'execute':
                // 直接SQL操作
                return $this->createExecute();
            case 'insert':
                // 插入
            case 'replace':
                // 存在则替换,否则插入
            case 'insertIgnore':
                // 存在则忽略,否则插入
                return $this->createAdd();
            case 'inserts':
                //多行插入
                return $this->createInserts();
            case 'update':
                // 修改
                return $this->createUpdate();
            case 'delete':
                // 删除
                return $this->createDelete();
            case 'deleteAll':
                // 删除全部
                return $this->createDeleteAll();
            case 'select':
                // 查询
            case 'selectHandle':
                // 查询并返回句柄
                return $this->createSelect();
            case 'crease':
                // 增减
                return $this->createCrease();
        }
        trigger_error('无法识别或不支持的SQL命令:' . $this->operation, E_USER_ERROR);
        return '';
    }
1248182
public function getSqlString() {
        $sql = $this->getSQL();
        if ($sql && $this->values) {
            foreach ($this->values as $value) {
                list ($name, $val, $type, , $rkey) = $value;
                if ($this->whereData) {
                    $val = isset($this->whereData[ $rkey ]) ? $this->whereData[ $rkey ] : (isset($this->whereData[ $name ]) ? $this->whereData[ $name ] : $val);
                }
                if ($type == \PDO::PARAM_STR) {
                    $sql = str_replace($name, $this->dialect->quote($val), $sql);
                } else {
                    $sql = str_replace($name, $val, $sql);
                }
            }
        }

        return $sql;
    }
936960
private function select() {
        $this->performed  = true;
        $this->resultSet  = [];
        $this->resultSets = [];
        $this->resultIdx  = 0;
        $this->maxIdx     = 0;
        $this->size       = 0;
        try {
            $this->checkDialect();
        } catch (DialectException $e) {
            $this->error = $e->getMessage();

            return;
        }
        //生成SQL
        if (!$this->sql) {
            $this->sql = $this->getSQL();
            if (!$this->sql) {
                $this->error       = 'can not generate the SQL';
                $this->errorSQL    = '';
                $this->errorValues = $this->values->__toString();

                return;
            }
            //重新生成SQL.
            $this->statement = null;
        }
        //生成prepare statement
        if (!$this->statement) {
            $this->prepareStatement();
        }
        //执行
        if ($this->statement) {
            try {
                if ($this->values) {
                    foreach ($this->values as $value) {
                        list ($name, $val, $type, $field, $rkey) = $value;
                        if ($this->whereData) {
                            $val = isset($this->whereData[ $rkey ]) ? $this->whereData[ $rkey ] : (isset($this->whereData[ $name ]) ? $this->whereData[ $name ] : $val);
                        }
                        if (!$this->statement->bindValue($name, $val, $type)) {
                            $this->errorSQL    = $this->sql;
                            $this->errorValues = $this->values->__toString();
                            $this->error       = 'can not bind the value ' . $val . '[' . $type . '] to the argument:' . $name . '(' . $field . ')';

                            return;
                        }
                    }
                }
                $rst = $this->statement->execute();
                QueryBuilder::addSqlCount();
                if ($rst) {
                    $this->resultSets = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
                    $this->size       = count($this->resultSets);
                    if ($this->size > 0) {
                        $this->maxIdx    = $this->size - 1;
                        $this->resultSet = $this->resultSets[0];
                    }
                } else {
                    $this->dumpSQL($this->statement);
                }
            } catch (\PDOException $e) {
                $this->exception   = $e;
                $this->error       = $e->getMessage();
                $this->errorSQL    = $this->sql;
                $this->errorValues = $this->values->__toString();
            }
        }
    }
404057
private function createDeleteAll(): string
    {
        // 生成三项
        $this->sql = $this->db->createDelete($this->table, '');
        $this->prepare = $this->sql;
        $this->params = [];

        $this->tables = [$this->table];
        return $this->prepare;
    }
783677
public function sqlOrders()
    {
        if (!$this->hasOrders()) {
            return '';
        }

        $parts = [];
        foreach ($this->orders() as $order) {
            if (!$order instanceof DatabaseOrder) {
                $order = $this->createOrder($order->data());
            }

            $sql = $order->sql();
            if (strlen($sql) > 0) {
                $parts[] = $sql;
            }
        }

        if (empty($parts)) {
            return '';
        }

        return ' ORDER BY '.implode(', ', $parts);
    }
1060610
public function Generate()
	{
		// check for all required fields
		if ( empty($_REQUEST["table_name"]) )
		{
			throw new Exception("Please select at least one table to generate");
		}

		$cstring = $this->GetConnectionString();

		// initialize the database connection
		$handler = new DBEventHandler();
		$connection = new DBConnection($cstring, $handler);
		$server = new DBServer($connection);
		$dbSchema = new DBSchema($server);

		$debug = isset($_REQUEST["debug"]) && $_REQUEST["debug"] == "1";
		$parameters = array();
		$tableNames = $_REQUEST["table_name"];
		$packageName = $_REQUEST["package"];
		$debug_output = "";
		
		$selectedTables = array();
		foreach ($tableNames as $tableName)
		{
			$selectedTables[] = $dbSchema->Tables[$tableName];
		}
		
		// see if arbitrary parameters were passed in - in which case they will be passed through to the templates
		$tmp = RequestUtil::Get('parameters');
		if ($tmp)
		{
			$pairs = explode("\n", str_replace("\r","", $tmp) );
			foreach ($pairs as $pair)
			{
				list($key,$val) = explode("=",$pair,2);
				$parameters[$key] = $val;
			}
		}
		
		// check for required parameters
		if (!array_key_exists('max_items_in_topnav', $parameters)) $parameters['max_items_in_topnav'] = self::$DEFAULT_MAX_ITEMS_IN_TOPNAV;

		$zipFile = new zipfile();

		$codeRoot = GlobalConfig::$APP_ROOT . '/code/';
		$tempRoot = GlobalConfig::$APP_ROOT . '/temp/';

		// initialize smarty
		$smarty = new Smarty();
		$smarty->template_dir = $codeRoot;
		$smarty->compile_dir = $tempRoot;
		$smarty->config_dir = $tempRoot;
		$smarty->cache_dir = $tempRoot;
		$smarty->caching = false;

		$appname = RequestUtil::Get("appname");
		$appRoot = RequestUtil::Get("appRoot");
		$includePath = RequestUtil::Get("includePath");
		$includePhar = RequestUtil::Get("includePhar");
		$enableLongPolling = RequestUtil::Get("enableLongPolling");

		$config = new AppConfig($codeRoot  . $packageName);
		
		foreach ($config->GetTemplateFiles() as $templateFile)
		{
			if ($templateFile->generate_mode == 3)
			{
				if ($includePhar == '1')
				{
					// proceed, copy the phar file
					$templateFile->generate_mode = 2;
				}
				else
				{
					// skip the phar file
					continue;
				}
			}
			
			if ($templateFile->generate_mode == 2)
			{
				// this is a template that is copied without parsing to the project (ie images, static files, etc)
				$templateFilename = str_replace(
						array('{$appname}','{$appname|lower}','{$appname|upper}'),
						array($appname,strtolower($appname),strtoupper($appname)),
						$templateFile->destination
				);

				$contents = file_get_contents($codeRoot . $templateFile->source);

				// this is a direct copy
				if ($debug)
				{
					$debug_output .= "\r\n###############################################################\r\n"
					. "# $templateFilename\r\n###############################################################\r\n"
					. "(contents of " . $codeRoot . $templateFile->source . ")\r\n";
				}
				else
				{
					$zipFile->addFile( $contents , $templateFilename);
				}
			}
			elseif ($templateFile->generate_mode == 1)
			{
				// single template where one is generated for the entire project instead of one for each selected table
				$templateFilename = str_replace(
						array('{$appRoot}','{$appRoot|lower}','{$appRoot|upper}'),
						array($appRoot,strtolower($appRoot),strtoupper($appRoot)),
						$templateFile->destination
				);

				$smarty->clearAllAssign();

				foreach ($parameters as $key => $val)
				{
					$smarty->assign($key,$val);
				}

				$smarty->assign("tableNames",$tableNames);
				$smarty->assign("templateFilename",$templateFilename);
				$smarty->assign("schema",$dbSchema);
				$smarty->assign("tables",$dbSchema->Tables);
				$smarty->assign("connection",$cstring);
				$smarty->assign("appname",$appname);
				$smarty->assign("appRoot",$appRoot);
				$smarty->assign("includePath",$includePath);
				$smarty->assign("includePhar",$includePhar);
				$smarty->assign("enableLongPolling",$enableLongPolling);
				$smarty->assign("PHREEZE_VERSION",Phreezer::$Version);

				$tableInfos = Array();
				
				// add all tables to a tableInfos array that can be used for cross-referencing by table name
						foreach ($dbSchema->Tables as $table)
				{
					if ($table->GetPrimaryKeyName())
					{
						$tableName = $table->Name;
						$tableInfos[$tableName] = Array();
						$tableInfos[$tableName]['table'] = $dbSchema->Tables[$tableName];
						$tableInfos[$tableName]['singular'] = $_REQUEST[$tableName."_singular"];
						$tableInfos[$tableName]['plural'] = $_REQUEST[$tableName."_plural"];
						$tableInfos[$tableName]['prefix'] = $_REQUEST[$tableName."_prefix"];
						$tableInfos[$tableName]['templateFilename'] = $templateFilename;
					}
				}
				
				$smarty->assign("tableInfos",$tableInfos);
				$smarty->assign("selectedTables",$selectedTables);

				if ($debug)
				{
					$debug_output .= "\r\n###############################################################\r\n"
					. "# $templateFilename\r\n###############################################################\r\n"
					. $smarty->fetch($templateFile->source) . "\r\n";
				}
				else
				{
					// we don't like bare linefeed characters
					$content = $body = preg_replace("/^(?=\n)|[^\r](?=\n)/", "\\0\r", $smarty->fetch($templateFile->source));

					$zipFile->addFile( $content , $templateFilename);
				}
			}
			else
			{
				// enumerate all selected tables and merge them with the selected template
				// append each to the zip file for output
				foreach ($tableNames as $tableName)
				{
					$singular = $_REQUEST[$tableName."_singular"];
					$plural = $_REQUEST[$tableName."_plural"];
					$prefix = $_REQUEST[$tableName."_prefix"];

					$templateFilename = str_replace(
							array('{$singular}','{$plural}','{$table}','{$appname}','{$singular|lower}','{$plural|lower}','{$table|lower}','{$appname|lower}','{$singular|upper}','{$plural|upper}','{$table|upper}','{$appname|upper}'),
							array($singular,$plural,$tableName,$appname,strtolower($singular),strtolower($plural),strtolower($tableName),strtolower($appname),strtoupper($singular),strtoupper($plural),strtoupper($tableName),strtoupper($appname)),
							$templateFile->destination);

					$smarty->clearAllAssign();
					$smarty->assign("appname",$appname);
					$smarty->assign("singular",$singular);
					$smarty->assign("plural",$plural);
					$smarty->assign("prefix",$prefix);
					$smarty->assign("templateFilename",$templateFilename);
					$smarty->assign("table",$dbSchema->Tables[$tableName]);
					$smarty->assign("connection",$cstring);
					$smarty->assign("appRoot",$appRoot);
					$smarty->assign("includePath",$includePath);
					$smarty->assign("includePhar",$includePhar);
					$smarty->assign("enableLongPolling",$enableLongPolling);
					$smarty->assign("PHREEZE_VERSION",Phreezer::$Version);

					$tableInfos = Array();
					
					// add all tables to a tableInfos array that can be used for cross-referencing by table name
					foreach ($dbSchema->Tables as $table)
					{
						if ($table->GetPrimaryKeyName())
						{
							$tableName = $table->Name;
							$tableInfos[$tableName] = Array();
							$tableInfos[$tableName]['table'] = $dbSchema->Tables[$tableName];
							$tableInfos[$tableName]['singular'] = $_REQUEST[$tableName."_singular"];
							$tableInfos[$tableName]['plural'] = $_REQUEST[$tableName."_plural"];
							$tableInfos[$tableName]['prefix'] = $_REQUEST[$tableName."_prefix"];
							$tableInfos[$tableName]['templateFilename'] = $templateFilename;
						}
					}
					
					$smarty->assign("tableInfos",$tableInfos);
					$smarty->assign("selectedTables",$selectedTables);
					
					foreach ($parameters as $key => $val)
					{
						$smarty->assign($key,$val);
					}

					//print "<pre>"; print_r($dbSchema->Tables[$tableName]->PrimaryKeyIsAutoIncrement()); die();
					if ($debug)
					{
						$debug_output .= "\r\n###############################################################\r\n"
						. "# $templateFilename\r\n###############################################################\r\n"
						. $smarty->fetch($templateFile->source) . "\r\n";
					}
					else
					{
						$zipFile->addFile( $smarty->fetch($templateFile->source) , $templateFilename);
					}

				}
			}

		}

		if ($debug)
		{
			header("Content-type: text/plain");
			print $debug_output;
		}
		else
		{
			// now output the zip as binary data to the browser
			header("Content-type: application/force-download");

			// laplix 2007-11-02.
			// Use the application name provided by the user in show_tables.
			//header("Content-disposition: attachment; filename=".str_replace(" ","_",$G_CONNSTR->DBName).".zip");
			header("Content-disposition: attachment; filename=".str_replace(" ","_",strtolower(str_replace("/","", $appRoot))).".zip");

			header("Content-Transfer-Encoding: Binary");
			header('Content-Type: application/zip');
			print $zipFile->file();
		}
	}
1138256
private function createUpdate(): string
    {
        // 处理字段名值数组
        list ($fields, $values) = $this->db->createRow($this->row);

        // 处理条件三项
        list ($whereSql, $wherePrepare, $whereParams) = $this->db->createWhere($this->where);
        if ($whereSql === false) {
            return '';
        }

        // 更新时未指定条件
        if (!$whereSql) {
            trigger_error('Update操作必须指定查询条件,不允许全表修改', E_USER_ERROR);
        }

        // 字段数组中的三项
        $set = $setPrepare = [];
        foreach ($fields as $k => $field) {
            $set[] = $this->db->createSet($field, $values[$k]);
            $setPrepare[] = $this->db->createSet($field, '?');
        }

        $this->sql = $this->db->createUpdate($this->table, $set, $whereSql);
        $this->prepare = $this->db->createUpdate($this->table, $setPrepare, $wherePrepare);
        $this->params = array_merge($values, $whereParams);

        $this->tables = [$this->table];
        return $this->prepare;
    }
383526
public static function build()
    {
        $args = func_get_args();

        $sql = [];

        foreach ($args as $arg) {
            if ($arg === '' || $arg === null || $arg === false) {
                continue;
            }

            $sql[] = $arg;
        }

        return implode(' ', $sql);
    }
1104051
public function getQuery(): string
    {
        $sql = $this->getSql();

        $sql = str_replace(['%', '?'], ['%%', '"%s"'], $sql);

        // replace mask by data
        return vsprintf($sql, $this->getParams());
    }
511070
public function buildSelectSQL()
	{
		$where = $this->parseCondition(isset($this->operationOption['where']) ? $this->operationOption['where'] : '');
		if ('' !== $where)
		{
			$where = 'where ' . $where . ' ';
		}
		return 'select ' . $this->parseDistinct()
				. $this->parseFieldBefore()
				. $this->parseField(null,'*')
				. 'from '
				. $this->parseTable() . ' '
				. $this->parseJoin()
				. $where
				. $this->parseGroup()
				. $this->parseHaving()
				. $this->parseOrder()
				. $this->parseLimit()
				. $this->parseLock()
				;
	}
905225
public function getCountSQL()
        {
            if (!$this->query->getTable() instanceof Table) {
                throw new Exception('Trying to generate sql when no table is being used.');
            }
            $sql = $this->generateCountSQL();
            $sql .= $this->generateJoinSQL();
            $sql .= $this->generateWhereSQL();

            return $sql;
        }
1046434
protected function generateSQL()
    {
        if ( !in_array( $this->type, array( 'name', 'alias', 'all' ) ) )
        {
            eZDebug::writeError( "Parameter \$type must be one of name, alias or all. The value which was used was '{$this->type}'." );
            return null;
        }

        $db = eZDB::instance();
        if ( $this->languages === true )
        {
            $langMask = trim( eZContentLanguage::languagesSQLFilter( 'ezurlalias_ml', 'lang_mask' ) );
            $conds[] = "($langMask)";
        }

        if ( $this->paren !== null )
        {
            $conds[] = "parent = {$this->paren}";
        }

        if ( $this->text !== null )
        {
            $conds[] = "text_md5 = " . $db->md5( "'" . $db->escapeString( $this->text ) . "'" );
        }

        if ( $this->actions !== null )
        {
            // Check for conditions which will return no rows.
            if ( count( $this->actions ) == 0 )
                return false;

            if ( count( $this->actions ) == 1 )
            {
                $action = $this->actions[0];
                $actionStr = $db->escapeString( $action );
                $conds[] = "action = '$actionStr'";
            }
            else
            {
                $actions = array();
                foreach ( $this->actions as $action )
                {
                    $actions[] = "'" . $db->escapeString( $action ) . "'";
                }
                $conds[] = "action IN (" . join( ", ", $actions ) . ")";
            }
        }
        $actionTypes = null;
        if ( $this->actionTypes !== null )
        {
            $actionTypes = $this->actionTypes;
        }
        if ( $this->actionTypesEx !== null )
        {
            if ( $actionTypes == null )
            {
                $rows = $db->arrayQuery( "SELECT DISTINCT action_type FROM ezurlalias_ml" );
                $actionTypes = array();
                foreach ( $rows as $row )
                {
                    $actionTypes[] = $row['action_type'];
                }
            }
            $actionTypes = array_values( array_diff( $actionTypes, $this->actionTypesEx ) );
        }
        if ( $actionTypes !== null )
        {
            // Check for conditions which will return no rows.
            if ( count( $actionTypes ) == 0 )
                return false;

            if ( count( $actionTypes ) == 1 )
            {
                $action = $actionTypes[0];
                $actionStr = $db->escapeString( $action );
                $conds[] = "action_type = '$actionStr'";
            }
            else
            {
                $actions = array();
                foreach ( $actionTypes as $action )
                {
                    $actions[] = "'" . $db->escapeString( $action ) . "'";
                }
                $conds[] = "action_type IN (" . join( ", ", $actions ) . ")";
            }
        }

        $conds[] = 'is_original = 1';
        if ( $this->type == 'name' )
        {
            $conds[] = 'is_alias = 0';
        }
        else if ( $this->type == 'alias' )
        {
            $conds[] = 'is_alias = 1';
        }
        else // 'all'
        {
        }

        return "FROM ezurlalias_ml WHERE " . join( " AND ", $conds );
    }
352342
protected function generateSelectAllSQL()
        {
            $sql_parts = [];
            foreach ($this->query->getSelectionColumns() as $selection) {
                $sql_parts[] = $selection->getSql();
            }
            return implode(', ', $sql_parts);
        }
1015640
public function toSQL()
    {
        $sql = [];
        $this->params = [];

        $sql[] = 'WHERE';

        if (! $this->conditions) {
            $sql[] = '1';
        } else {
            foreach ($this->conditions as $index => $value) {
                if ( $index > 0 ) $sql[] = $value->chain_by;
                $sql[] = $value->toSQL();
            }
        }

        return join(' ', $sql);
    }
770515
public function ___build(): string
    {
        $tables = \implode(', ', $this->tables);
        $fields = \implode(', ', $this->fields);
        $where = $orderBy = $limit = '';

        if ($this->where != '') {
            $where = \sprintf(' WHERE %s', $this->where);
        }
        if (\count($this->orderBy) > 0) {
            $orderBy = \sprintf(' ORDER BY %s', \implode(', ', $this->orderBy));
        }
        if ($this->limit != 0) {
            $limit = \sprintf(' LIMIT %s', $this->limit);
        }

        return \sprintf('UPDATE %s SET %s%s%s%s', $tables, $fields, $where, $orderBy, $limit);
    }
67370
private function generateQuery()
    {
        return $this->getUserModel()
                    ->select([
                        $this->getUserTable().'.*'
                    ])
                    ->join($this->getTokenTable(), $this->getTokenColumn('user_id'), '=', $this->getUserTable().'.'.$this->primaryKey)
                    ->where($this->getTokenColumn('token'), '=', $this->getToken());
    }
1197272
protected function replaceParamInSql()/*# : string */
    {
        $count = 0;
        $params = $this->params;
        return preg_replace_callback(
            '/\?|\:\w+/',
            function ($m) use ($count, $params) {
                if ('?' === $m[0]) {
                    $res = $params[$count++];
                } else {
                    $res = isset($params[$m[0]]) ? $params[$m[0]] :
                        $params[substr($m[0], 1)];
                }
                return $this->getDriver()->quote($res);
            },
            $this->sql
        );
    }