Creates DB and tables when necessary.<p>

@throws Exception in case creating DB or tables fails
500850
public void setupDB() throws Exception {

        if (m_bean.isInitialized()) {
            System.out.println("Setup-Bean initialized successfully.");
            CmsSetupDb db = new CmsSetupDb(m_bean.getWebAppRfsPath());
            try {
                // try to connect as the runtime user
                db.setConnection(
                    m_bean.getDbDriver(),
                    m_bean.getDbWorkConStr(),
                    m_bean.getDbConStrParams(),
                    m_bean.getDbWorkUser(),
                    m_bean.getDbWorkPwd(),
                    false);
                if (!db.noErrors()) {
                    // try to connect as the setup user
                    db.closeConnection();
                    db.clearErrors();
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbCreateConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbCreateUser(),
                        m_bean.getDbCreatePwd());
                }
                if (!db.noErrors() || !m_bean.validateJdbc()) {
                    throw new Exception("DB Connection test faild.");
                }
            } finally {
                db.clearErrors();
                db.closeConnection();
            }
        }

        System.out.println("DB connection tested successfully.");

        CmsSetupDb db = null;
        boolean dbExists = false;
        if (m_bean.isInitialized()) {
            if (m_props.isCreateDb() || m_props.isCreateTables()) {
                db = new CmsSetupDb(m_bean.getWebAppRfsPath());
                // check if database exists
                if (m_bean.getDatabase().startsWith("oracle")
                    || m_bean.getDatabase().startsWith("db2")
                    || m_bean.getDatabase().startsWith("as400")) {
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbWorkConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbWorkUser(),
                        m_bean.getDbWorkPwd());
                } else {
                    db.setConnection(
                        m_bean.getDbDriver(),
                        m_bean.getDbWorkConStr(),
                        m_bean.getDbConStrParams(),
                        m_bean.getDbCreateUser(),
                        m_bean.getDbCreatePwd(),
                        false);
                    dbExists = db.noErrors();
                    if (dbExists) {
                        db.closeConnection();
                    } else {
                        db.clearErrors();
                    }
                }
                if (!dbExists || m_props.isDropDb()) {
                    db.closeConnection();
                    if (!m_bean.getDatabase().startsWith("db2") && !m_bean.getDatabase().startsWith("as400")) {
                        db.setConnection(
                            m_bean.getDbDriver(),
                            m_bean.getDbCreateConStr(),
                            m_bean.getDbConStrParams(),
                            m_bean.getDbCreateUser(),
                            m_bean.getDbCreatePwd());
                    }
                }
            }
        }
        if (!m_props.isCreateDb() && !m_props.isCreateTables() && !dbExists) {
            throw new Exception("You have not created the Alkacon OpenCms database.");
        }
        if (dbExists && m_props.isCreateTables() && !m_props.isDropDb() && (db != null)) {
            throw new Exception("You have selected to not drop existing DBs, but a DB with the given name exists.");
        }
        if (dbExists && m_props.isCreateDb() && m_props.isDropDb() && (db != null)) {
            // drop the DB
            db.closeConnection();
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbCreateUser(),
                m_bean.getDbCreatePwd());
            db.dropDatabase(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while dropping the DB!");
            }
            System.out.println("Database dropped successfully.");
        }

        if (m_props.isCreateDb() && (db != null)) {
            // Create Database
            db.createDatabase(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while creating the DB!");
            }
            db.closeConnection();
            System.out.println("Database created successfully.");
        }

        if (m_props.isCreateTables() && (db != null)) {
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbWorkUser(),
                m_bean.getDbWorkPwd());
            //Drop Tables (intentionally quiet)
            db.dropTables(m_bean.getDatabase());
            db.clearErrors();
            db.closeConnection();
            // reopen the connection in order to display errors
            db.setConnection(
                m_bean.getDbDriver(),
                m_bean.getDbWorkConStr(),
                m_bean.getDbConStrParams(),
                m_bean.getDbWorkUser(),
                m_bean.getDbWorkPwd());
            //Create Tables
            db.createTables(m_bean.getDatabase(), m_bean.getReplacer());
            if (!db.noErrors()) {
                for (String error : db.getErrors()) {
                    System.err.println(error + "\n");
                    System.err.println(HR + "\n");
                }
                db.clearErrors();
                throw new Exception("Error ocurred while creating tables.");
            }
            db.closeConnection();
            System.out.println("Tables created successfully.");
        }
        if (db != null) {
            db.closeConnection();
        }
        System.out.println("Database setup was successful.");
    }
