//var x application.Application = &GormDB{}
//var y application.Application = &GormTransaction{}
182474
func NewGormDB(db *gorm.DB, config *configuration.ConfigurationData, wrappers factorymanager.FactoryWrappers, options ...factory.Option) *GormDB {
	g := new(GormDB)
	g.db = db.Set("gorm:save_associations", false)
	g.txIsoLevel = ""
	g.serviceFactory = factory.NewServiceFactory(func() servicecontext.ServiceContext {
		return factory.NewServiceContext(g, g, config, wrappers, options...)
	}, config, options...)
	return g
}
393223
func main() {
	r.Sync = make(chan string)
	app := &cli.App{
		Name:        strings.Title(realize.RPrefix),
		Version:     realize.RVersion,
		Description: "Realize is the #1 Golang Task Runner which enhance your workflow by automating the most common tasks and using the best performing Golang live reloading.",
		Commands: []*cli.Command{
			{
				Name:        "start",
				Aliases:     []string{"s"},
				Description: "Start " + strings.Title(realize.RPrefix) + " on a given path. If not exist a config file it creates a new one.",
				Flags: []cli.Flag{
					&cli.StringFlag{Name: "path", Aliases: []string{"p"}, Value: ".", Usage: "Project base path"},
					&cli.StringFlag{Name: "name", Aliases: []string{"n"}, Value: "", Usage: "Run a project by its name"},
					&cli.BoolFlag{Name: "fmt", Aliases: []string{"f"}, Value: false, Usage: "Enable go fmt"},
					&cli.BoolFlag{Name: "vet", Aliases: []string{"v"}, Value: false, Usage: "Enable go vet"},
					&cli.BoolFlag{Name: "test", Aliases: []string{"t"}, Value: false, Usage: "Enable go test"},
					&cli.BoolFlag{Name: "generate", Aliases: []string{"g"}, Value: false, Usage: "Enable go generate"},
					&cli.BoolFlag{Name: "server", Aliases: []string{"srv"}, Value: false, Usage: "Start server"},
					&cli.BoolFlag{Name: "open", Aliases: []string{"op"}, Value: false, Usage: "Open into the default browser"},
					&cli.BoolFlag{Name: "install", Aliases: []string{"i"}, Value: false, Usage: "Enable go install"},
					&cli.BoolFlag{Name: "build", Aliases: []string{"b"}, Value: false, Usage: "Enable go build"},
					&cli.BoolFlag{Name: "run", Aliases: []string{"nr"}, Value: false, Usage: "Enable go run"},
					&cli.BoolFlag{Name: "legacy", Aliases: []string{"l"}, Value: false, Usage: "Legacy watch by polling instead fsnotify"},
					&cli.BoolFlag{Name: "no-config", Aliases: []string{"nc"}, Value: false, Usage: "Ignore existing config and doesn't create a new one"},
				},
				Action: start,
			},
			{
				Name:        "add",
				Category:    "Configuration",
				Aliases:     []string{"a"},
				Description: "Add a project to an existing config or to a new one.",
				Flags: []cli.Flag{
					&cli.StringFlag{Name: "path", Aliases: []string{"p"}, Value: realize.Wdir(), Usage: "Project base path"},
					&cli.BoolFlag{Name: "fmt", Aliases: []string{"f"}, Value: false, Usage: "Enable go fmt"},
					&cli.BoolFlag{Name: "vet", Aliases: []string{"v"}, Value: false, Usage: "Enable go vet"},
					&cli.BoolFlag{Name: "test", Aliases: []string{"t"}, Value: false, Usage: "Enable go test"},
					&cli.BoolFlag{Name: "generate", Aliases: []string{"g"}, Value: false, Usage: "Enable go generate"},
					&cli.BoolFlag{Name: "install", Aliases: []string{"i"}, Value: false, Usage: "Enable go install"},
					&cli.BoolFlag{Name: "build", Aliases: []string{"b"}, Value: false, Usage: "Enable go build"},
					&cli.BoolFlag{Name: "run", Aliases: []string{"nr"}, Value: false, Usage: "Enable go run"},
				},
				Action: add,
			},
			{
				Name:        "init",
				Category:    "Configuration",
				Aliases:     []string{"i"},
				Description: "Make a new config file step by step.",
				Action:      setup,
			},
			{
				Name:        "remove",
				Category:    "Configuration",
				Aliases:     []string{"r"},
				Description: "Remove a project from an existing config.",
				Flags: []cli.Flag{
					&cli.StringFlag{Name: "name", Aliases: []string{"n"}, Value: ""},
				},
				Action: remove,
			},
			{
				Name:        "clean",
				Category:    "Configuration",
				Aliases:     []string{"c"},
				Description: "Remove " + strings.Title(realize.RPrefix) + " folder.",
				Action: func(c *cli.Context) error {
					return clean()
				},
			},
			{
				Name:        "version",
				Aliases:     []string{"v"},
				Description: "Print " + strings.Title(realize.RPrefix) + " version.",
				Action: func(p *cli.Context) error {
					version()
					return nil
				},
			},
		},
	}
	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}
