/*
(non-Javadoc)

@see edu.umd.cs.findbugs.classfile.IDatabaseFactory#createDatabase()
321711
@Override
    public E createDatabase() throws CheckedAnalysisException {
        E database;

        database = createUsingStaticCreateMethod();
        if (database != null) {
            return database;
        }

        database = createUsingConstructor();
        if (database != null) {
            return database;
        }

        throw new CheckedAnalysisException("Could not find a way to create database " + databaseClass.getName());
    }
1014238
public Database createDatabase(String instanceId, String databaseId) {
    // [START createDatabase]
    OperationFuture<Database, CreateDatabaseMetadata> op =
        dbAdminClient.createDatabase(
            instanceId,
            databaseId,
            Arrays.asList(
                "CREATE TABLE Singers (\n"
                    + "  SingerId   INT64 NOT NULL,\n"
                    + "  FirstName  STRING(1024),\n"
                    + "  LastName   STRING(1024),\n"
                    + "  SingerInfo BYTES(MAX)\n"
                    + ") PRIMARY KEY (SingerId)",
                "CREATE TABLE Albums (\n"
                    + "  SingerId     INT64 NOT NULL,\n"
                    + "  AlbumId      INT64 NOT NULL,\n"
                    + "  AlbumTitle   STRING(MAX)\n"
                    + ") PRIMARY KEY (SingerId, AlbumId),\n"
                    + "  INTERLEAVE IN PARENT Singers ON DELETE CASCADE"));
    Database db;
    try {
      db = op.get();
    } catch (ExecutionException e) {
      throw (SpannerException) e.getCause();
    } catch (InterruptedException e) {
      throw SpannerExceptionFactory.propagateInterrupt(e);
    }
    // [END createDatabase]
    return db;
  }
910444
private void generateOnCreate(String dataSourceNameClazz) {
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onCreate").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(Boolean.TYPE);

		methodBuilder.addJavadoc("<p>Create datasource and open database in read mode.</p>\n");
		methodBuilder.addJavadoc("\n");
		methodBuilder.addJavadoc("@see android.content.ContentProvider#onCreate()\n");

		methodBuilder.beginControlFlow("if ($T.getContext()==null)", KriptonLibrary.class);
		methodBuilder.addStatement("KriptonLibrary.init(getContext())");
		methodBuilder.endControlFlow();
		methodBuilder.addStatement("dataSource = $L.getInstance()", dataSourceNameClazz);
		methodBuilder.addStatement("dataSource.openWritableDatabase()");

		methodBuilder.addCode("return true;\n");

		classBuilder.addMethod(methodBuilder.build());
	}
220432
private static void deleteDatabase(String pathToDb)
    {
        File database = new File(pathToDb);
        if (database.exists()) {
            delete(database);
        }
        database.delete();
    }
479654
protected final <T> T createDataSource(Class<T> dataSourceClass) throws SQLException {
		if (getRealDataSourceClassName() == null) {
			throw new SQLException("Property realDataSourceClassName is not set");
		}
		try {
			T ds = dataSourceClass.cast(Class.forName(realDataSourceClassName).newInstance());
			for (Method m : ds.getClass().getMethods()) {
				String methodName = m.getName();
				if (methodName.startsWith("set") && m.getParameterTypes().length == 1) {
					final Object propertyValue;
					if (methodName.equals("setUser")) {
						propertyValue = getUser();
					} else if (methodName.equals("setPassword")) {
						propertyValue = getPassword();
					} else if (methodName.equalsIgnoreCase("setUrl")) {
						propertyValue = getRealUrl();
					} else if (methodName.equals("setLogWriter")) {
						propertyValue = getLogWriter();
					} else if (methodName.equals("setLoginTimeout")) {
						propertyValue = getLoginTimeout();
					} else {
						String propertyName = methodName.substring(3, 4).toLowerCase();
						if (methodName.length() > 4) {
							propertyName += methodName.substring(4);
						}
						final Class<?> propertyType = m.getParameterTypes()[0];
						propertyValue = getPropertyAs(propertyName, propertyType);
					}
					if (propertyValue != null) {
						m.invoke(ds, propertyValue);
					}
				}
			}
			return ds;

		} catch (Exception e) {
			throw new SQLException(e);
		}
	}
964929
@PostConstruct
    public void initDatabase() {
        MongoDBInit.LOGGER.info("initializing MongoDB");
        String dbName = System.getProperty("mongodb.name");
        if (dbName == null) {
            throw new RuntimeException("Missing database name; Set system property 'mongodb.name'");
        }
        MongoDatabase db = this.mongo.getDatabase(dbName);

        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:mongodb/*.ndjson");
            MongoDBInit.LOGGER.info("Scanning for collection data");
            for (Resource res : resources) {
                String filename = res.getFilename();
                String collection = filename.substring(0, filename.length() - 7);
                MongoDBInit.LOGGER.info("Found collection file: {}", collection);
                MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);
                try (Scanner scan = new Scanner(res.getInputStream(), "UTF-8")) {
                    int lines = 0;
                    while (scan.hasNextLine()) {
                        String json = scan.nextLine();
                        Object parse = JSON.parse(json);
                        if (parse instanceof DBObject) {
                            DBObject dbObject = (DBObject) parse;
                            dbCollection.insertOne(dbObject);
                        } else {
                            MongoDBInit.LOGGER.error("Invalid object found: {}", parse);
                            throw new RuntimeException("Invalid object");
                        }
                        lines++;
                    }
                    MongoDBInit.LOGGER.info("Imported {} objects into collection {}", lines, collection);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error importing objects", e);
        }
    }
874712
public DatabaseSession createDatabaseSession(BaseDatabase database, Map<String, Object> properties) throws RemoteException
    {
        DatabaseSession remoteDatabase = null;
        Map<String,Object> propOld = this.getProperties();
        this.setProperties(properties);
        DatabaseOwner databaseOwner = database.getDatabaseOwner();
        if (databaseOwner == null)
            databaseOwner = this.getDatabaseOwner();    // Never
        this.setProperties(propOld);
        if (databaseOwner instanceof Application)
            remoteDatabase = new DatabaseSession((Application)databaseOwner);   // Typical
        else
            remoteDatabase = new DatabaseSession((BaseSession)databaseOwner, null); // If AUTO_COMMIT if off, I need my own database
        database.setMasterSlave(RecordOwner.SLAVE);      // Don't create client behaviors
        remoteDatabase.setDatabase(database);
        return remoteDatabase;
    }
670091
public DataSource getDataSource(JdbcDatabase database)
    {
      com.mysql.jdbc.jdbc2.optional.MysqlDataSource dataSource = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
      this.setDatasourceParams(database, dataSource);
      return dataSource;
    }
611799
public static void createPropertiesTable( ASpatialDb database ) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLE ");
        sb.append(PROPERTIESTABLE);
        sb.append(" (");
        sb.append(ID);
        sb.append(" INTEGER PRIMARY KEY AUTOINCREMENT, ");
        sb.append(NAME).append(" TEXT, ");
        sb.append(SIZE).append(" REAL, ");
        sb.append(FILLCOLOR).append(" TEXT, ");
        sb.append(STROKECOLOR).append(" TEXT, ");
        sb.append(FILLALPHA).append(" REAL, ");
        sb.append(STROKEALPHA).append(" REAL, ");
        sb.append(SHAPE).append(" TEXT, ");
        sb.append(WIDTH).append(" REAL, ");
        sb.append(LABELSIZE).append(" REAL, ");
        sb.append(LABELFIELD).append(" TEXT, ");
        sb.append(LABELVISIBLE).append(" INTEGER, ");
        sb.append(ENABLED).append(" INTEGER, ");
        sb.append(ORDER).append(" INTEGER,");
        sb.append(DASH).append(" TEXT,");
        sb.append(MINZOOM).append(" INTEGER,");
        sb.append(MAXZOOM).append(" INTEGER,");
        sb.append(DECIMATION).append(" REAL,");
        sb.append(THEME).append(" TEXT");
        sb.append(" );");
        String query = sb.toString();
        database.executeInsertUpdateDeleteSql(query);
    }
957888
static synchronized SQLiteDatabase getDatabase() {
        if(sInstance == null) {
           throw new SprinklesNotInitializedException();
        }

        if(sDatabase == null) {
            DbOpenHelper dbOpenHelper = new DbOpenHelper(sInstance.mContext, sInstance.databaseName, sInstance.initialDatabaseVersion);
            sDatabase = dbOpenHelper.getWritableDatabase();
        }

        return sDatabase;
    }
1191069
func (host *Host) createDatabase() error {
	if _, err := host.db.Exec("CREATE DATABASE IF NOT EXISTS " + host.dbname + " CHARACTER SET = " + charset); err != nil {
		return err
	}
	if Verbose {
		log.Println("Created database " + host.dbname)
	}
	return nil
}
461520
func (s *Store) createDatabase() error {
	var db *sdb.DB
	var err error
	if !s.dbConf.Memory {
		// as it will be rebuilt from (possibly) a snapshot and committed log entries.
		if err := os.Remove(s.dbPath); err != nil && !os.IsNotExist(err) {
			return err
		}
		db, err = sdb.New(s.dbPath, s.dbConf.DSN, false)
		if err != nil {
			return err
		}
		s.logger.Println("SQLite database opened at", s.dbPath)
	} else {
		db, err = sdb.New(s.dbPath, s.dbConf.DSN, true)
		if err != nil {
			return err
		}
		s.logger.Println("SQLite in-memory database opened")
	}
	s.db = db
	return nil
}
596304
public synchronized OServerAdmin createDatabase(final String iDatabaseType, String iStorageMode) throws IOException {
    storage.checkConnection();

    try {
      if (storage.getName() == null || storage.getName().length() <= 0) {
        OLogManager.instance().error(this, "Cannot create unnamed remote storage. Check your syntax", OStorageException.class);
      } else {
        if (iStorageMode == null)
          iStorageMode = "csv";

        final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_CREATE);
        try {
          network.writeString(storage.getName());
          if (network.getSrvProtocolVersion() >= 8)
            network.writeString(iDatabaseType);
          network.writeString(iStorageMode);
        } finally {
          storage.endRequest(network);
        }

        storage.getResponse(network);

      }

    } catch (Exception e) {
      OLogManager.instance().error(this, "Cannot create the remote storage: " + storage.getName(), e, OStorageException.class);
      storage.close(true);
    }
    return this;
  }
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);
        }
    }
143239
public void addDatabase(Database database)
    {
        if (m_databaseCollection == null)
            m_databaseCollection = new DatabaseCollection(this);
        m_databaseCollection.addDatabase(database);
    }
1179187
protected DataSource createDataSource() {
    Driver driver = newInstance(Driver.class, driverClassName, "driverClassName");
    return globalFactory.createDataSource(driver, user, password, url);
  }
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
				}
			}
		}
	}