1082040
@Override
    public JdbcQueue<ID, DATA> init() throws Exception {
        SQL_COUNT = MessageFormat.format(SQL_COUNT, getTableName());
        SQL_COUNT_EPHEMERAL = MessageFormat.format(SQL_COUNT_EPHEMERAL, getTableNameEphemeral());

        if (jdbcHelper == null) {
            setJdbcHelper(buildJdbcHelper(), true);
        }

        super.init();

        if (jdbcHelper == null) {
            throw new IllegalStateException("JDBC helper is null.");
        }

        return this;
    }
914531
public function createDatabaseObject()
    {
        $dbname = trim($this->getSubmitValue('dbname'));
        if (empty($dbname)) // disallow database object creation w/ no selected database
        {
            throw new Exception("No database name");
        }

        $adapter = $this->getSubmitValue('adapter');
        $port = Adapter::getDefaultPortForAdapter($adapter);

        $host = $this->getSubmitValue('host');
        $tables_prefix = $this->getSubmitValue('tables_prefix');
        
        $dbInfos = array(
            'host'          => (is_null($host)) ? $host : trim($host),
            'username'      => $this->getSubmitValue('username'),
            'password'      => $this->getSubmitValue('password'),
            'dbname'        => $dbname,
            'tables_prefix' => (is_null($tables_prefix)) ? $tables_prefix : trim($tables_prefix),
            'adapter'       => $adapter,
            'port'          => $port,
            'schema'        => Config::getInstance()->database['schema'],
            'type'          => $this->getSubmitValue('type')
        );

        if (($portIndex = strpos($dbInfos['host'], '/')) !== false) {
            // unix_socket=/path/sock.n
            $dbInfos['port'] = substr($dbInfos['host'], $portIndex);
            $dbInfos['host'] = '';
        } else if (($portIndex = strpos($dbInfos['host'], ':')) !== false) {
            // host:port
            $dbInfos['port'] = substr($dbInfos['host'], $portIndex + 1);
            $dbInfos['host'] = substr($dbInfos['host'], 0, $portIndex);
        }

        try {
            @Db::createDatabaseObject($dbInfos);
        } catch (Zend_Db_Adapter_Exception $e) {
            $db = Adapter::factory($adapter, $dbInfos, $connect = false);

            // database not found, we try to create  it
            if ($db->isErrNo($e, '1049')) {
                $dbInfosConnectOnly = $dbInfos;
                $dbInfosConnectOnly['dbname'] = null;
                @Db::createDatabaseObject($dbInfosConnectOnly);
                @DbHelper::createDatabase($dbInfos['dbname']);

                // select the newly created database
                @Db::createDatabaseObject($dbInfos);
            } else {
                throw $e;
            }
        }

        return $dbInfos;
    }
1342355
public void createTable(TableSpec spec) throws SQLException {
        Statement s = createStatement();
        Iterator<String> iter = m_converter.getDDL(spec).iterator();
        while (iter.hasNext()) {
            String updateSQL = iter.next();
            s.executeUpdate(updateSQL);
        }
    }
400654
public void createDB() throws PlatformException
    {
        if (_creationScript == null)
        {
            createCreationScript();
        }

        Project             project    = new Project();
        TorqueDataModelTask modelTask  = new TorqueDataModelTask();
        File                tmpDir     = null;
        File                scriptFile = null;
        
        try
        {
            tmpDir = new File(getWorkDir(), "schemas");
            tmpDir.mkdir();

            scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);

            writeCompressedText(scriptFile, _creationScript);

            project.setBasedir(tmpDir.getAbsolutePath());

            // we use the ant task 'sql' to perform the creation script
	        SQLExec         sqlTask = new SQLExec();
	        SQLExec.OnError onError = new SQLExec.OnError();
	
	        onError.setValue("continue");
	        sqlTask.setProject(project);
	        sqlTask.setAutocommit(true);
	        sqlTask.setDriver(_jcd.getDriver());
	        sqlTask.setOnerror(onError);
	        sqlTask.setUserid(_jcd.getUserName());
	        sqlTask.setPassword(_jcd.getPassWord() == null ? "" : _jcd.getPassWord());
	        sqlTask.setUrl(getDBCreationUrl());
	        sqlTask.setSrc(scriptFile);
	        sqlTask.execute();

	        deleteDir(tmpDir);
        }
        catch (Exception ex)
        {
            // clean-up
            if ((tmpDir != null) && tmpDir.exists())
            {
                try
                {
                    scriptFile.delete();
                }
                catch (NullPointerException e) 
                {
                    LoggerFactory.getLogger(this.getClass()).error("NPE While deleting scriptFile [" + scriptFile.getName() + "]", e);
                }
            }
            throw new PlatformException(ex);
        }
    }
