Used to programatically create a database table. Does nothing if the table already exists.

@return true if the table was created, false if it already existed.
483273
public static boolean createTableIfMissing (
        Connection conn, String table, String[] definition, String postamble)
        throws SQLException
    {
        if (tableExists(conn, table)) {
            return false;
        }

        Statement stmt = conn.createStatement();
        try {
            stmt.executeUpdate("create table " + table +
                               "(" + StringUtil.join(definition, ", ") + ") " + postamble);
        } finally {
            close(stmt);
        }

        log.info("Database table '" + table + "' created.");
        return true;
    }
119252
public boolean exists(){
        return null != new DB(metaModelLocal.getDbName()).firstCell(metaModelLocal.getDialect().selectExists(metaModelLocal), getId());
    }
740568
protected function createTable()
    {
        if ($this->db->schema->getTableSchema($this->sessionTable) === null) {
            $cmd = $this->db->createCommand();
            $cmd->createTable($this->sessionTable, [
                'id' => 'CHAR(40) PRIMARY KEY',
                'expire' => 'integer',
                'data' => 'binary',
            ])->execute();
        }
    }
411501
public static final boolean createTableIfNotExists(final AmazonDynamoDB dynamo, final CreateTableRequest createTableRequest) {
        try {
            dynamo.createTable(createTableRequest);
            return true;
        } catch (final ResourceInUseException e) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Table " + createTableRequest.getTableName() + " already exists", e);
            }
        }
        return false;
    }
83690
protected function createSqliteDatabase()
    {
        $dbPath = config('database.connections.sqlite.database');
        $createDb = new Process("touch $dbPath");
        $createDb->run();

        if (! $createDb->isSuccessful()) {
            $this->warn("I couldn't create your SQLite database file.");
            $this->warn("Please create it after setup is complete and re-run setup.");
            $this->warn("Run `touch database/database.sqlite`");
            Storage::put('installer', '1');
            logger('NETWORK.INSTALL: Failed to create SQLite database');
            $this->hasError = true;

            return false;
        }

        $this->info("Database created at $dbPath.");

        return true;
    }
