// Create a new handler dumping data chunks and index info to db for an // object/file identified by label. func New(tx *sql.Tx, label string) (h *Handler, err error) { // get next file/object id var maxfid sql.NullInt64 row := tx.QueryRow(getMaxFidSql) if err := row.Scan(&maxfid); err != nil { return nil, err } // get next chunk rowid var maxrow sql.NullInt64 row = tx.QueryRow(getMaxChunkRowSql) if err := row.Scan(&maxrow); err != nil { return nil, err } // config and return handler h = &Handler{} h.tx = tx h.nextChunkRow = int(maxrow.Int64) + 1 h.label = label h.fid = int(maxfid.Int64) + 1 h.fullH = sha1.New() h.chunkH = sha1.New() return h, nil }
func makeAttempt(tx *sql.Tx, unit *workUnit, w *worker, length time.Duration) (*attempt, error) { a := attempt{unit: unit, worker: w} now := a.Coordinate().clock.Now() expiration := now.Add(length) params := queryParams{} fields := fieldList{} fields.Add(¶ms, "work_unit_id", unit.id) fields.Add(¶ms, "work_spec_id", unit.spec.id) fields.Add(¶ms, "worker_id", w.id) fields.Add(¶ms, "start_time", now) fields.Add(¶ms, "expiration_time", expiration) query := fields.InsertStatement(attemptTable) + " RETURNING id" row := tx.QueryRow(query, params...) err := row.Scan(&a.id) if err != nil { return nil, err } params = queryParams{} fields = fieldList{} fields.Add(¶ms, "active_attempt_id", a.id) query = buildUpdate(workUnitTable, fields.UpdateChanges(), []string{ isWorkUnit(¶ms, unit.id), }) _, err = tx.Exec(query, params...) return &a, err }
func (aca *ACA) populateAttribute(tx *sql.Tx, attr *AttributePair) error { fmt.Printf("*********************** ATTR %v %v %v\n", attr.GetID(), attr.attributeName, string(attr.attributeValue)) var count int err := tx.QueryRow("SELECT count(row) AS cant FROM Attributes WHERE id=? AND affiliation =? AND attributeName =?", attr.GetID(), attr.GetAffiliation(), attr.GetAttributeName()).Scan(&count) if err != nil { return err } if count > 0 { _, err = tx.Exec("UPDATE Attributes SET validFrom = ?, validTo = ?, attributeValue = ? WHERE id=? AND affiliation =? AND attributeName =? AND validFrom < ?", attr.GetValidFrom(), attr.GetValidTo(), attr.GetAttributeValue(), attr.GetID(), attr.GetAffiliation(), attr.GetAttributeName(), attr.GetValidFrom()) if err != nil { return err } } else { _, err = tx.Exec("INSERT INTO Attributes (validFrom , validTo, attributeValue, id, affiliation, attributeName) VALUES (?,?,?,?,?,?)", attr.GetValidFrom(), attr.GetValidTo(), attr.GetAttributeValue(), attr.GetID(), attr.GetAffiliation(), attr.GetAttributeName()) if err != nil { return err } } return nil }
func (d *Postgres) addLogTrack(tx *sql.Tx, log *models.Log, track *models.Track) error { var name *string if track.Name != "" { name = &track.Name } query, args, dest := sqlbuilder.Insert(). Dialect(sqlbuilder.Postgres). Into(`"track"`). Set(`"log_id"`, log.ID). Set(`"name"`, name). Set(`"start"`, track.Start). Set(`"end"`, track.End). Set(`"duration"`, track.Duration). Set(`"distance"`, track.Distance). Return(`"id"`, &track.ID). Build() if err := tx.QueryRow(query, args...).Scan(dest...); err != nil { return err } for _, point := range track.Points { if err := d.addTrackPoint(tx, track, point); err != nil { return err } } return nil }
// Attach a prefix to the prefix tree, reparenting other prefixes if needed. func (s *server) attachPrefix(tx *sql.Tx, realmID, prefixID int64, prefix string) error { var parentID *int64 q := `SELECT prefix_id FROM prefixes WHERE realm_id=$1 AND prefixIsInside($2, prefix) ORDER BY prefixLen(prefix) DESC LIMIT 1` if err := tx.QueryRow(q, realmID, prefix).Scan(&parentID); err != nil && err != sql.ErrNoRows { return err } if parentID == nil { q = `UPDATE prefixes SET parent_id=NULL WHERE realm_id=$1 AND prefix_id=$2` if _, err := tx.Exec(q, realmID, prefixID); err != nil { return err } q = `UPDATE prefixes SET parent_id=$1 WHERE realm_id=$2 AND parent_id IS NULL AND prefixIsInside(prefix, $3)` if _, err := tx.Exec(q, prefixID, realmID, prefix); err != nil { return err } } else { q = `UPDATE prefixes SET parent_id=$1 WHERE realm_id=$2 AND prefix_id=$3` if _, err := tx.Exec(q, *parentID, realmID, prefixID); err != nil { return err } q = `UPDATE prefixes SET parent_id=$1 WHERE realm_id=$2 AND parent_id=$3 AND prefixIsInside(prefix, $4)` if _, err := tx.Exec(q, prefixID, realmID, *parentID, prefix); err != nil { return err } } return nil }
// returns sql.ErrNoRows if not found func FindPublication(tx *sql.Tx, domain string) (int, error) { // TODO (maybe) match both www. and non www. versions? //domain = strings.ToLower(domain) var pubID int err := tx.QueryRow(`SELECT pub_id FROM pub_domain WHERE domain=$1`, domain).Scan(&pubID) return pubID, err }
func recipeContainsAlcohol(tx *sql.Tx, recipe_id string) bool { sql := ` select count(*) from recipe r inner join recipe_ingredient ri on ri.recipe_id = r.id inner join ingredient i on i.id = ri.ingredient_id where r.id = ? and alcoholic = 1` var alcoholic int row := tx.QueryRow(sql, recipe_id) err := row.Scan(&alcoholic) if err != nil { panic(fmt.Sprintf("recipeContainsAlcohol failed: %v", err)) return true } if alcoholic > 0 { return true } else { return false } }
// AddParent adds a parent. Uses passed transaction or a new one if one is not provided func AddParent(familyID int, name string, email string, password string, tx *sql.Tx) (int, error) { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) needCommit := false if tx == nil { tx, err = db.Begin() if err != nil { return 0, err } needCommit = true defer tx.Rollback() } // Create the parent if _, err := tx.Exec("INSERT INTO parents VALUES(NULL, ?, ?, ?, ?, NULL, NULL)", familyID, name, email, hashedPassword); err != nil { return 0, err } // Get the ID var ID int row := tx.QueryRow("SELECT LAST_INSERT_ID()") err = row.Scan(&ID) if needCommit { tx.Commit() } return ID, err }
func insertText(t *testing.T, conn *sql.Tx, spanish, chinese, russian string) bool { qry := "INSERT INTO " + tbl + " (F_int, F_text_spanish, F_text_chinese, F_text_russian)" + " VALUES (-1, :1, :2, :3)" if _, err := conn.Exec(qry, spanish, chinese, russian); err != nil { t.Errorf("cannot insert into "+tbl+" (%q): %v", qry, err) } row := conn.QueryRow("SELECT F_text_spanish, F_text_chinese, F_text_russian FROM " + tbl + " WHERE F_int = -1") var tSpanish, tChinese, tRussian string if err := row.Scan(&tSpanish, &tChinese, &tRussian); err != nil { t.Errorf("error scanning row: %v", errgo.Details(err)) return false } t.Logf("spanish=%q chinese=%q russian=%q", spanish, chinese, russian) ok := true if tSpanish != spanish { t.Errorf("spanish mismatch: got %q, awaited %q", tSpanish, spanish) ok = false } if tChinese != chinese { t.Errorf("chinese mismatch: got %q, awaited %q", tChinese, chinese) ok = false } if tRussian != russian { t.Errorf("russian mismatch: got %q, awaited %q", tRussian, russian) ok = false } return ok }
func createJourno(tx *sql.Tx, journo *arts.Author) (int, error) { ref, err := uniqRef(tx, baseRef(journo.Name)) if err != nil { return 0, err } prettyName := journo.Name firstName, lastName := splitName(journo.Name) firstNameMetaphone := phonetics.EncodeMetaphone(firstName) lastNameMetaphone := phonetics.EncodeMetaphone(lastName) var journoID int err = tx.QueryRow(`INSERT INTO journo (id,ref,prettyname,firstname,lastname,firstname_metaphone,lastname_metaphone,created) VALUES (DEFAULT,$1,$2,$3,$4,$5,$6,NOW()) RETURNING id`, ref, prettyName, firstName, lastName, firstNameMetaphone, lastNameMetaphone).Scan(&journoID) if err != nil { return 0, err } // TODO: future: fill out journo_alias table, and also rel-author links etc to help resolution... return journoID, nil }
func addGeometryColumn(tx *sql.Tx, tableName string, spec TableSpec) error { colName := "" for _, col := range spec.Columns { if col.Type.Name() == "GEOMETRY" { colName = col.Name break } } if colName == "" { return nil } geomType := strings.ToUpper(spec.GeometryType) if geomType == "POLYGON" { geomType = "GEOMETRY" // for multipolygon support } sql := fmt.Sprintf("SELECT AddGeometryColumn('%s', '%s', '%s', '%d', '%s', 2);", spec.Schema, tableName, colName, spec.Srid, geomType) row := tx.QueryRow(sql) var void interface{} err := row.Scan(&void) if err != nil { return &SQLError{sql, err} } return nil }
func createPublication(tx *sql.Tx, pub *arts.Publication) (int, error) { prettyName := pub.Name if prettyName == "" { prettyName = strippedDomain(pub.Domain) } shortName := genShortName(prettyName) // strip leading "the"s for more natural sort order sortName := strings.ToLower(prettyName) sortName = stripThePat.ReplaceAllLiteralString(prettyName, "") homeURL := "http://" + pub.Domain var pubID int err := tx.QueryRow(`INSERT INTO organisation (id,shortname,prettyname,sortname,home_url) VALUES (DEFAULT, $1,$2,$3,$4) RETURNING id`, shortName, prettyName, sortName, homeURL).Scan(&pubID) if err != nil { return 0, err } _, err = tx.Exec(`INSERT INTO pub_domain (pub_id,domain) VALUES ($1, $2)`, pubID, pub.Domain) if err != nil { return 0, err } _, err = tx.Exec(`INSERT INTO pub_alias (pub_id,alias) VALUES ($1, $2)`, pubID, prettyName) if err != nil { return 0, err } return pubID, nil }
func UpdateSchema(txn *sql.Tx) error { var ( err error count int64 ) err = txn.QueryRow( `SELECT COUNT(table_name) FROM information_schema.tables WHERE table_schema = $1 AND table_name = $2;`, "public", "cas_objects", ).Scan(&count) if err != nil { return err } if count == 0 { _, err = txn.Exec( ` CREATE TABLE cas_objects ( address BYTEA NOT NULL, content BYTEA, external VARCHAR, PRIMARY KEY (address), CHECK (octet_length(address) = 20), CHECK (content IS NOT NULL OR external IS NOT NULL) ); `, ) if err != nil { return err } } return nil }
func insertTaskFunctions(tx *sql.Tx) error { var minTaskFunction, minPriority int row := tx.QueryRow("SELECT task_function, priority FROM scheduled_functions ORDER BY scheduled_time DESC, priority DESC, task_function DESC LIMIT 1") if err := row.Scan(&minTaskFunction, &minPriority); err == sql.ErrNoRows { log.Printf("no prior functions scheduled") noPriorFunctionsScheduledCounter.Inc(1) } else if err != nil { log.Printf("error finding max last priority: %v", err) lastMaxPriorityErrorCounter.Inc(1) return err } log.Printf("min task function: %v, min priority: %v", minTaskFunction, minPriority) if _, err := tx.Exec("DELETE FROM scheduled_functions WHERE expiration_time < now() OR measurements_remaining <= 0"); err != nil { log.Printf("error deleting expired task functions: %v", err) deleteExpiredFunctionsErrorCounter.Inc(1) return err } var toSchedule int row = tx.QueryRow("SELECT concurrent_functions - scheduled FROM (SELECT count(1) scheduled FROM scheduled_functions) AS c, scheduler_configuration") if err := row.Scan(&toSchedule); err != nil { log.Printf("error counting scheduled tasks: %v", err) countSchedluedTasksErrorCounter.Inc(1) return err } result, err := tx.Exec("INSERT INTO scheduled_functions (task_function, expiration_time, measurements_remaining, priority, scheduled_time) SELECT id, now() + max_duration_seconds * interval '1 second', max_measurements, priority, now() FROM task_functions WHERE enabled AND ((priority = $1 AND id > $2) OR priority > $1) ORDER BY priority, id LIMIT $3", minPriority, minTaskFunction, toSchedule) if err != nil { log.Printf("error inserting new schedules: %v", err) insertScheduledFunctionsErrorCounter.Inc(1) return err } rowsAffected, err := result.RowsAffected() if err != nil { log.Printf("error discovering number of affected rows: %v", err) countScheduledFunctionsErrorCounter.Inc(1) return err } toSchedule -= int(rowsAffected) result, err = tx.Exec("INSERT INTO scheduled_functions (task_function, expiration_time, measurements_remaining, priority, scheduled_time) SELECT id, now() + max_duration_seconds * interval '1 second', max_measurements, priority, now() FROM task_functions WHERE enabled ORDER BY priority, id LIMIT $1", toSchedule) if err != nil { log.Printf("error inserting new schedules: %v", err) insertScheduledFunctionsErrorCounter.Inc(1) return err } rowsAffected, err = result.RowsAffected() if err != nil { log.Printf("error discovering number of affected rows: %v", err) countScheduledFunctionsErrorCounter.Inc(1) return err } toSchedule -= int(rowsAffected) if toSchedule > 0 { log.Printf("unable to fill schedule") unfilledScheduleCounter.Inc(1) } return nil }
// TODO: is this used? func CreatePublication(tx *sql.Tx, domain, name string) (*Publication, error) { pub := NewPublication(domain, name) err := tx.QueryRow(`INSERT INTO organisation (id,shortname,prettyname,sortname,home_url) VALUES (DEFAULT, $1,$2,$3,$4) RETURNING id`, pub.ShortName, pub.PrettyName, pub.SortName, pub.HomeURL).Scan(&pub.ID) if err != nil { return nil, err } for _, domain := range pub.Domains { _, err = tx.Exec(`INSERT INTO pub_domain (pub_id,domain) VALUES ($1, $2)`, pub.ID, domain) if err != nil { return nil, err } } _, err = tx.Exec(`INSERT INTO pub_alias (pub_id,alias) VALUES ($1, $2)`, pub.ID, pub.PrettyName) if err != nil { return nil, err } return pub, nil }
func (s *SQLEngine) ctimeFromMessage(tx *sql.Tx, u gregor.UID, mid gregor.MsgID) (time.Time, error) { row := tx.QueryRow("SELECT ctime FROM gregor_messages WHERE uid=? AND msgid=?", hexEnc(u), hexEnc(mid)) var ctime timeScanner if err := row.Scan(&ctime); err != nil { return time.Time{}, err } return ctime.Time(), nil }
func ModelExample(tx *sql.Tx, user, model string) (input string, err error) { q := `SELECT m.example_input FROM Model m INNER JOIN User u ON u.user_id = m.user_id WHERE m.modelname = ? AND u.username = ?;` err = tx.QueryRow(q, model, user).Scan(&input) return }
// getSequence get sequence number func getSequence(tx *sql.Tx) (id uint64, err error) { if _, err := tx.Query("UPDATE seq SET id = LAST_INSERT_ID(id + 1)"); err != nil { return 0, err } if err := tx.QueryRow("SELECT LAST_INSERT_ID()").Scan(&id); err != nil { return 0, err } return }
func Get(tx *sql.Tx, uid string) (*model.File, error) { m := &model.File{} err := tx.QueryRow(selectQuery+"WHERE uid = unhex(?)", uid).Scan(&m.UID, &m.Name, &m.Mime, &m.UniqueID, &m.Type, &m.Tmp, &m.CreatedAt) if err != nil { return nil, err } return m, nil }
// getLastLogEntry returns the index and term of the last entry in the log. func getLastLogEntry(tx *sql.Tx) (index, term int, err error) { err = tx.QueryRow(`SELECT index, term FROM log ORDER BY index LIMIT 1`).Scan(&index, &term) if err == sql.ErrNoRows { return -1, -1, nil } else if err != nil { log.Printf("db error checking last log entry index and term: %v", err) return 0, 0, err } return index, term, nil }
func isPostGIS2(tx *sql.Tx) (bool, error) { sql := fmt.Sprintf("SELECT PostGIS_lib_version();") row := tx.QueryRow(sql) var version string err := row.Scan(&version) if err != nil { return false, &SQLError{sql, err} } return strings.HasPrefix(version, "2."), nil }
func insertNum(t *testing.T, conn *sql.Tx, small int, bigint string, notint float64, bigreal string, text string, date time.Time, ) bool { date = date.Round(time.Second) qry := fmt.Sprintf(`INSERT INTO `+tbl+` (F_int, F_bigint, F_real, F_bigreal, F_text, F_date) VALUES (%d, %s, %3.3f, %s, '%s', TO_DATE('%s', 'YYYY-MM-DD HH24:MI:SS')) `, small, bigint, notint, bigreal, text, date.Format("2006-01-02 15:04:05")) if _, err := conn.Exec(qry); err != nil { t.Errorf("cannot insert into "+tbl+" (%q): %v", qry, err) return false } row := conn.QueryRow("SELECT F_int, F_bigint, F_real, F_bigreal, F_text, F_date FROM "+tbl+" WHERE F_int = :1", small) var ( smallO int bigintO big.Int notintO float64 bigrealF, bigrealO big.Rat bigintS, bigrealS string textO string dateO time.Time ) if err := row.Scan(&smallO, &bigintS, ¬intO, &bigrealS, &textO, &dateO); err != nil { t.Errorf("error scanning row[%d]: %v", small, errgo.Details(err)) return false } t.Logf("row: small=%d big=%s notint=%f bigreal=%s text=%q date=%s", smallO, bigintS, notintO, bigrealS, textO, dateO) if smallO != small { t.Errorf("small mismatch: got %d, awaited %d.", smallO, small) } (&bigintO).SetString(bigintS, 10) if bigintO.String() != bigint { t.Errorf("bigint mismatch: got %s, awaited %s.", bigintO, bigint) } if notintO != notint { t.Errorf("noting mismatch: got %f, awaited %f.", notintO, notint) } (&bigrealF).SetString(bigreal) (&bigrealO).SetString(bigrealS) if (&bigrealO).Cmp(&bigrealF) != 0 { t.Errorf("bigreal mismatch: got %s, awaited %f.", (&bigrealO), (&bigrealF)) } if textO != text { t.Errorf("text mismatch: got %q, awaited %q.", textO, text) } if !dateO.Equal(date) { t.Errorf("date mismatch: got %s, awaited %s.", dateO, date.Round(time.Second)) } return true }
func (pdb *pipelineDB) createJobBuild(jobName string, tx *sql.Tx) (Build, error) { err := pdb.registerJob(tx, jobName) if err != nil { return Build{}, err } dbJob, err := pdb.getJob(tx, jobName) if err != nil { return Build{}, err } var name string err = tx.QueryRow(` UPDATE jobs SET build_number_seq = build_number_seq + 1 WHERE id = $1 RETURNING build_number_seq `, dbJob.ID).Scan(&name) if err != nil { return Build{}, err } // We had to resort to sub-selects here because you can't paramaterize a // RETURNING statement in lib/pq... sorry build, _, err := pdb.scanBuild(tx.QueryRow(` INSERT INTO builds (name, job_id, status) VALUES ($1, $2, 'pending') RETURNING `+buildColumns+`, ( SELECT j.name FROM jobs j WHERE j.id = job_id ), ( SELECT p.name FROM jobs j INNER JOIN pipelines p ON j.pipeline_id = p.id WHERE j.id = job_id ) `, name, dbJob.ID)) if err != nil { return Build{}, err } _, err = tx.Exec(fmt.Sprintf(` CREATE SEQUENCE %s MINVALUE 0 `, buildEventSeq(build.ID))) if err != nil { return Build{}, err } return build, nil }
func populateGeometryColumn(tx *sql.Tx, tableName string, spec TableSpec) error { sql := fmt.Sprintf("SELECT Populate_Geometry_Columns('%s.%s'::regclass);", spec.Schema, tableName) row := tx.QueryRow(sql) var void interface{} err := row.Scan(&void) if err != nil { return &SQLError{sql, err} } return nil }
// insertVulnerabilityFixedInFeatureVersions populates Vulnerability_FixedIn_Feature for the given // vulnerability with the specified database.FeatureVersion list and uses // linkVulnerabilityToFeatureVersions to propagate the changes on Vulnerability_FixedIn_Feature to // Vulnerability_Affects_FeatureVersion. func (pgSQL *pgSQL) insertVulnerabilityFixedInFeatureVersions(tx *sql.Tx, vulnerabilityID int, fixedIn []database.FeatureVersion) error { defer observeQueryTime("insertVulnerabilityFixedInFeatureVersions", "all", time.Now()) // Insert or find the Features. // TODO(Quentin-M): Batch me. var err error var features []*database.Feature for i := 0; i < len(fixedIn); i++ { features = append(features, &fixedIn[i].Feature) } for _, feature := range features { if feature.ID == 0 { if feature.ID, err = pgSQL.insertFeature(*feature); err != nil { return err } } } // Lock Vulnerability_Affects_FeatureVersion exclusively. // We want to prevent InsertFeatureVersion to modify it. promConcurrentLockVAFV.Inc() defer promConcurrentLockVAFV.Dec() t := time.Now() _, err = tx.Exec(lockVulnerabilityAffects) observeQueryTime("insertVulnerability", "lock", t) if err != nil { tx.Rollback() return handleError("insertVulnerability.lockVulnerabilityAffects", err) } for _, fv := range fixedIn { var fixedInID int // Insert Vulnerability_FixedIn_Feature. err = tx.QueryRow( insertVulnerabilityFixedInFeature, vulnerabilityID, fv.Feature.ID, &fv.Version, ).Scan(&fixedInID) if err != nil { return handleError("insertVulnerabilityFixedInFeature", err) } // Insert Vulnerability_Affects_FeatureVersion. err = linkVulnerabilityToFeatureVersions(tx, fixedInID, vulnerabilityID, fv.Feature.ID, fv.Version) if err != nil { return err } } return nil }
func GetClientByID(tx *sql.Tx, id string) (*model.Client, error) { client := &model.Client{} // get client err := tx.QueryRow("SELECT lower(hex(uid)), clientID, clientSecret, redirectURI FROM "+clientTable+" WHERE clientID = ?", id).Scan(&client.UID, &client.Id, &client.Secret, &client.RedirectUri) if err != nil { return nil, err } return client, nil }
func Get(tx *sql.Tx, uid string) (*model.Group, error) { r := &model.Group{} row := tx.QueryRow(selectQuery+"WHERE uid = unhex(?)", uid) err := scanSelectSingle(r, row) if err != nil { return nil, err } return r, nil }
func tableExists(tx *sql.Tx, schema, table string) (bool, error) { var exists bool sql := fmt.Sprintf(`SELECT EXISTS(SELECT * FROM information_schema.tables WHERE table_name='%s' AND table_schema='%s')`, table, schema) row := tx.QueryRow(sql) err := row.Scan(&exists) if err != nil { return false, err } return exists, nil }
func GetOneByUserUIDAndGroup(tx *sql.Tx, uid string, group string) (*model.Group, error) { r := &model.Group{} row := tx.QueryRow(selectQuery+"WHERE userUID = unhex(?) AND name = ?", uid, group) err := scanSelectSingle(r, row) if err != nil { return nil, err } return r, nil }
func (SQLServerHelper) tableHasIdentityColumn(tx *sql.Tx, tableName string) bool { sql := ` SELECT COUNT(*) FROM SYS.IDENTITY_COLUMNS WHERE OBJECT_NAME(OBJECT_ID) = ? ` var count int tx.QueryRow(sql, tableName).Scan(&count) return count > 0 }