// CreateNewDatabase データベース作成
161113
func CreateNewDatabase(values *CreateDatabaseValue) *Database {

	db := &Database{
		// Appliance
		Appliance: &Appliance{
			// Class
			Class: "database",
			// Name
			propName: propName{Name: values.Name},
			// Description
			propDescription: propDescription{Description: values.Description},
			// TagsType
			propTags: propTags{
				// Tags
				Tags: values.Tags,
			},
			// Icon
			propIcon: propIcon{
				&Icon{
					// Resource
					Resource: values.Icon,
				},
			},
			// Plan
			//propPlanID: propPlanID{Plan: &Resource{ID: int64(values.Plan)}},
		},
		// Remark
		Remark: &DatabaseRemark{
			// ApplianceRemarkBase
			ApplianceRemarkBase: &ApplianceRemarkBase{
				// Servers
				Servers: []interface{}{""},
			},
			// DBConf
			DBConf: &DatabaseCommonRemarks{
				// Common
				Common: &DatabaseCommonRemark{
					// DatabaseName
					DatabaseName: values.DatabaseName,
					// DatabaseRevision
					DatabaseRevision: values.DatabaseRevision,
					// DatabaseTitle
					DatabaseTitle: values.DatabaseTitle,
					// DatabaseVersion
					DatabaseVersion: values.DatabaseVersion,
				},
			},
			// Plan
			propPlanID:      propPlanID{Plan: &Resource{ID: int64(values.Plan)}},
			SourceAppliance: values.SourceAppliance,
		},
		// Settings
		Settings: &DatabaseSettings{
			// DBConf
			DBConf: &DatabaseSetting{
				// Backup
				Backup: &DatabaseBackupSetting{
					// Rotate
					// Rotate: values.BackupRotate,
					Rotate: 8,
					// Time
					Time: values.BackupTime,
					// DayOfWeek
					DayOfWeek: values.BackupDayOfWeek,
				},
				// Common
				Common: &DatabaseCommonSetting{
					// DefaultUser
					DefaultUser: values.DefaultUser,
					// UserPassword
					UserPassword: values.UserPassword,
					// SourceNetwork
					SourceNetwork: SourceNetwork(values.SourceNetwork),
				},
			},
		},
	}

	if values.ServicePort > 0 {
		db.Settings.DBConf.Common.ServicePort = json.Number(fmt.Sprintf("%d", values.ServicePort))
	}

	if !values.EnableBackup {
		db.Settings.DBConf.Backup = nil
	}

	db.Remark.Switch = &ApplianceRemarkSwitch{
		// ID
		ID: values.SwitchID,
	}
	db.Remark.Network = &DatabaseRemarkNetwork{
		// NetworkMaskLen
		NetworkMaskLen: values.MaskLen,
		// DefaultRoute
		DefaultRoute: values.DefaultRoute,
	}

	db.Remark.Servers = []interface{}{
		map[string]interface{}{"IPAddress": values.IPAddress1},
	}

	if values.WebUI {
		db.Settings.DBConf.Common.WebUI = values.WebUI
	}

	if values.ReplicaPassword != "" {
		db.Settings.DBConf.Common.ReplicaUser = "replica"
		db.Settings.DBConf.Common.ReplicaPassword = values.ReplicaPassword
		db.Settings.DBConf.Replication = &DatabaseReplicationSetting{
			Model: DatabaseReplicationModelMasterSlave,
		}
	}

	return db
}
755198
func (c *Client) CreateDB(db string) error {
	u := *c.url
	q := u.Query()
	q.Del("db")
	u.Path = "/query"
	u.RawQuery = q.Encode()

	r, err := c.http.Post(u.String(), "application/x-www-form-urlencoded", strings.NewReader(
		fmt.Sprintf("q=CREATE DATABASE %q", db),
	))
	if err != nil {
		return err
	}
	return readResponse(r)
}
805898
func (client *Client) CreateDatabase(args *CreateDatabaseArgs) (resp *CreateDatabaseResponse, err error) {
	response := CreateDatabaseResponse{}
	err = client.Invoke("CreateDatabase", args, &response)

	if err != nil {
		return nil, err
	}
	return &response, nil
}
570043
func newVersionedDB(couchInstance *couchdb.CouchInstance, dbName string) (*VersionedDB, error) {
	// CreateCouchDatabase creates a CouchDB database object, as well as the underlying database if it does not exist
	chainName := dbName
	dbName = couchdb.ConstructMetadataDBName(dbName)

	metadataDB, err := couchdb.CreateCouchDatabase(couchInstance, dbName)
	if err != nil {
		return nil, err
	}
	namespaceDBMap := make(map[string]*couchdb.CouchDatabase)
	return &VersionedDB{
		couchInstance:      couchInstance,
		metadataDB:         metadataDB,
		chainName:          chainName,
		namespaceDBs:       namespaceDBMap,
		committedDataCache: newVersionCache(),
		lsccStateCache: &lsccStateCache{
			cache: make(map[string]*statedb.VersionedValue),
		},
	}, nil
}
249529
func CreateTables(db *sql.DB) error {
	// Create all of the data tables.
	for tableName, createCommand := range createTableStatements {
		err := createTable(db, tableName, createCommand)
		if err != nil {
			return err
		}
	}

	return ClearTestingTable(db)
}
541704
func (p *Parser) parseCreateDatabaseStatement() (*CreateDatabaseStatement, error) {
	stmt := &CreateDatabaseStatement{}

	// Parse the name of the database to be created.
	lit, err := p.ParseIdent()
	if err != nil {
		return nil, err
	}
	stmt.Name = lit

	// Look for "WITH"
	if tok, _, _ := p.ScanIgnoreWhitespace(); tok == WITH {
		// validate that at least one of DURATION, NAME, REPLICATION or SHARD is provided
		tok, pos, lit := p.ScanIgnoreWhitespace()
		if tok != DURATION && tok != NAME && tok != REPLICATION && tok != SHARD {
			return nil, newParseError(tokstr(tok, lit), []string{"DURATION", "NAME", "REPLICATION", "SHARD"}, pos)
		}
		// rewind
		p.Unscan()

		// mark statement as having a RetentionPolicyInfo defined
		stmt.RetentionPolicyCreate = true

		// Look for "DURATION"
		if err := p.parseTokens([]Token{DURATION}); err != nil {
			p.Unscan()
		} else {
			rpDuration, err := p.ParseDuration()
			if err != nil {
				return nil, err
			}
			stmt.RetentionPolicyDuration = &rpDuration
		}

		// Look for "REPLICATION"
		if err := p.parseTokens([]Token{REPLICATION}); err != nil {
			p.Unscan()
		} else {
			rpReplication, err := p.ParseInt(1, math.MaxInt32)
			if err != nil {
				return nil, err
			}
			stmt.RetentionPolicyReplication = &rpReplication
		}

		// Look for "SHARD"
		if err := p.parseTokens([]Token{SHARD}); err != nil {
			p.Unscan()
		} else {
			// Look for "DURATION"
			tok, pos, lit := p.ScanIgnoreWhitespace()
			if tok != DURATION {
				return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos)
			}
			stmt.RetentionPolicyShardGroupDuration, err = p.ParseDuration()
			if err != nil {
				return nil, err
			}
		}

		// Look for "NAME"
		if err := p.parseTokens([]Token{NAME}); err != nil {
			p.Unscan()
		} else {
			stmt.RetentionPolicyName, err = p.ParseIdent()
			if err != nil {
				return nil, err
			}
		}
	} else {
		p.Unscan()
	}
	return stmt, nil
}
382700
func (db *Database) buildCreate() string {
	var query bytes.Buffer
	query.WriteString(db.buildCTE())
	query.WriteString("INSERT INTO ")

	// Model only
	if len(db.tables) != 1 {
		db.panicLog(fmt.Sprintf("Unable to infer table name for Create. Number of tables: %d", len(db.tables)))
	}
	// Table (
	query.WriteString(db.tables[0])
	query.WriteString("(")

	// field1,file2,...
	createSize := len(db.updateCreateFields)
	if createSize == 0 {
		db.panicLog("Unable to detect fields for Create")
	}

	query.WriteString(strings.Join(db.updateCreateFields, ","))
	// values($1,..$n) place holders
	query.WriteString(") VALUES (")
	for i := 0; i < createSize; i++ {
		query.WriteString("$")
		query.WriteString(strconv.Itoa(db.varCount))
		db.varCount++
		if i != createSize-1 {
			query.WriteString(",")
		}
	}

	query.WriteString(") ")
	query.WriteString(db.buildReturning())
	query.WriteString(";")

	qs := query.String()
	db.printLog(qs)
	return qs
}
1019206
func createDataDir() error {
	var err error
	path := filepath.Join(DataDir(), ParsersFolder)

	if _, err = os.Stat(path); os.IsNotExist(err) {
		log.Info(fmt.Sprintf("data dir '%s' does not exist", path))
		log.Info("creating the data dir...")

		if err = os.MkdirAll(path, 0755); err != nil {
			return err
		}

		log.Success("data dir successfully created")
	} else if err != nil {
		return err
	}

	return nil
}
995219
func NewPrefixDB(db DB, prefix []byte) *prefixDB {
	return &prefixDB{
		prefix: prefix,
		db:     db,
	}
}
62200
func CreateTable(db *sql.DB, tableName string) error {
	createCommand, tableNameFound := createTableStatements[tableName]
	if !tableNameFound {
		return fmt.Errorf("table name %s unknown", tableName)
	}

	return createTable(db, tableName, createCommand)
}
90190
func NewCreate(ctx *Context, stmt *rel.SqlCreate) *Create {
	return &Create{Stmt: stmt, PlanBase: NewPlanBase(false), Ctx: ctx}
}
850857
func (idx *AddrIndex) Create(dbTx database.Tx) error {
	_, err := dbTx.Metadata().CreateBucket(addrIndexKey)
	return err
}
357828
func NewLevelDBDatabase(file string, cache int, handles int, namespace string) (ethdb.Database, error) {
	db, err := leveldb.New(file, cache, handles, namespace)
	if err != nil {
		return nil, err
	}
	return NewDatabase(db), nil
}
996123
func NewDatabase(opts ...Option) *Database {
	db := &Database{
		endpoint: "http://localhost:8529",
		dbName:   "_system",
		// These Transport parameters are derived from github.com/hashicorp/go-cleanhttp which is under Mozilla Public License.
		cli: &http.Client{
			Transport: &http.Transport{
				DialContext: (&net.Dialer{
					Timeout:   30 * time.Second,
					KeepAlive: 30 * time.Second,
				}).DialContext,
				MaxIdleConns:          100,
				IdleConnTimeout:       90 * time.Second,
				TLSHandshakeTimeout:   10 * time.Second,
				ExpectContinueTimeout: 1 * time.Second,
				MaxIdleConnsPerHost:   runtime.GOMAXPROCS(0) + 1,
			},
			Timeout: 10 * time.Minute,
		},
		sender: &basicSender{},
		auth:   &basicAuth{},
	}

	db.Options(opts...)

	return db
}
702681
func (db *DB) Create(name string) error {
	db.schemaLock.Lock()
	defer db.schemaLock.Unlock()
	return db.create(name)
}
760212
func NewDebugDB(label string, db DB) debugDB {
	return debugDB{
		label: label,
		db:    db,
	}
}
257122
func newDbConn(mdb *MemDb) *dbConn {
	c := &dbConn{md: mdb, db: mdb.db}
	return c
}