1063690
void createTable() {
        Connection con = null;
        java.sql.Statement s = null;

        //PK55900 We can pass in true to the getConnection method since this method,
        //createTable, is only called from the initDBSettings method.
        con = getConnection(true);
        if (con == null) {
            return;
        }

        try {

            try {
                s = con.createStatement();
                if (!getTableDefinition(con)) {
                    if (usingOracle) {
                        if (_smc.isUseOracleBlob()) { // cmd LI1963 start
                            s.executeUpdate("create table "
                                            + tableName
                                            + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess integer, creationtime integer, maxinactivetime integer, username varchar(256), small raw("
                                            + SMALLCOL_SIZE_ORACLE + "), medium BLOB, large raw(1))");
                        } else {
                            s.executeUpdate("create table "
                                            + tableName
                                            + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess integer, creationtime integer, maxinactivetime integer, username varchar(256), small raw("
                                            + SMALLCOL_SIZE_ORACLE + "), medium long raw, large raw(1))");
                        } // cmd LI1963 end
                    } else if (usingAS400DB2) {
                        try { //if using AS400, create collection first
                            s.executeUpdate("CREATE COLLECTION " + collectionName);
                        } catch (Exception e) {
                            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.store.db.DatabaseHashMap.createTable", "470", con);
                        }
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess bigint, creationtime bigint, maxinactivetime integer, username varchar(256), small varchar("
                                        + SMALLCOL_SIZE_DB2 + ") for bit data, medium long varchar for bit data, large BLOB(2M))");
                    } else if (usingSybase) {
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint null, lastaccess numeric(21,0) null, creationtime numeric(21,0) null, maxinactivetime numeric(10,0) null, username varchar(255) null, small image null, medium image null, large image null)");
                    } else if (usingSQLServer) {
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint null, lastaccess decimal(21,0) null, creationtime decimal(21,0) null, maxinactivetime integer null, username varchar(255) null, small image null, medium image null, large image null)");
                    } else if (usingInformix) {
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess int8, creationtime int8, maxinactivetime integer, username varchar(255), small BYTE, medium BYTE, large BYTE)");
                    } else if (usingCloudScape) {
                        s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess bigint, creationtime bigint, maxinactivetime integer, username varchar(255), small LONG VARBINARY , medium char(1) , large char(1))");
                    } else if (dbHandler != null) {
                        dbHandler.createTable(s, tableName);
                    } else if (!usingDB2Connect && !usingDB2zOS) { // LIDB2775.25 zOS
                        String tableSpaceName = " ";
                        // a little overkill for this test
                        String configTableSpaceName = _smc.getTableSpaceName();
                        if (configTableSpaceName != null && !configTableSpaceName.equals("") && configTableSpaceName.length() != 0)
                            tableSpaceName = " in " + configTableSpaceName;
                        if (usingSolidDB)
                            s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess bigint, creationtime bigint, maxinactivetime integer, username varchar(256), small varchar("
                                        + smallColSize + "), medium long varchar, large BLOB(2M)) " + tableSpaceName);
                        else
                            s.executeUpdate("create table "
                                        + tableName
                                        + " (id varchar(128) not null, propid varchar(128) not null, appname varchar(128) not null, listenercnt smallint, lastaccess bigint, creationtime bigint, maxinactivetime integer, username varchar(256), small varchar("
                                        + smallColSize + ") for bit data, medium long varchar for bit data, large BLOB(2M)) " + tableSpaceName);
                    }
                }
                //            } catch (com.ibm.ejs.cm.portability.TableAlreadyExistsException eee) {
                //                // Do nothing since all is well!!
                //                com.ibm.ws.ffdc.FFDCFilter.processException(eee, "com.ibm.ws.session.store.db.DatabaseHashMap.createTable", "495", this);
            } catch (SQLException err) {
                com.ibm.ws.ffdc.FFDCFilter.processException(err, "com.ibm.ws.session.store.db.DatabaseHashMap.createTable", "497", this);
                if (!usingCloudScape) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[CREATE_TABLE], "CommonMessage.exception", err);
                } else {
                    if (err.getErrorCode() != 30000)
                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[CREATE_TABLE], "CommonMessage.exception", err);
                }
            }

            if (!_smc.isSessionTableSkipIndexCreation()) { // PM37139

                //Creating index in a seperate step as we have seen customers missing this
                //step when they create the table manually
                try {
                    if (s == null)
                        s = con.createStatement();
                    if (usingSybase) {
                        s.executeUpdate("create unique index sess_index on " + tableName + " (id, propid, appname)");
                        s.executeUpdate("alter table sessions lock datarows");
                    } else if (usingSolidDB) {
                        s.executeUpdate("create unique index sess_index on " + tableName + " (id, propid, appname)");
                    } else if (usingAS400DB2) {
                        mediumColSize = mediumColSize - 2; //d154211
                        //PK56991: If multiple cluster members startup at the same time the
                        // combination of these DDLs can lock up for a substantial duration.
                        // We now execute these only if they do not exist.
                        if (!doesIndexExists(con, "sess_index")) {
                            s.executeUpdate("create unique index " + collectionName + ".sess_index on " + tableName + " (id,propid,appname)"); //tableName is already in the form of "collectionName.tableName"
                            //PK56991 comment out marking table as volatile. The DB2 chief architect on iSeries
                            //team informed that VOLATILE clause is only compatible and improve performance on LUW
                            //s.executeUpdate("alter table " + tableName + " volatile");
                        } else if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[CREATE_TABLE], "Skip index creation");
                        }
                    } else if (dbHandler != null) {
                        dbHandler.createIndex(con, s, tableName);
                    } else if (!usingDB2Connect && !usingDB2zOS) { // LIDB2775.25
                        //PK56991: Refer to detailed comment above
                        if (!doesIndexExists(con, "sess_index")) {
                            s.executeUpdate("create unique index sess_index on " + tableName + " (id, propid, appname)");//PK86373: changed sesscmd_index to sess_index
                        } else if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[CREATE_TABLE], "Skip index creation");
                        }
                        //PK56991: We are marking the the session table as volatile if it is not
                        //done yet.
                        if (usingDB2 && !isTableMarkedVolatile(con)) {
                            s.executeUpdate("alter table " + tableName + " volatile");
                        } else if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[CREATE_TABLE], "Skip marking table volatile");
                        }

                    }
                } catch (SQLException err) {
                    //Don't do any thing if it is only index already exists
                    //err.printStackTrace();
                    com.ibm.ws.ffdc.FFDCFilter.processException(err, "com.ibm.ws.session.store.db.DatabaseHashMap.createTable", "526", con);
                }
            } // END PM37139
        } finally {
            if (s != null)
                closeStatement(s);
                closeConnection(con); //findbugs for 106329
        }
    }