1283876
public synchronized void initialize() throws DatabaseException {
        //this only needs to be called once.
        if (connectionString != null) {
            return;
        }
        Connection conn = null;
        try {
            //load the driver if necessary
            final String driverName = settings.getString(Settings.KEYS.DB_DRIVER_NAME, "");
            final String driverPath = settings.getString(Settings.KEYS.DB_DRIVER_PATH, "");
            LOGGER.debug("Loading driver '{}'", driverName);
            try {
                if (!driverPath.isEmpty()) {
                    LOGGER.debug("Loading driver from: {}", driverPath);
                    driver = DriverLoader.load(driverName, driverPath);
                } else {
                    driver = DriverLoader.load(driverName);
                }
            } catch (DriverLoadException ex) {
                LOGGER.debug("Unable to load database driver", ex);
                throw new DatabaseException("Unable to load database driver", ex);
            }
            userName = settings.getString(Settings.KEYS.DB_USER, "dcuser");
            //yes, yes - hard-coded password - only if there isn't one in the properties file.
            password = settings.getString(Settings.KEYS.DB_PASSWORD, "DC-Pass1337!");
            try {
                connectionString = settings.getConnectionString(
                        Settings.KEYS.DB_CONNECTION_STRING,
                        Settings.KEYS.DB_FILE_NAME);
            } catch (IOException ex) {
                LOGGER.debug("Unable to retrieve the database connection string", ex);
                throw new DatabaseException("Unable to retrieve the database connection string", ex);
            }

            boolean shouldCreateSchema = false;
            try {
                if (connectionString.startsWith("jdbc:h2:file:")) { //H2
                    shouldCreateSchema = !h2DataFileExists();
                    LOGGER.debug("Need to create DB Structure: {}", shouldCreateSchema);
                }
            } catch (IOException ioex) {
                LOGGER.debug("Unable to verify database exists", ioex);
                throw new DatabaseException("Unable to verify database exists", ioex);
            }
            LOGGER.debug("Loading database connection");
            LOGGER.debug("Connection String: {}", connectionString);
            LOGGER.debug("Database User: {}", userName);

            try {
                if (connectionString.toLowerCase().contains("integrated security=true")
                        || connectionString.toLowerCase().contains("trusted_connection=true")) {
                    conn = DriverManager.getConnection(connectionString);
                } else {
                    conn = DriverManager.getConnection(connectionString, userName, password);
                }
            } catch (SQLException ex) {
                if (ex.getMessage().contains("java.net.UnknownHostException") && connectionString.contains("AUTO_SERVER=TRUE;")) {
                    connectionString = connectionString.replace("AUTO_SERVER=TRUE;", "");
                    try {
                        conn = DriverManager.getConnection(connectionString, userName, password);
                        settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
                        LOGGER.debug("Unable to start the database in server mode; reverting to single user mode");
                    } catch (SQLException sqlex) {
                        LOGGER.debug("Unable to connect to the database", ex);
                        throw new DatabaseException("Unable to connect to the database", ex);
                    }
                } else {
                    LOGGER.debug("Unable to connect to the database", ex);
                    throw new DatabaseException("Unable to connect to the database", ex);
                }
            }
            if (shouldCreateSchema) {
                try {
                    createTables(conn);
                } catch (DatabaseException dex) {
                    LOGGER.debug("", dex);
                    throw new DatabaseException("Unable to create the database structure", dex);
                }
            }
            try {
                ensureSchemaVersion(conn);
            } catch (DatabaseException dex) {
                LOGGER.debug("", dex);
                throw new DatabaseException("Database schema does not match this version of dependency-check", dex);
            }
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    LOGGER.debug("An error occurred closing the connection", ex);
                }
            }
        }
    }
1140138
public function create()
        {
            $sql = $this->generateCreateSql();
            $query = new RawQuery($sql);
            try {
                $this->drop();
                return Statement::getPreparedStatement($query)->execute();
            } catch (\Exception $e) {
                throw new Exception('Error creating table ' . $this->getB2DBName() . ': ' . $e->getMessage(), $sql);
            }
        }