1052334
func (r *GormWorkItemLinkTypeRepository) Load(ctx context.Context, ID uuid.UUID) (*WorkItemLinkType, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitemlinktype", "load"}, time.Now())
	log.Info(ctx, map[string]interface{}{
		"wilt_id": ID,
	}, "loading work item link type")
	modelLinkType := WorkItemLinkType{}
	db := r.db.Model(&modelLinkType).Where("id=?", ID).First(&modelLinkType)
	if db.RecordNotFound() {
		log.Error(ctx, map[string]interface{}{
			"wilt_id": ID,
		}, "work item link type not found")
		return nil, errors.NewNotFoundError("work item link type", ID.String())
	}
	if db.Error != nil {
		log.Error(ctx, map[string]interface{}{
			"wilt_id": ID,
			"err":     db.Error,
		}, "failed to create work item link type")
		return nil, errors.NewInternalError(ctx, db.Error)
	}
	return &modelLinkType, nil
}
1176866
func (m *Mysql) gatherGlobalVariables(db *sql.DB, serv string, acc telegraf.Accumulator) error {
	// run query
	rows, err := db.Query(globalVariablesQuery)
	if err != nil {
		return err
	}
	defer rows.Close()

	var key string
	var val sql.RawBytes

	// parse DSN and save server tag
	servtag := getDSNTag(serv)
	tags := map[string]string{"server": servtag}
	fields := make(map[string]interface{})
	for rows.Next() {
		if err := rows.Scan(&key, &val); err != nil {
			return err
		}
		key = strings.ToLower(key)
		// parse mysql version and put into field and tag
		if strings.Contains(key, "version") {
			fields[key] = string(val)
			tags[key] = string(val)
		}
		if value, ok := m.parseValue(val); ok {
			fields[key] = value
		}
		// Send 20 fields at a time
		if len(fields) >= 20 {
			acc.AddFields("mysql_variables", fields, tags)
			fields = make(map[string]interface{})
		}
	}
	// Send any remaining fields
	if len(fields) > 0 {
		acc.AddFields("mysql_variables", fields, tags)
	}
	return nil
}
515224
func (mp *Proxy) doSet(ctx context.Context, session *ProxySession, sql string, bindVariables map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
	vals, _, err := sqlparser.ExtractSetValues(sql)
	if err != nil {
		return nil, err
	}

	for k, v := range vals {
		switch k.Key {
		case "autocommit":
			val, ok := v.(int64)
			if !ok {
				return nil, fmt.Errorf("unexpected value type for autocommit: %T", v)
			}
			switch val {
			case 0:
				session.Autocommit = false
			case 1:
				if !session.Autocommit && session.TransactionID != 0 {
					if err := mp.doCommit(ctx, session); err != nil {
						return nil, err
					}
				}
				session.Autocommit = true
			default:
				return nil, fmt.Errorf("unexpected value for autocommit: %d", val)
			}
		case "charset", "names":
			val, ok := v.(string)
			if !ok {
				return nil, fmt.Errorf("unexpected value type for charset/names: %T", v)
			}
			switch val {
			case "", "utf8", "utf8mb4", "latin1", "default":
				break
			default:
				return nil, fmt.Errorf("unexpected value for charset/names: %v", val)
			}
		default:
			log.Warningf("Ignored inapplicable SET %v = %v", k, v)
		}
	}

	return &sqltypes.Result{}, nil
}
1055718
func (p *CopyPropagator) Apply(query ast.Body) (result ast.Body) {

	uf, ok := makeDisjointSets(p.livevars, query)
	if !ok {
		return query
	}

	// Compute set of vars that appear in the head of refs in the query. If a var
	// is dereferenced, we cannot plug it with a constant value so the constant on
	// the union-find root must be unset (e.g., [1][0] is not legal.)
	headvars := ast.NewVarSet()
	ast.WalkRefs(query, func(x ast.Ref) bool {
		if v, ok := x[0].Value.(ast.Var); ok {
			if root, ok := uf.Find(v); ok {
				root.constant = nil
				headvars.Add(root.key)
			} else {
				headvars.Add(v)
			}
		}
		return false
	})

	bindings := map[ast.Var]*binding{}

	for _, expr := range query {

		// Deep copy the expr as it may be mutated below. The caller that is running
		// copy propagation may hold references to the expr.
		expr = expr.Copy()

		pctx := &plugContext{
			bindings: bindings,
			uf:       uf,
			negated:  expr.Negated,
			headvars: headvars,
		}

		if p.plugBindings(pctx, expr) {
			if p.updateBindings(pctx, expr) {
				result.Append(expr)
			}
		}
	}

	// Run post-processing step on the query to ensure that all live vars are bound
	// in the result. The plugging that happens above substitutes all vars in the
	// same set with the root.
	//
	// This step should run before the next step to prevent unnecessary bindings
	// from being added to the result. For example:
	//
	// - Given the following result: <empty>
	// - Given the following bindings: x/input.x and y/input
	// - Given the following liveset: {x}
	//
	// If this step were to run AFTER the following step, the output would be:
	//
	//	x = input.x; y = input
	//
	// Even though y = input is not required.
	for _, v := range p.sorted {
		if root, ok := uf.Find(v); ok {
			if root.constant != nil {
				result.Append(ast.Equality.Expr(ast.NewTerm(v), root.constant))
			} else if b, ok := bindings[root.key]; ok {
				result.Append(ast.Equality.Expr(ast.NewTerm(v), ast.NewTerm(b.v)))
			} else if root.key != v {
				result.Append(ast.Equality.Expr(ast.NewTerm(v), ast.NewTerm(root.key)))
			}
		}
	}

	// Run post-processing step on query to ensure that all killed exprs are
	// accounted for. If an expr is killed but the binding is never used, the query
	// must still include the expr. For example, given the query 'input.x = a' and
	// an empty livevar set, the result must include the ref input.x otherwise the
	// query could be satisfied without input.x being defined. When exprs are
	// killed we initialize the binding counter to zero and then increment it each
	// time the binding is substituted. if the binding was never substituted it
	// means the binding value must be added back into the query.
	for _, b := range sortbindings(bindings) {
		if !b.containedIn(result) {
			result.Append(ast.Equality.Expr(ast.NewTerm(b.k), ast.NewTerm(b.v)))
		}
	}

	if p.ensureNonEmptyBody && len(result) == 0 {
		result = append(result, ast.NewExpr(ast.BooleanTerm(true)))
	}

	return result
}
5203
func (env *CustomEnv) Var(ident string) reflect.Value {
	// Note that variables are always pointer values.
	if v := env.Env.Var(ident); v.IsValid() && v.Type().Elem().Kind() == reflect.Int {
		i := v.Elem().Int()
		plusOne := reflect.New(v.Type().Elem()).Elem()
		plusOne.Set(reflect.ValueOf(int(i + 1)))
		return plusOne.Addr()
	} else {
		return v
	}
}
202669
func (s *SHA1Reporter) Var() expvar.Var {
	s.loadFileInfo()
	return expvar.Func(func() interface{} {
		return s.Fi
	})
}
879688
func (s *RedisApplicationStore) Get(appID string) (*Application, error) {
	applicationI, err := s.store.Get(appID)
	if err != nil {
		return nil, err
	}
	if application, ok := applicationI.(Application); ok {
		return &application, nil
	}
	return nil, errors.New("Database did not return a Application")
}
961829
func (c *Controller) updateApplication(ch ApplicationChange) {
	c.ensureModel(ch.ModelUUID).updateApplication(ch, c.manager)
}
1368277
func (s *DB) SubQuery() *expr {
	scope := s.NewScope(s.Value)
	scope.InstanceSet("skip_bindvar", true)
	scope.prepareQuerySQL()

	return Expr(fmt.Sprintf("(%v)", scope.SQL), scope.SQLVars...)
}
123514
func (q ConfigsQuery) scope(db *gorm.DB) *gorm.DB {
	var scope composedScope

	if q.ID != nil {
		scope = append(scope, idEquals(*q.ID))
	}

	if q.App != nil {
		scope = append(scope, forApp(q.App))
	}

	return scope.scope(db)
}
532482
func main() {
	var addr, conf string
	flag.StringVar(&addr, "a", "127.0.0.1:9876", "`address` of server")
	flag.StringVar(&conf, "f", "server.json", "config `file` to use")
	flag.Parse()

	var id = new(core.Identity)
	data, err := ioutil.ReadFile(conf)
	if err != nil {
		exlib.Err(1, err, "reading config file")
	}

	err = json.Unmarshal(data, id)
	if err != nil {
		exlib.Err(1, err, "parsing config file")
	}

	tr, err := transport.New(exlib.Before, id)
	if err != nil {
		exlib.Err(1, err, "creating transport")
	}

	l, err := transport.Listen(addr, tr)
	if err != nil {
		exlib.Err(1, err, "setting up listener")
	}

	var errChan = make(chan error, 0)
	go func(ec <-chan error) {
		for {
			err, ok := <-ec
			if !ok {
				log.Warning("error channel closed, future errors will not be reported")
				break
			}
			log.Errorf("auto update error: %v", err)
		}
	}(errChan)

	log.Info("setting up auto-update")
	go l.AutoUpdate(nil, errChan)

	log.Info("listening on ", addr)
	exlib.Warn(serve(l), "serving listener")
}
850941
func Tx(db *sql.DB, txFunc func(*sql.Tx) error) (err error) {
	tx, err := db.Begin()
	if err != nil {
		return
	}
	defer func() {
		if p := recover(); p != nil {
			switch p := p.(type) {
			case error:
				err = p
			default:
				err = fmt.Errorf("%s", p)
			}
		}
		if err != nil {
			tx.Rollback()
			return
		}
		err = tx.Commit()
	}()
	return txFunc(tx)
}
938673
func main() {

	// init a connection
	s, err := solr.Init("localhost", 8983, "collection-name")

	if err != nil {
		fmt.Println(err)
		return
	}

	// Build a query object
	// Here we are specifying a 'q' param,
	// rows, faceting and facet.fields
	q := solr.Query{
		Params: solr.URLParamMap{
			"q":           []string{"id:13"},
			"facet.field": []string{"accepts_4x4s", "accepts_bicycles"},
			"facet":       []string{"true"},
		},
		Rows: 10,
	}

	// perform the query, checking for errors
	res, err := s.Select(&q)

	if err != nil {
		fmt.Println(err)
		return
	}

	// grab results for ease of use later on
	results := res.Results

	// print a summary and loop over results, priting the "title" and "latlng" fields
	fmt.Println(
		fmt.Sprintf("Query: %#v\nHits: %d\nNum Results: %d\nQtime: %d\nStatus: %d\n\nResults\n-------\n",
			q,
			results.NumFound,
			results.Len(),
			res.QTime,
			res.Status))

	for i := 0; i < results.Len(); i++ {
		fmt.Println("Some field:", results.Get(i).Field("id"))
		fmt.Println("Some other field:", results.Get(i).Field("title"))

		fmt.Println("")
	}

}
1372119
func appsFindOrCreateByRepo(db *gorm.DB, repo string) (*App, error) {
	n := appNameFromRepo(repo)
	a, err := appsFind(db, AppsQuery{Name: &n})
	if err != nil && err != gorm.RecordNotFound {
		return a, err
	}

	// If the app wasn't found, create a new app.
	if err != gorm.RecordNotFound {
		return a, appsEnsureRepo(db, a, repo)
	}

	a = &App{
		Name: n,
		Repo: &repo,
	}

	return appsCreate(db, a)
}
321182
func (q DomainsQuery) scope(db *gorm.DB) *gorm.DB {
	var scope composedScope

	if q.Hostname != nil {
		scope = append(scope, fieldEquals("hostname", *q.Hostname))
	}

	if q.App != nil {
		scope = append(scope, forApp(q.App))
	}

	return scope.scope(db)
}