// parseCreateDatabaseStatement parses a string and returns a CreateDatabaseStatement.
// This function assumes the "CREATE DATABASE" tokens have already been consumed.
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
}
973515
func (db *SQLDB) createTable(table *types.SQLTable, isInitialise bool) error {
	db.Log.Info("msg", "Creating Table", "value", table.Name)

	// prepare log query
	logQuery := db.DBAdapter.InsertLogQuery()

	//get create table query
	safeTable := safe(table.Name)
	query, dictionary := db.DBAdapter.CreateTableQuery(safeTable, table.Columns)
	if query == "" {
		db.Log.Info("msg", "empty CREATE TABLE query")
		return errors.New("empty CREATE TABLE query")
	}

	// create table
	db.Log.Info("msg", "CREATE TABLE", "query", query)
	_, err := db.DB.Exec(query)
	if err != nil {
		return err
	}

	//store dictionary
	db.Log.Info("msg", "STORE DICTIONARY", "query", dictionary)
	_, err = db.DB.Exec(dictionary)
	if err != nil {
		db.Log.Info("msg", "Error storing  dictionary", "err", err)
		return err
	}

	err = db.createTableTriggers(table)
	if err != nil {
		db.Log.Info("msg", "error creating notification triggers", "err", err, "value", fmt.Sprintf("%v", table))
		return fmt.Errorf("could not create table notification triggers: %v", err)
	}

	//insert log (if action is not database initialization)
	if !isInitialise {
		// Marshal the table into a JSON string.
		var jsonData []byte
		jsonData, err = db.getJSON(table)
		if err != nil {
			db.Log.Info("msg", "error marshaling table", "err", err, "value", fmt.Sprintf("%v", table))
			return err
		}
		sqlValues, _ := db.getJSON(nil)

		//insert log
		_, err = db.DB.Exec(logQuery, table.Name, "", "", nil, nil, types.ActionCreateTable, jsonData, query, sqlValues)
		if err != nil {
			db.Log.Info("msg", "Error inserting log", "err", err)
			return err
		}
	}
	return nil
}
36277
func (client *Client) DeleteDatabase(instanceId, dbName string) error {
	args := DeleteDatabaseArgs{
		DBInstanceId: instanceId,
		DBName:       dbName,
	}
	response := DeleteDatabaseResponse{}
	err := client.Invoke("DeleteDatabase", &args, &response)
	return err
}
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
}
99646
func (host *Host) useDatabase() error {
	if Verbose {
		log.Println("Using database " + host.dbname)
	}
	return nil
}
889512
func newDatabase(name string, conn Connection) (Database, error) {
	if name == "" {
		return nil, WithStack(InvalidArgumentError{Message: "name is empty"})
	}
	if conn == nil {
		return nil, WithStack(InvalidArgumentError{Message: "conn is nil"})
	}
	return &database{
		name: name,
		conn: conn,
	}, nil
}
525047
func (db *baseDB) CreateTable(model interface{}, opt *orm.CreateTableOptions) error {
	return orm.CreateTable(db.db, model, opt)
}
1327168
func NewTempDatabase() (Database, error) {
	storage, err := util.NewTempFileStorage()
	return NewDatabaseWithStorage(storage), err
}
422993
func (p *Parser) parseCreateTableFields(ctx *parseCtx, stmt model.Table) error {
	for {
		ctx.skipWhiteSpaces()
		switch t := ctx.peek(); t.Type {
		case CONSTRAINT:
			if err := p.parseTableConstraint(ctx, stmt); err != nil {
				return err
			}
		case PRIMARY:
			if err := p.parseTablePrimaryKey(ctx, stmt); err != nil {
				return err
			}
		case UNIQUE:
			if err := p.parseTableUniqueKey(ctx, stmt); err != nil {
				return err
			}
		case INDEX, KEY:
			// TODO. separate to KEY and INDEX
			if err := p.parseTableIndex(ctx, stmt); err != nil {
				return err
			}
		case FULLTEXT:
			if err := p.parseTableFulltextIndex(ctx, stmt); err != nil {
				return err
			}
		case SPATIAL:
			if err := p.parseTableSpatialIndex(ctx, stmt); err != nil {
				return err
			}
		case FOREIGN:
			if err := p.parseTableForeignKey(ctx, stmt); err != nil {
				return err
			}
		case CHECK: // TODO
			return newParseError(ctx, t, "unsupported field: CHECK")
		case IDENT, BACKTICK_IDENT:
			if err := p.parseTableColumn(ctx, stmt); err != nil {
				return err
			}
		default:
			return newParseError(ctx, t, "unexpected create table field token: %s", t.Type)
		}

		ctx.skipWhiteSpaces()
		switch t := ctx.peek(); t.Type {
		case RPAREN:
			ctx.advance()
			if err := p.parseCreateTableOptions(ctx, stmt); err != nil {
				return err
			}
			// partition option
			if !p.eol(ctx) {
				return newParseError(ctx, t, "expected EOL")
			}
			return nil
		case COMMA:
			ctx.advance()
			// Expecting another table field, keep looping
		default:
			return newParseError(ctx, t, "expected RPAREN or COMMA")
		}
	}
}
708420
func (a Associations) AssociationsCreatableStatement() []AssociationCreatableStatement {
	var stm []AssociationCreatableStatement
	for i := range a {
		if _, ok := a[i].(AssociationCreatableStatement); ok {
			stm = append(stm, a[i].(AssociationCreatableStatement))
		}
	}
	return stm
}
1142839
func ParseFilterQL(filter string) (*FilterStatement, error) {
	f, err := NewFilterParser(filter).ParseFilter()
	if err != nil {
		return nil, err
	}
	return f.FilterStatement, nil
}
600679
func (m *PlannerDefault) WalkPreparedStatement(p *PreparedStatement) error {
	u.Debugf("WalkPreparedStatement %+v", p.Stmt)
	return ErrNotImplemented
}
649092
func (dbclient *CouchDatabase) GetDatabaseInfo() (*DBInfo, *DBReturn, error) {

	connectURL, err := url.Parse(dbclient.CouchInstance.conf.URL)
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, nil, errors.Wrapf(err, "error parsing CouchDB URL: %s", dbclient.CouchInstance.conf.URL)
	}

	//get the number of retries
	maxRetries := dbclient.CouchInstance.conf.MaxRetries

	resp, couchDBReturn, err := dbclient.handleRequest(http.MethodGet, "GetDatabaseInfo", connectURL, nil, "", "", maxRetries, true, nil)
	if err != nil {
		return nil, couchDBReturn, err
	}
	defer closeResponseBody(resp)

	dbResponse := &DBInfo{}
	decodeErr := json.NewDecoder(resp.Body).Decode(&dbResponse)
	if decodeErr != nil {
		return nil, nil, errors.Wrap(decodeErr, "error decoding response body")
	}

	// trace the database info response
	logger.Debugw("GetDatabaseInfo()", "dbResponseJSON", dbResponse)

	return dbResponse, couchDBReturn, 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
}
719808
func NewDatabaseAPI(client *Client) *DatabaseAPI {
	return &DatabaseAPI{
		&baseAPI{
			client: client,
			FuncGetResourceURL: func() string {
				return "appliance"
			},
			FuncBaseSearchCondition: func() *sacloud.Request {
				res := &sacloud.Request{}
				res.AddFilter("Class", "database")
				return res
			},
		},
	}
}
591715
func BuildParsedQuery(in string, vars ...interface{}) *ParsedQuery {
	buf := NewTrackedBuffer(nil)
	buf.Myprintf(in, vars...)
	return buf.ParsedQuery()
}
78582
func (host *Host) SelectDatabase(dbname string) error {
	host.dbname = dbname
	if err := host.createDatabase(); err != nil {
		return err
	}
	if err := host.useDatabase(); err != nil {
		return err
	}
	return nil
}