/*
(non-Javadoc)

@see
com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create
(java.util.List)
329420
@Override
    protected void create(List<TableInfo> tableInfos)
    {

        if (clusterManager.hasBucket(databaseName))
        {
            /*
             * Removing bucket will drop indexes too
             * 
             */
            removeBucket(databaseName);
        }
        addBucket(databaseName);
        createIdIndex(databaseName);
    }
806465
@Nonnull
  public ApiFuture<WriteResult> create(@Nonnull Map<String, Object> fields) {
    WriteBatch writeBatch = firestore.batch();
    return extractFirst(writeBatch.create(this, fields).commit());
  }
174521
@Override
    public <P> void pojoDaoCreated(PojoDaoFactoryEvent<P> event) {
        Schema schema = new Schema();
        event.getPojoBinding().describe(schema.createTable(event.getTableName()), schema);
        List<SchemaStatement> statements = schema.items().map(SchemaItem::createStatement).collect(Collectors.toList());
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Creating table(s) to support \"{}\":\n\t{}\n", event.getPojoBinding().getPojoType().getSimpleName(), statements.stream().map(SchemaStatement::getQueryString).collect(Collectors.joining("\n\t")));
        }
        statements.forEach(session::execute);
    }
468276
@Override
	public Map<String, Object> createRecord(final ResultSet rs) throws SQLException {
		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();
		Map<String, Object> record = new LinkedHashMap<>(columnCount);
		for (int i = 1; i <= columnCount; i++) {
			record.put(caseFormat.convert(rsmd.getColumnLabel(i)), getValue(rs, rsmd, i));
		}
		return record;
	}
266215
@Override
    public void create(SchemaMigrationMetadata metadata) {
        session.execute(
                insertInto(METADATA_TABLE)
                        .ifNotExists()
                        .value(ID_COL, metadata.getId())
                        .value(INDEX_COL, metadata.getIndex())
                        .value(TOKEN_COL, metadata.getToken())
                        .value(STATUS_COL, metadata.getStatus().name())
                        .value(FINGERPRINT_COL, metadata.getFingerprint()));
    }
637336
private void createSchema() throws SQLException {
		logger.entering(CLASSNAME, "createSchema");
		Connection conn = getConnectionToDefaultSchema();

		logger.log(Level.INFO, schema + " schema does not exists. Trying to create it.");
		PreparedStatement ps = null;
		ps = conn.prepareStatement("CREATE SCHEMA " + schema);
		ps.execute();

		cleanupConnection(conn, null, ps);
		logger.exiting(CLASSNAME, "createSchema");
	}
860161
void createPublicSchema() {

        HsqlName name = database.nameManager.newHsqlName(null,
            SqlInvariants.PUBLIC_SCHEMA, SchemaObject.SCHEMA);
        Schema schema = new Schema(name,
                                   database.getGranteeManager().getDBARole());

        defaultSchemaHsqlName = schema.name;

        schemaMap.put(schema.name.name, schema);
    }
474127
def create(self, collection, **kw):
		
		
		options = dict(
				name = self.__name__,
				unique = self.unique,
				background = self.background,
				sparse = self.sparse,
				expireAfterSeconds = self.expire,
				partialFilterExpression = self.partial,
				bucketSize = self.bucket,
				min = self.min,
				max = self.max,
			)
		options.update(kw)
		
		# Clear null options.
		for key in list(options):
			if options[key] is None:
				del options[key]
		
		return collection.create_index(self.fields, **options)
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;
	}
899592
@Override
    public <T> T create(EntityCreateOperation<T> creator)
            throws ServiceException {
        try {
            return service.create(creator);
        } catch (UniformInterfaceException e) {
            throw processCatch(new ServiceException(e));
        } catch (ClientHandlerException e) {
            throw processCatch(new ServiceException(e));
        }
    }
568691
@Override
    public void create(TaskRecord taskRecord) throws Exception {
        Task task = new Task(taskRecord);
        EntityManager em = getPersistenceServiceUnit().createEntityManager();
        try {
            em.persist(task);
            em.flush();
            taskRecord.setId(task.ID);
        } finally {
            em.close();
        }
    }
942555
public void createIndex(String collectionName, List<String> columnList, int order)
    {
        DBCollection coll = mongoDb.getCollection(collectionName);

        List<DBObject> indexes = coll.getIndexInfo(); // List of all current
        // indexes on collection
        Set<String> indexNames = new HashSet<String>(); // List of all current
        // index names
        for (DBObject index : indexes)
        {
            BasicDBObject obj = (BasicDBObject) index.get("key");
            Set<String> set = obj.keySet(); // Set containing index name which
            // is key
            indexNames.addAll(set);
        }

        // Create index if not already created
        for (String columnName : columnList)
        {
            if (!indexNames.contains(columnName))
            {
                KunderaCoreUtils.printQuery("Create index on:" + columnName, showQuery);
                coll.createIndex(new BasicDBObject(columnName, order));
            }
        }
    }
