// GenerateFieldQuery generates a query to just fetch the field info
// by adding impossible where clauses as needed.
976263
func GenerateFieldQuery(statement sqlparser.Statement) *sqlparser.ParsedQuery {
	buf := sqlparser.NewTrackedBuffer(sqlparser.FormatImpossibleQuery).WriteNode(statement)

	if buf.HasBindVars() {
		return nil
	}

	return buf.ParsedQuery()
}
674861
func GenerateUpdateOuterQuery(upd *sqlparser.Update, aliased *sqlparser.AliasedTableExpr, formatter sqlparser.NodeFormatter) *sqlparser.ParsedQuery {
	buf := sqlparser.NewTrackedBuffer(formatter)
	buf.Myprintf("update %v%v set %v where %a%v", upd.Comments, aliased.RemoveHints(), upd.Exprs, ":#pk", upd.OrderBy)
	return buf.ParsedQuery()
}
735652
func GenerateUpdateSubquery(upd *sqlparser.Update, table *schema.Table, aliased *sqlparser.AliasedTableExpr) *sqlparser.ParsedQuery {
	return GenerateSubquery(
		table.Indexes[0].Columns,
		aliased,
		upd.Where,
		upd.OrderBy,
		upd.Limit,
		true,
	)
}
264832
func Generate(schema *rdl.Schema, params *GeneratorParams) error {
	packageDir, err := GenerationDir(params.Outdir, schema, params.Namespace)
	if err != nil {
		return err
	}
	//	getSetters := GenerationBoolOptionSet(options, "getsetters")
	registry := rdl.NewTypeRegistry(schema)
	for _, t := range schema.Types {
		tName, _, _ := rdl.TypeInfo(t)
		if strings.HasPrefix(string(tName), "rdl.") {
			continue
		}
		err := generateJavaType(params.Banner, schema, registry, packageDir, t, params.Namespace, params.GetSetters)
		if err != nil {
			return err
		}
	}
	cName := capitalize(string(schema.Name)) + "Schema"
	out, file, _, err := genutil.OutputWriter(packageDir, cName, ".java")
	if err != nil {
		return err
	}
	err = GenerateSchema(schema, cName, out, params.Namespace, params.Banner)
	out.Flush()
	file.Close()
	if err != nil {
		return err
	}
	return nil
}
705702
func getSQLFields(s DBModel) (ret []string) {
	fields := getFields(s)
	table := handleIdentifier(s.TableName())
	for _, field := range fields {
		ret = append(ret, table+"."+getColumnName(field))
	}
	return
}
944849
func (q *QueryStringQuery) DefaultField(defaultField string) *QueryStringQuery {
	q.defaultField = defaultField
	return q
}
1338708
func (q *NumericRangeQuery) Field(field string) *NumericRangeQuery {
	q.options["field"] = field
	return q
}
235927
func (t *Trending) generateURL(mode, time, language string) (*url.URL, error) {
	urlStr := urlTrendingPath
	if mode == modeDevelopers {
		urlStr += urlDevelopersPath
	}

	u := t.appendBaseHostToPath(urlStr, true)
	q := u.Query()
	if len(time) > 0 {
		q.Set("since", time)
	}

	if len(language) > 0 {
		q.Set("l", language)
	}

	u.RawQuery = q.Encode()

	return u, nil
}
61639
func (codegen *CodeGenerator) Generate() (string, error) {
	for index, rawSchema := range codegen.rawSchemas {
		parsedSchema, err := ParseSchema(rawSchema)
		if err != nil {
			return "", err
		}

		schema, ok := parsedSchema.(*RecordSchema)
		if !ok {
			return "", errors.New("Not a Record schema.")
		}
		schemaInfo, err := newRecordSchemaInfo(schema)
		if err != nil {
			return "", err
		}

		buffer := &bytes.Buffer{}
		codegen.codeSnippets = append(codegen.codeSnippets, buffer)

		// write package and import only once
		if index == 0 {
			err = codegen.writePackageName(schemaInfo)
			if err != nil {
				return "", err
			}

			err = codegen.writeImportStatement()
			if err != nil {
				return "", err
			}
		}

		err = codegen.writeStruct(schemaInfo)
		if err != nil {
			return "", err
		}
	}

	formatted, err := format.Source([]byte(codegen.collectResult()))
	if err != nil {
		return "", err
	}

	return string(formatted), nil
}
1099409
func NewQueryStringQuery(query string) *QueryStringQuery {
	q := &QueryStringQuery{newFtsQueryBase()}
	q.options["query"] = query
	return q
}
1198762
func (q *PrefixQuery) Field(field string) *PrefixQuery {
	q.options["field"] = field
	return q
}
441611
func getFields(s interface{}) (ret []reflect.StructField) {
	val := reflect.Indirect(reflect.ValueOf(s))
	// addIf adds filedType to ret if is not marked as `sql:"-"`
	addIf := func(fieldType reflect.StructField) {
		tag := strings.ToLower(fieldType.Tag.Get("sql"))
		tagValue := strings.Split(tag, ",")
		sort.Strings(tagValue)
		idx := sort.SearchStrings(tagValue, "-")
		if idx == len(tagValue) || tagValue[idx] != "-" {
			ret = append(ret, fieldType)
		}
	}
	for i := 0; i < val.NumField(); i++ {
		fieldValue := val.Field(i)
		fieldType := val.Type().Field(i)
		// if it's exported
		if fieldType.PkgPath == "" {
			// Handle embedded anoymous struct
			switch fieldValue.Kind() {
			case reflect.Struct:
				// if it's anonymous, embed its fields in the query
				if fieldType.Anonymous {
					ret = append(ret, getFields(fieldValue.Interface())...)
				} else { // use its name only (to work with structs like time.Time)
					addIf(fieldType)
				}
			default:
				addIf(fieldType)
			}
		}
	}

	return
}
1129808
func Generate(schema *rdl.Schema, params *GeneratorParams) error {
	name := strings.ToLower(string(schema.Name))
	outdir := params.Outdir
	if outdir == "" {
		outdir = "."
		name = name + "_model.go"
	} else if strings.HasSuffix(outdir, ".go") {
		name = filepath.Base(outdir)
		outdir = filepath.Dir(outdir)
	} else {
		name = name + "_model.go"
	}
	err := os.MkdirAll(outdir, 0755)
	if err != nil {
		return err
	}
	filepath := outdir + "/" + name
	out, file, _, err := genutil.OutputWriter(filepath, "", ".go")
	if err != nil {
		return err
	}
	if file != nil {
		defer func() {
			file.Close()
			err := goFmt(filepath)
			if err != nil {
				fmt.Println("Warning: could not format go code:", err)
			}
		}()
	}
	gen := &modelGenerator{
		registry:       rdl.NewTypeRegistry(schema),
		schema:         schema,
		writer:         out,
		librdl:         params.LibRdl,
		prefixEnums:    params.PrefixEnums,
		precise:        params.PreciseTypes,
		err:            nil,
		untaggedUnions: params.UntaggedUnions,
		ns:             params.Namespace,
		rdl:            schema.Name == "rdl",
	}
	gen.emitHeader(params.Banner)
	if gen.err == nil {
		for _, t := range schema.Types {
			gen.emitType(t)
		}
	}
	out.Flush()
	if gen.err == nil {
		if params.GenerateSchema {
			gen.err = GenerateGoSchema(params.Banner, schema, outdir, params.Namespace, params.LibRdl, params.PrefixEnums)
		}
	}
	return gen.err
}
635150
func (q QueryStringQuery) Source() interface{} {
	// {
	//    "query_string" : {
	//      "default_field" : "content",
	//      "query" : "this AND that OR thus"
	//    }
	// }

	source := make(map[string]interface{})

	query := make(map[string]interface{})
	source["query_string"] = query

	query["query"] = q.queryString

	if q.defaultField != "" {
		query["default_field"] = q.defaultField
	}

	if len(q.fields) > 0 {
		fields := make([]string, 0)
		for _, field := range q.fields {
			if boost, found := q.fieldBoosts[field]; found {
				if boost != nil {
					fields = append(fields, fmt.Sprintf("%s^%f", field, *boost))
				} else {
					fields = append(fields, field)
				}
			} else {
				fields = append(fields, field)
			}
		}
		query["fields"] = fields
	}

	if q.tieBreaker != nil {
		query["tie_breaker"] = *q.tieBreaker
	}

	if q.useDisMax != nil {
		query["use_dis_max"] = *q.useDisMax
	}

	if q.defaultOper != "" {
		query["default_operator"] = q.defaultOper
	}

	if q.analyzer != "" {
		query["analyzer"] = q.analyzer
	}

	if q.quoteAnalyzer != "" {
		query["quote_analyzer"] = q.quoteAnalyzer
	}

	if q.autoGeneratePhraseQueries != nil {
		query["auto_generate_phrase_queries"] = *q.autoGeneratePhraseQueries
	}

	if q.allowLeadingWildcard != nil {
		query["allow_leading_wildcard"] = *q.allowLeadingWildcard
	}

	if q.lowercaseExpandedTerms != nil {
		query["lowercase_expanded_terms"] = *q.lowercaseExpandedTerms
	}

	if q.enablePositionIncrements != nil {
		query["enable_position_increments"] = *q.enablePositionIncrements
	}

	if q.fuzzyMinSim != nil {
		query["fuzzy_min_sim"] = *q.fuzzyMinSim
	}

	if q.boost != nil {
		query["boost"] = *q.boost
	}

	if q.fuzzyPrefixLength != nil {
		query["fuzzy_prefix_length"] = *q.fuzzyPrefixLength
	}

	if q.fuzzyMaxExpansions != nil {
		query["fuzzy_max_expansions"] = *q.fuzzyMaxExpansions
	}

	if q.fuzzyRewrite != "" {
		query["fuzzy_rewrite"] = q.fuzzyRewrite
	}

	if q.phraseSlop != nil {
		query["phrase_slop"] = *q.phraseSlop
	}

	if q.analyzeWildcard != nil {
		query["analyze_wildcard"] = *q.analyzeWildcard
	}

	if q.rewrite != "" {
		query["rewrite"] = q.rewrite
	}

	if q.minimumShouldMatch != "" {
		query["minimum_should_match"] = q.minimumShouldMatch
	}

	if q.quoteFieldSuffix != "" {
		query["quote_field_suffix"] = q.quoteFieldSuffix
	}

	if q.lenient != nil {
		query["lenient"] = *q.lenient
	}

	return source
}
1355259
func (q *QueryStringQuery) Field(field string) *QueryStringQuery {
	q.fields = append(q.fields, field)
	return q
}
494211
func NewQueryStringQuery(queryString string) QueryStringQuery {
	q := QueryStringQuery{
		queryString: queryString,
		fields:      make([]string, 0),
		fieldBoosts: make(map[string]*float32),
	}
	return q
}
952593
func GenerateInsertOuterQuery(ins *sqlparser.Insert) *sqlparser.ParsedQuery {
	buf := sqlparser.NewTrackedBuffer(nil)
	buf.Myprintf("%s %v%sinto %v%v values %a",
		ins.Action,
		ins.Comments,
		ins.Ignore,
		ins.Table,
		ins.Columns,
		":#values",
	)
	return buf.ParsedQuery()
}