// CreateTableQuery builds query for creating a new table
968912
func (adapter *PostgresAdapter) CreateTableQuery(tableName string, columns []*types.SQLTableColumn) (string, string) {
	// build query
	columnsDef := ""
	primaryKey := ""
	dictionaryValues := ""

	for i, column := range columns {
		secureColumn := adapter.SecureName(column.Name)
		sqlType, _ := adapter.TypeMapping(column.Type)
		pKey := 0

		if columnsDef != "" {
			columnsDef += ", "
			dictionaryValues += ", "
		}

		columnsDef += Cleanf("%s %s", secureColumn, sqlType)

		if column.Length > 0 {
			columnsDef += Cleanf("(%v)", column.Length)
		}

		if column.Primary {
			pKey = 1
			columnsDef += " NOT NULL"
			if primaryKey != "" {
				primaryKey += ", "
			}
			primaryKey += secureColumn
		}

		dictionaryValues += Cleanf("('%s','%s',%d,%d,%d,%d)",
			tableName,
			column.Name,
			column.Type,
			column.Length,
			pKey,
			i)
	}

	query := Cleanf("CREATE TABLE %s.%s (%s", adapter.Schema, adapter.SecureName(tableName), columnsDef)
	if primaryKey != "" {
		query += "," + Cleanf("CONSTRAINT %s_pkey PRIMARY KEY (%s)", tableName, primaryKey)
	}
	query += ");"

	dictionaryQuery := Cleanf("INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s) VALUES %s;",
		adapter.Schema, types.SQLDictionaryTableName,
		types.SQLColumnLabelTableName, types.SQLColumnLabelColumnName,
		types.SQLColumnLabelColumnType, types.SQLColumnLabelColumnLength,
		types.SQLColumnLabelPrimaryKey, types.SQLColumnLabelColumnOrder,
		dictionaryValues)

	return query, dictionaryQuery
}
620474
func (d MySQLDialect) CreateTableSuffix() string {
	return fmt.Sprintf(" engine=%s charset=%s", d.Engine, d.Encoding)
}
453920
func (session *Session) createAll() error {
	if session.IsAutoClose {
		defer session.Close()
	}

	for _, table := range session.Engine.Tables {
		session.Statement.RefTable = table
		session.Statement.tableName = table.Name
		err := session.createOneTable()
		session.resetStatement()
		if err != nil {
			return err
		}
	}
	return nil
}
124238
func (q *Query) AddFacetQuery(fq string) {
	q.params.Set("facet", "true")
	q.params.Add("facet.query", fq)
}
1060141
func NewCreateTable(ctx context.Context, table []byte,
	families map[string]map[string]string,
	options ...func(*CreateTable)) *CreateTable {
	ct := &CreateTable{
		base: base{
			table:    table,
			ctx:      ctx,
			resultch: make(chan RPCResult, 1),
		},
		families: make(map[string]map[string]string, len(families)),
	}
	for _, option := range options {
		option(ct)
	}
	for family, attrs := range families {
		ct.families[family] = make(map[string]string, len(defaultAttributes))
		for k, dv := range defaultAttributes {
			if v, ok := attrs[k]; ok {
				ct.families[family][k] = v
			} else {
				ct.families[family][k] = dv
			}
		}
	}
	return ct
}
392327
func TableCreate(name interface{}, optArgs ...TableCreateOpts) Term {
	opts := map[string]interface{}{}
	if len(optArgs) >= 1 {
		opts = optArgs[0].toMap()
	}
	return constructRootTerm("TableCreate", p.Term_TABLE_CREATE, []interface{}{name}, opts)
}
792595
func newQuery(t Term, qopts map[string]interface{}, copts *ConnectOpts) (q Query, err error) {
	queryOpts := map[string]interface{}{}
	for k, v := range qopts {
		queryOpts[k], err = Expr(v).Build()
		if err != nil {
			return
		}
	}
	if copts.Database != "" {
		queryOpts["db"], err = DB(copts.Database).Build()
		if err != nil {
			return
		}
	}

	builtTerm, err := t.Build()
	if err != nil {
		return q, err
	}

	// Construct query
	return Query{
		Type:      p.Query_START,
		Term:      &t,
		Opts:      queryOpts,
		builtTerm: builtTerm,
	}, nil
}
1271746
func newQuery(collection *Collection) *query {
	q := &query{
		collection: collection,
		pool:       collection.pool,
	}
	// For now, only indexed collections are queryable. This might change in
	// future versions.
	if !collection.index {
		q.setError(fmt.Errorf("zoom: error in NewQuery: Only indexed collections are queryable"))
		return q
	}
	return q
}
771623
func (m *DbMap) CreateTablesSql() (map[string]string, error) {
	return m.createTables(false, false)
}
981135
func (m *Meta) CreateTableOrView(dbID int64, tableInfo *model.TableInfo) error {
	// Check if db exists.
	dbKey := m.dbKey(dbID)
	if err := m.checkDBExists(dbKey); err != nil {
		return errors.Trace(err)
	}

	// Check if table exists.
	tableKey := m.tableKey(tableInfo.ID)
	if err := m.checkTableNotExists(dbKey, tableKey); err != nil {
		return errors.Trace(err)
	}

	data, err := json.Marshal(tableInfo)
	if err != nil {
		return errors.Trace(err)
	}

	return m.txn.HSet(dbKey, tableKey, data)
}
1004943
func (m *Meta) CreateTableAndSetAutoID(dbID int64, tableInfo *model.TableInfo, autoID int64) error {
	err := m.CreateTableOrView(dbID, tableInfo)
	if err != nil {
		return errors.Trace(err)
	}
	_, err = m.txn.HInc(m.dbKey(dbID), m.autoTableIDKey(tableInfo.ID), autoID)
	return errors.Trace(err)
}
888826
func CreateRequiredTables(c *gocql.ClusterConfig, rt []CTable) error {
	tl, err := GetTables(c)
	if err != nil {
		return err
	}

	tm := map[string]CTable{}
	rtl := []string{}
	for _, v := range rt {
		tm[v.Name] = v
		rtl = append(rtl, v.Name)
	}
	tset := set.NewStringSet(tl)
	rset := set.NewStringSet(rtl)
	diff := rset.Difference(tset)
	missing := diff.Items()
	if len(missing) > 0 {
		for _, t := range missing {
			ts := tm[t]
			err = CreateTable(c, ts)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
217820
func (session *Session) CreateTable(bean interface{}) error {
	v := rValue(bean)
	session.Statement.setRefValue(v)

	defer session.resetStatement()
	if session.IsAutoClose {
		defer session.Close()
	}

	return session.createOneTable()
}
866038
func (c *Connection) CreateIndex(name string, mapping interface{}) (*Response, error) {
	r := Request{
		Conn:      c,
		Query:     mapping,
		IndexList: []string{name},
		method:    "PUT",
	}

	return r.Run()
}
1147259
func (dbclient *CouchDatabase) CreateIndex(indexdefinition string) (*CreateIndexResponse, error) {
	dbName := dbclient.DBName

	logger.Debugf("[%s] Entering CreateIndex()  indexdefinition=%s", dbName, indexdefinition)

	//Test to see if this is a valid JSON
	if IsJSON(indexdefinition) != true {
		return nil, errors.New("JSON format is not valid")
	}

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

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

	resp, _, err := dbclient.handleRequest(http.MethodPost, "CreateIndex", indexURL, []byte(indexdefinition), "", "", maxRetries, true, nil, "_index")
	if err != nil {
		return nil, err
	}
	defer closeResponseBody(resp)

	if resp == nil {
		return nil, errors.New("invalid response received from CouchDB")
	}

	//Read the response body
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errors.Wrap(err, "error reading response body")
	}

	couchDBReturn := &CreateIndexResponse{}

	jsonBytes := []byte(respBody)

	//unmarshal the response
	err = json.Unmarshal(jsonBytes, &couchDBReturn)
	if err != nil {
		return nil, errors.Wrap(err, "error unmarshalling json data")
	}

	if couchDBReturn.Result == "created" {

		logger.Infof("Created CouchDB index [%s] in state database [%s] using design document [%s]", couchDBReturn.Name, dbclient.DBName, couchDBReturn.ID)

		return couchDBReturn, nil

	}

	logger.Infof("Updated CouchDB index [%s] in state database [%s] using design document [%s]", couchDBReturn.Name, dbclient.DBName, couchDBReturn.ID)

	return couchDBReturn, nil
}
1047742
func (self *MyTable) Create() error {
	if len(self.columnNames) == 0 {
		return errors.New("Column can not be empty")
	}
	self.sqlCode = `CREATE TABLE IF NOT EXISTS ` + self.tableName + " ("
	if !self.customPrimaryKey {
		self.sqlCode += `id INT(12) NOT NULL PRIMARY KEY AUTO_INCREMENT,`
	}
	for _, title := range self.columnNames {
		self.sqlCode += title[0] + ` ` + title[1] + `,`
	}
	self.sqlCode = self.sqlCode[:len(self.sqlCode)-1] + `) ENGINE=MyISAM DEFAULT CHARSET=utf8;`

	maxConnChan <- true
	defer func() {
		self.sqlCode = ""
		<-maxConnChan
	}()

	// debug
	// println("Create():", self.sqlCode)

	_, err := db.Exec(self.sqlCode)
	return err
}
1283215
func (cb *CreateBuilder) Table(name string) *CreateTableBuilder {
	return &CreateTableBuilder{
		name:    name,
		columns: make([]tableColumn, 0),
	}
}