//构建实体模型的插入函数 func createInsertFunc(modelInfo *modelMeta) EntityCFunc { insertFields := fun.Filter(exceptIdPred, modelInfo.fields).([]*modelField) columns := strings.Join(fun.Map(func(field *modelField) string { return field.column }, insertFields).([]string), ",") params := strings.Join(toSlice("?", len(insertFields)), ",") return func(executor interface{}, entity EntityInterface) error { ind := checkEntity(modelInfo, entity, executor) paramValues := make([]interface{}, 0, len(insertFields)) for _, field := range insertFields { fv := ind.Field(field.index).Interface() paramValues = append(paramValues, fv) } insertSql := fmt.Sprintf("INSERT INTO %s (%s) VALUES(%s)", entity.TableName(), columns, params) c.Debugf("insertSql:%v", insertSql) rs, err := exec(executor, insertSql, paramValues) if err != nil { return err } if modelInfo.pkField.pkAuto { if id, err := rs.LastInsertId(); err == nil { ind.Field(modelInfo.pkField.index).SetInt(id) } else { return err } } return nil } }
// LoadCertificateForDomains loads certificates from ACME for given domains func (a *ACME) LoadCertificateForDomains(domains []string) { domains = fun.Map(types.CanonicalDomain, domains).([]string) safe.Go(func() { operation := func() error { if a.client == nil { return fmt.Errorf("ACME client still not built") } return nil } notify := func(err error, time time.Duration) { log.Errorf("Error getting ACME client: %v, retrying in %s", err, time) } ebo := backoff.NewExponentialBackOff() ebo.MaxElapsedTime = 30 * time.Second err := backoff.RetryNotify(operation, ebo, notify) if err != nil { log.Errorf("Error getting ACME client: %v", err) return } account := a.store.Get().(*Account) var domain Domain if len(domains) == 0 { // no domain return } else if len(domains) > 1 { domain = Domain{Main: domains[0], SANs: domains[1:]} } else { domain = Domain{Main: domains[0]} } if _, exists := account.DomainsCertificate.exists(domain); exists { // domain already exists return } certificate, err := a.getDomainsCertificates(domains) if err != nil { log.Errorf("Error getting ACME certificates %+v : %v", domains, err) return } log.Debugf("Got certificate for domains %+v", domains) transaction, object, err := a.store.Begin() if err != nil { log.Errorf("Error creating transaction %+v : %v", domains, err) return } account = object.(*Account) _, err = account.DomainsCertificate.addCertificateForDomains(certificate, domain) if err != nil { log.Errorf("Error adding ACME certificates %+v : %v", domains, err) return } if err = transaction.Commit(account); err != nil { log.Errorf("Error Saving ACME account %+v: %v", account, err) return } }) }
func (sl *simpleLoad) add(line []byte, args ...interface{}) { if err := sl.ins.Exec(args...); err != nil { toStr := func(v interface{}) string { return sf("%#v", v) } logf("Full %s info (that failed to add): %s", sl.table, fun.Map(toStr, args).([]string)) logf("Context: %s", line) csql.Panic(ef("Error adding to %s table: %s", sl.table, err)) } sl.count++ }
func (s *Searcher) where() string { var conj []string conj = append(conj, s.whereCredits()...) entString := func(e imdb.EntityKind) string { return e.String() } ents := fun.Map(entString, s.entities).([]string) conj = append(conj, s.inStrs(s.entityColumn(), ents)) conj = append(conj, s.inStrs("mpaa_rating.rating", s.mpaas)) conj = append(conj, s.inSubquery("genre", "name", s.genres)) if !s.subTvshow.empty() { conj = append(conj, sf("e.tvshow_atom_id = %d", s.subTvshow.id)) } if s.atom > 0 { conj = append(conj, sf("name.atom_id = %d", s.atom)) } if s.year != nil { conj = append(conj, s.year.cond("COALESCE(m.year, t.year, e.year, 0)")) } if s.rating != nil { conj = append(conj, s.rating.cond("rating.rank")) } if s.votes != nil { conj = append(conj, s.votes.cond("rating.votes")) } if s.season != nil { cond := sf("(e.atom_id IS NULL OR %s)", s.season.cond("e.season")) conj = append(conj, cond) } if s.episode != nil { cond := sf("(e.atom_id IS NULL OR %s)", s.episode.cond("e.episode_num")) conj = append(conj, cond) } if s.noTvMovie { conj = append(conj, "(m.atom_id IS NULL OR m.tv = cast(0 as boolean))") } if s.noVideoMovie { conj = append(conj, "(m.atom_id IS NULL OR m.video = cast(0 as boolean))") } if len(s.name) > 0 { if s.fuzzy { conj = append(conj, "name.name % $1") } else { if s.db.Driver == "postgres" { conj = append(conj, sf("name.name ILIKE $1")) } else { conj = append(conj, sf("name.name LIKE $1")) } } } return strings.Join(conj, " AND ") }
// ParseDomains parses rules expressions and returns domains func (r *Rules) ParseDomains(expression string) ([]string, error) { domains := []string{} err := r.parseRules(expression, func(functionName string, function interface{}, arguments []string) error { if functionName == "Host" { domains = append(domains, arguments...) } return nil }) if err != nil { return nil, fmt.Errorf("Error parsing domains: %v", err) } return fun.Map(types.CanonicalDomain, domains).([]string), nil }
func cmd_rename(c *command) bool { if len(flagRenameTvshow) > 0 { return cmd_rename_tvshow(c, flagRenameTvshow) } firstArg := c.flags.Arg(0) if _, err := os.Stat(firstArg); err == nil { return cmd_rename_smart(c) } c.assertLeastNArg(2) db := openDb(c.dbinfo()) defer closeDb(db) query := c.flags.Arg(0) files := fun.Map(path.Clean, c.flags.Args()[1:]).([]string) searcher, err := search.Query(db, query) if err != nil { pef("%s", err) return false } searcher.Chooser(c.chooser) searcher.Limit(len(files)) results, err := searcher.Results() if err != nil { pef("%s", err) return false } if len(results) == 0 { pef("No search results.") return false } if len(results) < len(files) { pef("Omitting last %d file(s) since there are only %d search results.", len(files)-len(results), len(results)) files = files[0:len(results)] } entities := make([]imdb.Entity, len(results)) for i, r := range results { e, err := r.GetEntity(db) if err != nil { pef("Could not get entity for '%s': %s", r, err) return false } entities[i] = e } return doRename(c, db, files, entities) }
func (a *ACME) getDomainsCertificates(domains []string) (*Certificate, error) { domains = fun.Map(types.CanonicalDomain, domains).([]string) log.Debugf("Loading ACME certificates %s...", domains) bundle := true certificate, failures := a.client.ObtainCertificate(domains, bundle, nil, OSCPMustStaple) if len(failures) > 0 { log.Error(failures) return nil, fmt.Errorf("Cannot obtain certificates %s+v", failures) } log.Debugf("Loaded ACME certificates %s", domains) return &Certificate{ Domain: certificate.Domain, CertURL: certificate.CertURL, CertStableURL: certificate.CertStableURL, PrivateKey: certificate.PrivateKey, Certificate: certificate.Certificate, }, nil }
func cmd_rename_smart(c *command) bool { c.assertLeastNArg(1) db := openDb(c.dbinfo()) defer closeDb(db) files := fun.Map(path.Clean, c.flags.Args()).([]string) var oldNames []string var newNames []imdb.Entity for _, file := range files { e, err := guessEntity(c, db, file) if err != nil { pef("Could not guess entity for '%s': %s", file, err) continue } oldNames = append(oldNames, file) newNames = append(newNames, e) } return doRename(c, db, oldNames, newNames) }
func cmd_rename_tvshow(c *command, tvQuery string) bool { c.assertLeastNArg(1) db := openDb(c.dbinfo()) defer closeDb(db) files := fun.Map(path.Clean, c.flags.Args()).([]string) tv, err := searchTvshow(c, db, tvQuery) if err != nil { pef("%s", err) return false } episodes, err := tvEpisodes(db, tv) if err != nil { pef("%s", err) return false } var oldNames []string var newNames []imdb.Entity for _, file := range files { baseFile := path.Base(file) s, e, _, _, err := episodeNumbers(baseFile, flagRenameRegexEpisode) if err != nil { pef("Could not find episode numbers in '%s': %s", file, err) continue } if s == 0 || e == 0 { pef("Found numbers, but they look wrong: (s: %d, e: %d)", s, e) continue } ep, ok := episodes[episodeKey{s, e}] if !ok { pef("Could not find episode (%s, S%02dE%02d) for '%s'.", tv, s, e, file) continue } oldNames = append(oldNames, file) newNames = append(newNames, ep) } return doRename(c, db, oldNames, newNames) }
//构建查询函数 func createQueryFunc(modelInfo *modelMeta) EntityQFunc { columns := strings.Join(fun.Map(func(field *modelField) string { return "`" + field.column + "`" }, modelInfo.fields).([]string), ",") return func(executor interface{}, entity EntityInterface, condition string, params []interface{}) ([]EntityInterface, error) { ind := checkEntity(modelInfo, entity, executor) querySql := fmt.Sprintf("SELECT %s FROM %s ", columns, entity.TableName()) if len(condition) > 0 { querySql += condition } c.Debugf("querySql:%v", querySql) rows, err := query(executor, querySql, params) if err != nil { return nil, err } defer rows.Close() var rt = make([]EntityInterface, 0, 10) for rows.Next() { ptrValue := reflect.New(ind.Type()) ptrValueInd := reflect.Indirect(ptrValue) ptrValueSlice := make([]interface{}, 0, len(modelInfo.fields)) for _, field := range modelInfo.fields { fv := ptrValueInd.Field(field.index).Addr().Interface() //c.Debugf("fv:%v,type:%T", fv, fv) ptrValueSlice = append(ptrValueSlice, fv) } if err := rows.Scan(ptrValueSlice...); err == nil { rt = append(rt, ptrValue.Interface().(EntityInterface)) } else { return nil, err } } return rt, nil } }
//构建实体模型的更新函数 func createUpdateFunc(modelInfo *modelMeta) EntityUFunc { updateFields := fun.Filter(exceptIdPred, modelInfo.fields).([]*modelField) columns := strings.Join(fun.Map(func(field *modelField) string { return field.column + "=?" }, updateFields).([]string), ",") return func(executor interface{}, entity EntityInterface) (bool, error) { ind := checkEntity(modelInfo, entity, executor) paramValues := make([]interface{}, 0, len(updateFields)+1) for _, field := range updateFields { fv := ind.Field(field.index).Interface() paramValues = append(paramValues, fv) } id := ind.Field(modelInfo.pkField.index).Interface() paramValues = append(paramValues, id) updateSql := fmt.Sprintf("UPDATE %s SET %s where %s = %s", entity.TableName(), columns, modelInfo.pkField.column, "?") c.Debugf("updateSql:%v", updateSql) rs, err := exec(executor, updateSql, paramValues) if err != nil { return false, err } //检查更新的记录数 if rows, err := rs.RowsAffected(); err == nil { if rows != 1 { return false, err } else { return true, err } } else { return false, err } } }
func Map(xs, f interface{}) interface{} { return fun.Map(f, xs) }