925543
public boolean createTableIfMissing (Connection conn, String table, List<String> columns,
                                         List<ColumnDefinition> definitions,
                                         List<List<String>> uniqueConstraintColumns,
                                         List<String> primaryKeyColumns)
        throws SQLException
    {
        if (tableExists(conn, table)) {
            return false;
        }
        if (columns.size() != definitions.size()) {
            throw new IllegalArgumentException("Column name and definition number mismatch");
        }

        StringBuilder builder = new StringBuilder("CREATE TABLE ").
            append(tableSQL(table)).append(" (");
        for (int ii = 0; ii < columns.size(); ii ++) {
            if (ii > 0) {
                builder.append(", ");
            }
            builder.append(columnSQL(columns.get(ii))).append(" ");
            builder.append(expandDefinition(definitions.get(ii)));
        }

        if (uniqueConstraintColumns != null) {
            for (List<String> uCols : uniqueConstraintColumns) {
                builder.append(", UNIQUE (");
                appendColumns(uCols, builder);
                builder.append(")");
            }
        }

        if (primaryKeyColumns != null && !primaryKeyColumns.isEmpty()) {
            builder.append(", PRIMARY KEY (");
            appendColumns(primaryKeyColumns, builder);
            builder.append(")");
        }

        builder.append(")");

        executeQuery(conn, builder.toString());
        log("Database table '" + table + "' created.");
        return true;
    }
979958
public static boolean createTableIfNotExists(final Connection conn, final String tableName, final String schema) {
        if (doesTableExist(conn, tableName)) {
            return false;
        }

        try {
            execute(conn, schema);

            return true;
        } catch (SQLException e) {
            return false;
        }
    }
842178
public function create () : bool
	{
        $dbObject 	= Database::getInstance();
		$attributes = $this->sanitizedAttributes();
		$sqlQuery	= "INSERT INTO ".static::$tableName." (";
		$sqlQuery  .= join(", ", array_keys($attributes));
	  	$sqlQuery  .= ") VALUES ('";
		$sqlQuery  .= join("', '", array_values($attributes));
		$sqlQuery  .= "')";
		$result 	= $dbObject->query($sqlQuery);
    	$this->id 	= $dbObject->insertId();
    	return ($result) ? TRUE : FALSE;
	}
871671
def createTable(self, tableName, strFields) :
		''
		if not self.tableExits(tableName) :
			sql = 'CREATE TABLE %s ( %s)' % (tableName, strFields)
			self.execute(sql)
			self.tables.add(tableName)
			return True
		return False
376034
private TableIndex getOrCreateTableIndex() {
		TableIndex tableIndex = getTableIndex();

		if (tableIndex == null) {
			try {
				if (!tableIndexDao.isTableExists()) {
					geoPackage.createTableIndexTable();
				}

				tableIndex = new TableIndex();
				tableIndex.setTableName(tableName);
				tableIndex.setLastIndexed(null);

				tableIndexDao.create(tableIndex);
			} catch (SQLException e) {
				throw new GeoPackageException(
						"Failed to create Table Index for GeoPackage: "
								+ geoPackage.getName() + ", Table Name: "
								+ tableName + ", Column Name: " + columnName, e);
			}
		}

		return tableIndex;
	}
1159206
private boolean storeExists(String tableName) {
        KeyspaceMetadata ksMetadata = m_cluster.getMetadata().getKeyspace(m_keyspace);
        return (ksMetadata != null) && (ksMetadata.getTable(tableName) != null);
    }