423406
@Override
	public void createResource() throws Exception {
		cluster = builder.getCluster();
		session = cluster.connect();

		session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s with replication={'class':'SimpleStrategy', 'replication_factor':1};", keySpace));
		session.execute(String.format("CREATE TABLE IF NOT EXISTS %s.%s (sink_id text, sub_id int, checkpoint_id bigint, PRIMARY KEY (sink_id, sub_id));", keySpace, table));

		try {
			session.close();
		} catch (Exception e) {
			LOG.error("Error while closing session.", e);
		}
		try {
			cluster.close();
		} catch (Exception e) {
			LOG.error("Error while closing cluster.", e);
		}
	}
108744
@Override
  public void create()
    throws IOException
  {
    Files.createDirectories(_path.getParent());

    if (Files.exists(_path)) {
      throw new IOException(L.l("CREATE for path '{0}' failed, because the file already exists.  CREATE can not override an existing table.",
                                _path));
    }
    
    init();
    /*
    _channel = _path.openFileChannel(StandardOpenOption.CREATE, 
                                     StandardOpenOption.WRITE,
                                     StandardOpenOption.READ);
    
    setFileSize(_path.length());
    
    initImpl();
    */
  }
1296622
public function create() {
        $migration = $this->getMessages();
        if (!$migration) {
            $this->db()->insert($this->table, array('migration' => get_class($this), 'state' => false));
        } else {
            throw new \Exception('Migration ' .  get_class($this) . ' already created');
        }
    }
897727
@Override
    protected void create(List<TableInfo> tableInfos)
    {

        for (TableInfo tableInfo : tableInfos)
        {
            try
            {
                if (client.tableExists(tableInfo.getTableName()))
                {
                    client.deleteTable(tableInfo.getTableName());
                }
            }
            catch (Exception e)
            {
                logger.error("Cannot check table existence for table " + tableInfo.getTableName() + ". Caused By: " + e);
                throw new KunderaException("Cannot check table existence for table " + tableInfo.getTableName()
                        + ". Caused By: " + e);
            }
            createKuduTable(tableInfo);
        }
    }
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();
		}
	}