49212
protected void createIndexesOnColumns(EntityMetadata m, String tableName, List<Column> columns, Class columnType) {
        Object pooledConnection = null;
        try {
            Cassandra.Client api = null;
            pooledConnection = getConnection();
            api = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);
            KsDef ksDef = api.describe_keyspace(m.getSchema());
            List<CfDef> cfDefs = ksDef.getCf_defs();

            // Column family definition on which secondary index creation is
            // required
            CfDef columnFamilyDefToUpdate = null;
            boolean isUpdatable = false;
            for (CfDef cfDef : cfDefs) {
                if (cfDef.getName().equals(tableName)) {
                    columnFamilyDefToUpdate = cfDef;
                    break;
                }
            }

            if (columnFamilyDefToUpdate == null) {
                log.error("Join table {} not available.", tableName);
                throw new PersistenceException("table" + tableName + " not found!");
            }
            // create a column family, in case it is not already available.

            // Get list of indexes already created
            List<ColumnDef> columnMetadataList = columnFamilyDefToUpdate.getColumn_metadata();
            List<String> indexList = new ArrayList<String>();

            if (columnMetadataList != null) {
                for (ColumnDef columnDef : columnMetadataList) {
                    indexList.add(new StringAccessor().fromBytes(String.class, columnDef.getName()));
                }
                // need to set them to null else it is giving problem on update
                // column family and trying to add again existing indexes.
                // columnFamilyDefToUpdate.column_metadata = null;
            }

            // Iterate over all columns for creating secondary index on them
            for (Column column : columns) {

                ColumnDef columnDef = new ColumnDef();

                columnDef.setName(column.getName());
                columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(columnType, false));
                columnDef.setIndex_type(IndexType.KEYS);

                // Add secondary index only if it's not already created
                // (if already created, it would be there in column family
                // definition)
                if (!indexList.contains(new StringAccessor().fromBytes(String.class, column.getName()))) {
                    isUpdatable = true;
                    columnFamilyDefToUpdate.addToColumn_metadata(columnDef);
                }
            }

            // Finally, update column family with modified column family
            // definition
            if (isUpdatable) {
                columnFamilyDefToUpdate.setKey_validation_class(CassandraValidationClassMapper
                    .getValidationClass(m.getIdAttribute().getJavaType(), isCql3Enabled(m)));
                api.system_update_column_family(columnFamilyDefToUpdate);
            }

        } catch (Exception e) {
            log.warn("Could not create secondary index on column family {}, Caused by: . ", tableName, e);

        } finally {
            releaseConnection(pooledConnection);
        }
    }
361627
static TableSchema createTableSchemaFromFields(String fieldsJson) throws IOException {
    List<TableFieldSchema> fields = new ArrayList<>();
    JsonParser parser = JacksonFactory.getDefaultInstance().createJsonParser(fieldsJson);
    parser.parseArrayAndClose(fields, TableFieldSchema.class);

    return new TableSchema().setFields(fields);
  }
1011341
SchemaProperty createDatabaseSchema(final App app, final AbstractSchemaNode schemaNode) throws FrameworkException {

		final PropertyMap getOrCreateProperties = new PropertyMap();
		final PropertyMap updateProperties      = new PropertyMap();

		getOrCreateProperties.put(SchemaProperty.name, getName());
		getOrCreateProperties.put(SchemaProperty.schemaNode, schemaNode);

		SchemaProperty property = app.nodeQuery(SchemaProperty.class).and(getOrCreateProperties).getFirst();
		if (property == null) {

			getOrCreateProperties.put(SchemaProperty.compound, isCompoundUnique());
			getOrCreateProperties.put(SchemaProperty.unique, isUnique());
			getOrCreateProperties.put(SchemaProperty.indexed, isIndexed());
			getOrCreateProperties.put(SchemaProperty.notNull, isRequired());
			getOrCreateProperties.put(SchemaProperty.readOnly, isReadOnly());
			getOrCreateProperties.put(SchemaProperty.format, getFormat());
			getOrCreateProperties.put(SchemaProperty.hint, getHint());
			getOrCreateProperties.put(SchemaProperty.category, getCategory());
			getOrCreateProperties.put(SchemaProperty.validators, validators.toArray(new String[0]));
			getOrCreateProperties.put(SchemaProperty.transformers, transformers.toArray(new String[0]));
			getOrCreateProperties.put(SchemaProperty.defaultValue, defaultValue);

			property = app.create(SchemaProperty.class, getOrCreateProperties);
		}

		if (parent != null) {

			final JsonSchema root = parent.getSchema();
			if (root != null) {

				if (SchemaService.DynamicSchemaRootURI.equals(root.getId())) {

					updateProperties.put(SchemaProperty.isPartOfBuiltInSchema, true);
				}
			}
		}

		// update properties
		property.setProperties(SecurityContext.getSuperUserInstance(), updateProperties);

		// return modified property
		return property;
	}
815131
public static <T> List<T> create(final T item) {
        final List<T> list = new ArrayList<T>();
        list.add(item);
        return list;
    }
482206
private void createIfNotExists(String tableName, String createTableStatement) throws SQLException {
		logger.entering(CLASSNAME, "createIfNotExists", new Object[] {tableName, createTableStatement});

		Connection conn = getConnection();
		DatabaseMetaData dbmd = conn.getMetaData();
		ResultSet rs = dbmd.getTables(null, schema, tableName, null);
		PreparedStatement ps = null;
		if(!rs.next()) {
			logger.log(Level.INFO, tableName + " table does not exists. Trying to create it.");
			ps = conn.prepareStatement(createTableStatement);
			ps.executeUpdate();
		}

		cleanupConnection(conn, rs, ps);
		logger.exiting(CLASSNAME, "createIfNotExists");
	}