675862
private boolean generateOnCreate(SQLiteDatabaseSchema schema, List<SQLiteEntity> orderedEntities) {
		boolean useForeignKey = false;
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onCreate").addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC);
		methodBuilder.addParameter(SQLiteDatabase.class, "database");
		methodBuilder.addJavadoc("onCreate\n");
		methodBuilder.addCode("// generate tables\n");
		if (schema.isLogEnabled()) {
			// generate log section - BEGIN
			methodBuilder.addComment("log section create BEGIN");
			methodBuilder.beginControlFlow("if (this.logEnabled)");

			methodBuilder.beginControlFlow("if (options.inMemory)");
			methodBuilder.addStatement("$T.info(\"Create database in memory\")", Logger.class);
			methodBuilder.nextControlFlow("else");
			methodBuilder.addStatement("$T.info(\"Create database '%s' version %s\",this.name, this.version)",
					Logger.class);
			methodBuilder.endControlFlow();

			// generate log section - END
			methodBuilder.endControlFlow();
			methodBuilder.addComment("log section create END");
		}
		for (SQLiteEntity item : orderedEntities) {
			if (schema.isLogEnabled()) {
				// generate log section - BEGIN
				methodBuilder.addComment("log section create BEGIN");
				methodBuilder.beginControlFlow("if (this.logEnabled)");

				methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class,
						BindTableGenerator.tableClassName(null, item));

				// generate log section - END
				methodBuilder.endControlFlow();
				methodBuilder.addComment("log section create END");
			}
			methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)",
					BindTableGenerator.tableClassName(null, item));

			if (item.referedEntities.size() > 0) {
				useForeignKey = true;
			}
		}

		// use generated entities too
		// if we have generated entities, we use foreign key for sure
		if (schema.generatedEntities.size() > 0)
			useForeignKey = true;
		for (GeneratedTypeElement item : schema.generatedEntities) {
			if (schema.isLogEnabled()) {
				// generate log section - BEGIN
				methodBuilder.addComment("log section BEGIN");
				methodBuilder.beginControlFlow("if (this.logEnabled)");

				methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class,
						TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));

				// generate log section - END
				methodBuilder.endControlFlow();
				methodBuilder.addComment("log section END");
			}
			methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)",
					TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));

		}

		methodBuilder.beginControlFlow("if (options.databaseLifecycleHandler != null)");
		methodBuilder.addStatement("options.databaseLifecycleHandler.onCreate(database)");
		methodBuilder.endControlFlow();

		methodBuilder.addStatement("justCreated=true");

		classBuilder.addMethod(methodBuilder.build());

		return useForeignKey;
	}
951123
public function tableExists()
    {
        $dbh    = $this->db();
        $table  = $this->table();
        $driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
        if ($driver === self::SQLITE_DRIVER_NAME) {
            $query = sprintf('SELECT name FROM sqlite_master WHERE type = "table" AND name = "%s";', $table);
        } else {
            $query = sprintf('SHOW TABLES LIKE "%s"', $table);
        }

        $this->logger->debug($query);
        $sth    = $dbh->query($query);
        $exists = $sth->fetchColumn(0);

        return !!$exists;
    }
56570
public boolean validateJdbc() {

        boolean result = false;
        String libFolder = getLibFolder();
        Iterator<String> it = getDatabaseLibs(getDatabase()).iterator();
        while (it.hasNext()) {
            String libName = it.next();
            File libFile = new File(libFolder, libName);
            if (libFile.exists()) {
                result = true;
            }
        }
        return result;
    }
376595
@Override
	public void createDb(String dbName) {
		String dbPath = getDbPath(dbName);
		if (map.containsKey(dbPath)) {
			throw DBLogger.newUser("Database already exists: " + dbPath);
		}
		map.put(dbPath, new ArrayList<ByteBuffer>());
		
		//create files

		//DB file
		FreeSpaceManager fsm = new FreeSpaceManager();
		StorageRootInMemory root = 
				new StorageRootInMemory(dbPath, "rw", ZooConfig.getFilePageSize(), fsm);
		IOResourceProvider 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);
		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();
	}
18114
private WDataTable createTable() {
		WDataTable table = new WDataTable();
		table.addColumn(new WTableColumn("First name", new WTextField()));
		table.addColumn(new WTableColumn("Last name", new WTextField()));
		table.addColumn(new WTableColumn("DOB", new WDateField()));
		table.addColumn(new WTableColumn("Action", new ExampleButton()));
		table.setExpandMode(ExpandMode.CLIENT);

		table.setDataModel(createTableModel());

		return table;
	}