func (s *Server) CreateStudent(w http.ResponseWriter, r *http.Request) { // Unmarshal json into Student. student := Student{} err := json.NewDecoder(r.Body).Decode(&student) if err != nil { // Malformed json. w.WriteHeader(http.StatusBadRequest) log.Error(err) return } log.Infof("%+v", student) // Insert into db. err = s.Collection().Insert(student) if err != nil { // Check for duplicates. if mgo.IsDup(err) { w.WriteHeader(http.StatusConflict) } else { // Something went wrong. w.WriteHeader(http.StatusInternalServerError) log.Error(err) } return } w.WriteHeader(http.StatusCreated) }
func AddHost(h *Host) error { conn, err := db.Conn() if err != nil { return err } defer conn.Close() err = conn.InstallHosts().Insert(h) if mgo.IsDup(err) { return &ErrHostAlreadyExists{Name: h.Name} } return err }
func (a *Article) Create() error { if a == nil { return apierror.NewServerError("article not instanced") } if a.Slug == "" { a.Slug = slug.Make(a.Title) } if bson.IsObjectIdHex(a.Slug) { return apierror.NewBadRequest("slug cannot be a ObjectId") } a.CreatedAt = time.Now() // To prevent duplicates on the slug, we'll retry the insert() up to 10 times originalSlug := a.Slug var err error for i := 0; i < 10; i++ { a.ID = bson.NewObjectId() err = Query().Insert(a) if err != nil { // In case of duplicate we'll add "-X" at the end of the slug, where X is // a number a.Slug = fmt.Sprintf("%s-%d", originalSlug, i) if mgo.IsDup(err) == false { return apierror.NewServerError(err.Error()) } } else { // everything went well return nil } } // after 10 try we just return an error return apierror.NewConflict(err.Error()) }
func TestDocumentManager_Register_IndexAnnotation(t *testing.T) { type Country struct { ID bson.ObjectId `bson:"_id"` Name string `bson:"Name" odm:"index(unique:true)"` } dm, done := getDocumentManager(t) defer done() err := dm.Register("Country", new(Country)) test.Fatal(t, err, nil) country := &Country{Name: "Sweden"} dm.Persist(country) err = dm.Flush() test.Fatal(t, err, nil) country2 := new(Country) err = dm.FindID(country.ID, country2) test.Fatal(t, err, nil) test.Fatal(t, country2.Name, country.Name) country3 := &Country{Name: "Sweden"} dm.Persist(country3) err = dm.Flush() test.Fatal(t, mgo.IsDup(err), true, "Error should be a duplicate key error ") }
func main() { session, err := mgo.DialWithTimeout("db", time.Minute) if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior session.SetMode(mgo.Monotonic, true) // Retrieve lines from STIF website. c := session.DB("dispotrains").C("stations") lines, err := client.GetAllLines() if err != nil { panic(err) } // Build the station database collection. stations := make(map[string]*storage.Station) for _, line := range lines { for _, station := range line.GetStations() { if _, ok := stations[strings.ToLower(station.Name)]; ok == true { for _, sLine := range station.Lines { stations[strings.ToLower(station.Name)].AttachLine(sLine) } } else { stations[strings.ToLower(station.Name)] = station } } } AddPositionToStations(stations) stationIndex := mgo.Index{ Key: []string{"name"}, Background: true, DropDups: true, Unique: true, } err = c.EnsureIndex(stationIndex) if err != nil { panic(err) } for _, station := range stations { _, err = c.Upsert(bson.M{"name": station.Name}, &station) if err != nil { panic(err) } } // Build the lines database collection. job := &mgo.MapReduce{ Map: mapStationsToLines, Reduce: reduceLines, Out: bson.M{"replace": "lines"}, } _, err = c.Find(bson.M{}).MapReduce(job, nil) if err != nil { panic(err) } // Append the new statuses to the database log. c = session.DB("dispotrains").C("statuses") index := mgo.Index{ Key: []string{"state", "lastupdate", "elevator"}, Background: true, DropDups: true, Sparse: true, Unique: true, } err = c.EnsureIndex(index) if err != nil { panic(err) } for _, station := range stations { for _, elevator := range station.GetElevators() { bsonStatus := bson.M{ "state": elevator.Status.State, "lastupdate": elevator.Status.LastUpdate, "elevator": elevator.ID, } err = c.Insert(bsonStatus) if err != nil && !mgo.IsDup(err) { panic(err) } } } }