838206
@Override
	public void createDb(String dbName) {
	    String dbPath = toPath(dbName);
        LOGGER.info("Creating DB file: {}", dbPath);
        String folderPath = dbPath.substring(0, dbPath.lastIndexOf(File.separator));
        File dbDir = new File(folderPath);
        if (!dbDir.exists()) {
            createDbFolder(dbDir);
            LOGGER.info("Creating DB folder: {}", dbDir.getAbsolutePath());
        }

		
		//create files
		IOResourceProvider file = null;
		StorageRoot root = null;
		try {
			//DB file
			File dbFile = new File(toPath(dbName));
			if (dbFile.exists()) {
				throw DBLogger.newUser("ZOO: DB already exists: " + dbFile);
			}
			if (!dbFile.createNewFile()) {
				throw DBLogger.newUser("ZOO: Error creating DB file: " + dbFile);
			}
			FreeSpaceManager fsm = new FreeSpaceManager();
			root = new StorageRootFile(dbPath, "rw",
					ZooConfig.getFilePageSize(), fsm);
			file = root.createChannel();
			StorageChannelOutput out = file.createWriter(false);
			fsm.initBackingIndexNew(file);
			
			int headerPage = out.allocateAndSeek(PAGE_TYPE.DB_HEADER, 0);
			if (headerPage != 0) {
				throw DBLogger.newFatalInternal("Header page = " + headerPage);
			}
			int rootPage1 = out.allocateAndSeek(PAGE_TYPE.ROOT_PAGE, 0);
			int rootPage2 = out.allocateAndSeek(PAGE_TYPE.ROOT_PAGE, 0);

			//header: this is written further down
			
			//write User data
			int userData = out.allocateAndSeek(PAGE_TYPE.USERS, 0);
			
			
			//dir for schemata
			int schemaData = out.allocateAndSeekAP(PAGE_TYPE.SCHEMA_INDEX, 0, -1);
			//ID of next page
			out.writeInt(0);
			//Schema ID / schema data (page or actual data?)
			//0 for no more schemata
			out.writeInt(0);

			
			//dir for indices
			int indexDirPage = out.allocateAndSeek(PAGE_TYPE.INDEX_CATALOG, 0);
			//ID of next page
			out.writeInt(0);
			//Schema ID / attribute ID / index type / Page ID
			//0 for nor more indices
			out.writeInt(0);

			//OID index
			PagedOidIndex oidIndex = new PagedOidIndex(file);
//			bootstrapSchema(raf, oidIndex);
			int oidPage = file.writeIndex(oidIndex::write);

			//Free space index
			int freeSpacePg = file.writeIndex(fsm::write);
			
			//write header
			out.seekPageForWrite(PAGE_TYPE.DB_HEADER, headerPage);
			out.writeInt(DiskIO.DB_FILE_TYPE_ID);
			out.writeInt(DiskIO.DB_FILE_VERSION_MAJ);
			out.writeInt(DiskIO.DB_FILE_VERSION_MIN);
			out.writeInt(ZooConfig.getFilePageSize());
			out.writeInt(rootPage1);
			out.writeInt(rootPage2);
			
			writeRoot(out, rootPage1, 1, userData, oidPage, schemaData, indexDirPage, freeSpacePg, 
					fsm.getPageCount());
			writeRoot(out, rootPage2, 0, userData, oidPage, schemaData, indexDirPage, freeSpacePg, 
					fsm.getPageCount());
			
			
			file.close();
			file = null;
			root.close();
			root = null;
			out = null;


			//initial schemata
			Properties props = new ZooJdoProperties(dbName);
			PersistenceManagerFactory pmf = 
				JDOHelper.getPersistenceManagerFactory(props);
			PersistenceManager pm = pmf.getPersistenceManager();
			pm.currentTransaction().begin();
			
			ZooSchema schema = ZooJdoHelper.schema(pm);
			schema.addClass(PersistenceCapableImpl.class);
			schema.addClass(DBHashMap.class);
			schema.addClass(DBArrayList.class);
			
			pm.currentTransaction().commit();
			pm.close();
			pmf.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw DBLogger.newUser("ERROR While creating database: " + dbPath, e);
		} finally {
			if (file != null) {
				try {
					file.close();
				} catch (JDOException e) {
					e.printStackTrace();
					//ignore
				}
			}
		}
	}
773132
@Override
  public final void createDatabase(final String pDbName,
    final int pDbId) throws Exception {
    String dbNm = this.databasePrefix + pDbName + ".sqlite";
    synchronized (this.factoryAppBeans) {
      if (!this.factoryAppBeans.getDatabaseName().equals(dbNm)) {
        this.factoryAppBeans.setDatabaseName(dbNm);
        this.factoryAppBeans.setNewDatabaseId(pDbId);
        this.factoryAppBeans.handleDatabaseChanged();
      }
    }
  }
1049659
private void createTables(Connection conn) throws DatabaseException {
        LOGGER.debug("Creating database structure");

        try (InputStream is = FileUtils.getResourceAsStream(DB_STRUCTURE_RESOURCE)) {
            final String dbStructure = IOUtils.toString(is, StandardCharsets.UTF_8);

            Statement statement = null;
            try {
                statement = conn.createStatement();
                statement.execute(dbStructure);
            } catch (SQLException ex) {
                LOGGER.debug("", ex);
                throw new DatabaseException("Unable to create database statement", ex);
            } finally {
                DBUtils.closeStatement(statement);
            }
        } catch (IOException ex) {
            throw new DatabaseException("Unable to create database schema", ex);
        }
    }
906954
protected void createUserDataTable(CmsSetupDb dbCon) throws SQLException {

        System.out.println(new Exception().getStackTrace()[0].toString());
        String createStatement = readQuery(QUERY_CREATE_TABLE_USERDATA);
        dbCon.updateSqlStatement(createStatement, null, null);
    }
559705
public final void execute()
  {
    _log.debug( _sqlString );

    CallableStatement lCallableStatement = null;

    try
    {
      lCallableStatement = _callableStatementProvider.createCallableStatement( _sqlString );

      useCallableStatement( lCallableStatement );
    }
    catch( SQLException e )
    {
      _log.debug( e + ": " + _sqlString, e );

      throw ExceptionManager.createException( e, _sqlString );
    }
    finally
    {
      if( lCallableStatement != null )
      {
        try
        {
          lCallableStatement.close();
        }
        catch( SQLException e )
        {
          _log.debug( e, e );

          throw ExceptionManager.createException( e, _sqlString );
        }
      }
    }
  }