Ejemplo n.º 1
0
func getAddedItemIds() (string, int) {
	session, err := mgo.Dial("mongodb://localhost/kawamura")
	checkErr(err)

	defer session.Close()

	db := session.DB("kawamura")
	col := db.C("items")
	rows := col.Find(bson.M{}).Iter()
	count, err := col.Find(bson.M{}).Count()
	checkErr(err)

	bytes := make([]byte, 0, count*11)
	index := 0

	response := Response{}
	for rows.Next(&response) {
		if index != 0 {
			bytes = append(bytes, ","...)
		}
		bytes = append(bytes, strconv.Itoa(response.ItemId)...)
		index++
	}
	return string(bytes), count
}
Ejemplo n.º 2
0
func NewMongoDriver(ctx *cli.Context) (db.Driver, error) {
	var url string
	if ctx.Bool(mongoAuthFlag) {
		url = fmt.Sprintf("mongodb://%s:%s@%s/%s", ctx.String(mongoUserFlag), ctx.String(mongoPasswordFlag), ctx.String(mongoURLFlag), ctx.String(mongoDBFlag))
	} else {
		url = fmt.Sprintf("mongodb://%s/%s", ctx.String(mongoURLFlag), ctx.String(mongoDBFlag))
	}
	s, err := mgo.Dial(url)

	if err != nil {
		return nil, err
	}

	log.Info("mongodb.go: connected to mongodb")

	md := &MongoDBDriver{
		Session: s,
	}
	md.tokenRepo = newMongoDBTokenRepo(md)
	md.tarballRepo = newTarballRepo(md)
	md.gameRepo = newGameRepo(md)
	md.gameReleaseRepo = newGameReleaseRepo(md)

	return md, nil
}
func main() {
	session, _ := mgo.Dial("mongodb://localhost/test1")
	defer session.Close()
	db := session.DB("test")

	/**
	 * つくるところ
	**/
	ritsu := &Person{
		Name: "田井中律",
		Age:  17,
	}
	col := db.C("people")
	col.Insert(ritsu)

	r := &Person{
		Name: "田井中律",
		Age:  17,
	}
	cola := db.C("people")
	cola.Insert(r)

	/**
	 * みつけるところ
	**/
	p := new(Person)
	query := db.C("people").Find(bson.M{})
	query.One(&p)

	/**
	 * 結果
	**/
	fmt.Printf("%+v\n", p)
	// &{ID:ObjectIdHex("5478517a9871b9b8e42e2ee2") Name:田井中律 Age:17}
}
Ejemplo n.º 4
0
func AppInit() {
	var err error
	// Read configuration.
	Dial = revel.Config.StringDefault("revmgo.dial", "localhost")
	Method = revel.Config.StringDefault("revmgo.method", "clone")
	if err = MethodError(Method); err != nil {
		revel.ERROR.Panic(err)
	}

	// Let's try to connect to Mongo DB right upon starting revel but don't
	// raise an error. Errors will be handled if there is actually a request
	if Session == nil {
		Session, err = mgo.Dial(Dial)
		if err != nil {
			// Only warn since we'll retry later for each request
			revel.WARN.Printf("Could not connect to Mongo DB. Error: %s", err)
		} else {
			setDuplMethod()
		}
	}

	// register the custom bson.ObjectId binder
	objId := bson.NewObjectId()
	revel.TypeBinders[reflect.TypeOf(objId)] = ObjectIdBinder
}
Ejemplo n.º 5
0
/**
 * Perform two passes over a Freebase file; the first pass identifies all entities
 * that are labeled as countries. The second pass finds and stores relevant fields
 * for the entities that were labeled in the first pass.
 */
func main() {
	flag.Parse()

	countries, names := RunFirstStage(*FreebasePath)
	countries = RunSecondStage(*FreebasePath, countries, names)

	// Store data for valid countries.
	log.Println("Storing in database...")
	session, err := mgo.Dial("172.30.0.101")
	if err != nil {
		log.Println("Couldn't connect to MongoDB: " + err.Error())
		return
	}
	defer session.Close()

	collection := session.DB("newsflash").C("country_tags")

	for _, country := range countries {
		if len(country.CountryCode) > 0 {
			collection.Insert(country)
			log.Println(fmt.Sprintf("Valid: %+v", country))
		} else {
			log.Println(fmt.Sprintf("Invalid: %+v", country))
		}
	}
}
Ejemplo n.º 6
0
func TestMongo(t *testing.T) {

	type Test struct {
		ID bson.ObjectId `bson:"_id,omitempty"`
		Name,
		Description string
	}

	session, err := mgo.Dial(os.Getenv("MONGODB_TEST_SERVER"))
	test.Fatal(t, err, nil)
	defer session.Close()
	defer session.DB(os.Getenv("MONGODB_TEST_DB")).C("mongo_tests").DropCollection()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	collection := session.DB(os.Getenv("MONGODB_TEST_DB")).C("mongo_tests")
	test1 := &Test{Name: "Initial", Description: "A simple test"}
	err = collection.Insert(test1)
	test.Fatal(t, err, nil)
	result := new(Test)
	err = collection.Find(bson.M{"name": test1.Name}).One(result)
	test.Error(t, err, nil)
	test.Error(t, result.Description, test1.Description)
	result1 := new(Test)
	err = collection.FindId(result.ID).One(result1)
	test.Error(t, err, nil)
	test.Error(t, result1.ID, result.ID)
}
Ejemplo n.º 7
0
func main() {
	session, err := mgo.Dial("192.168.225.225")

	if err != nil {
		panic(err)
	}
	fmt.Println("Connected to mongo")
	c := session.DB("test").C("TestCollection")

	c.Upsert(bson.M{"_id": "1"}, &TestData{
		Id:   "1",
		Data: "test",
	})
	defer session.Close()

	for {
		s := session.Clone()
		c := s.DB("test").C("TestCollection")

		result := &TestData{}
		err := c.Find(bson.M{"_id": "1"}).One(result)

		if err != nil {
			fmt.Printf("Got error: %+v\n", err)
		} else {
			fmt.Printf("Got result: %+v\n", *result)
		}

		time.Sleep(5 * time.Second)
		s.Close()
	}
}
Ejemplo n.º 8
0
// 新建数据库连接
func (*MgoSrc) New() pool.Src {
	session, err := mgo.Dial(config.MGO_OUTPUT.Host)
	if err != nil {
		logs.Log.Error("%v", err)
	}
	return &MgoSrc{Session: session}
}
Ejemplo n.º 9
0
func main() {
	flag.Parse()

	// Connect to mongodb.
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	s := &Server{session}
	log.Info("Opened Mongo Session\n")

	// Set SafeMode so write errors are checked.
	session.SetSafe(&mgo.Safe{})

	// Create routes.
	r := mux.NewRouter()
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok\n")) })
	r.HandleFunc("/Student", s.CreateStudent).Methods("POST")
	r.HandleFunc("/Student/getstudent", s.ReadStudent).Methods("GET")
	r.HandleFunc("/Student", s.UpdateStudents).Methods("UPDATE")
	r.HandleFunc("/Student", s.DeleteStudents).Methods("DELETE")
	r.HandleFunc("/Student/listall", s.ListStudents).Methods("GET")
	// Start the server.
	http.ListenAndServe(":1234", r)
}
Ejemplo n.º 10
0
func main() {
	session, err := mgo.Dial("db")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior
	// session.SetMode(mgo.Monotonic, true)

	c := session.DB("dispotrains").C("statuses")
	index := mgo.Index{
		Key:        []string{"state", "lastupdate", "elevator"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}
	err = c.EnsureIndex(index)
	if err != nil {
		panic(err)
	}

	_, err = c.RemoveAll(bson.M{"elevator": nil})
	if err != nil {
		panic(err)
	}
}
Ejemplo n.º 11
0
Archivo: db.go Proyecto: Gurrt/go-IoTDM
func GetDatabaseConnection(url string) (*DatabaseHandle, error) {
	session, err := mgo.Dial(url)
	if err != nil {
		return nil, err
	}
	return &DatabaseHandle{session: session}, nil
}
Ejemplo n.º 12
0
func Init() {
	MONGOSERVER := os.Getenv("MONGO_URL")
	MONGODB := os.Getenv("MONGODB")
	if MONGOSERVER == "" {
		log.Println("No mongo server address set, resulting to default address")
		MONGOSERVER = "127.0.0.1:27017"
		MONGODB = "calabarpages"
		//MONGODB = "yellowListings"
		//MONGODB = "y"
		//mongodb://localhost
	}

	session, err := mgo.Dial(MONGOSERVER)
	if err != nil {
		log.Println(err)
	}

	config = Conf{
		MongoDB:     MONGODB,
		MongoServer: MONGOSERVER,
		Database:    session.DB(MONGODB),
	}

	log.Printf("mongoserver %s", MONGOSERVER)
}
Ejemplo n.º 13
0
func MInit(uri, dbName, k string) error {
	DB_NAME = dbName
	n := time.Second
	var e error
	var m_conn *mgo.Session = mcMap[k]
	for {
		if session, err := mgo.Dial(uri); err != nil {
			e = err
		} else {
			m_conn = session
			if err := m_conn.Ping(); err != nil {
				e = err
			} else {
				break
			}
		}

		fmt.Printf("fail to connect mysql,err:%v,uri:%s,try to reconnect in %d second\n", e, uri, n/1000000000)
		time.Sleep(n)
		n = n * 2
		//最大重连间隔时长:10分钟
		if n > 600*time.Second {
			n = 600 * time.Second
		}
	}
	mcMap[k] = m_conn
	return nil
}
Ejemplo n.º 14
0
func newServer(config Config) *server {
	var err error
	db, err := mgo.Dial(config.DB.Host + ":" + config.DB.Port)
	if err != nil {
		log.Fatal("ERROR connecting to DB:", err)
	}

	queryResult := User{}
	c := db.DB("test").C("users")
	err = c.Find(bson.M{}).One(&queryResult)
	if err != nil {
		defaultUser := User{
			Username: config.DefaultUser.Username,
			Email:    "*****@*****.**",
			Role:     "admin",
		}
		h := sha256.New()
		h.Write([]byte(config.DefaultUser.Password))
		defaultUser.Password = hex.EncodeToString(h.Sum(nil))
		err = c.Insert(defaultUser)
		if err != nil {
			log.Fatal("Error adding default user:", err)
		}
	}

	return &server{
		config: config,
		db:     db,
		auth:   jwtauth.NewAuthHandler(config.Local.PrivateKey, config.Local.PublicKey),
	}
}
Ejemplo n.º 15
0
func initCnf() error {
	flag.Parse()
	cnf = NewConfig()

	err := cnf.Read(configFile)
	if err != nil {
		logger.Fatalf("Error reading config file %s: %s", configFile, err)
		return err
	}

	file, err := os.OpenFile(cnf.Log.File, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		logger.Fatalf("Error opening log file %s: %s", cnf.Log.File, err)
		return err
	}
	logger = log.New(file, "", log.Lshortfile|log.Ldate|log.Ltime|log.Lmicroseconds)

	DBSes, err := mgo.Dial(cnf.MongoDB.Adr())
	if err != nil {
		logger.Fatalf("Error dialing DB %v: %s", cnf.MongoDB, err)
		return err
	}

	DB := DBSes.DB(cnf.MongoDB.Database)
	Kitas = DB.C(cnf.MongoDB.Collection)

	logger.Printf("Initialisation finished.")
	logger.Printf("Config: %#v", cnf)

	return nil
}
Ejemplo n.º 16
0
func main() {
	session, _ := mgo.Dial("mongodb://localhost/test")
	defer session.Close()
	db := session.DB("test")

	me := &Admin{
		Person: Person{
			ID:   bson.NewObjectId(),
			Name: "Jhon Donner",
			Age:  17,
		},
		Password:    "******",
		Permissions: []string{"read", "write"},
	}
	col := db.C("people")
	err := col.Insert(me)
	if err != nil {
		log.Fatalf("%v\n", err)
	}

	query := db.C("people").Find(bson.M{})
	p := new(Person)
	query.One(&p)
	a := new(Admin)
	query.One(&a)

	fmt.Printf("%+v\n", p)
	fmt.Printf("%+v\n", a)
}
Ejemplo n.º 17
0
func createSessionOrDie() *mgo.Session {
	session, err := mgo.Dial(mongoDbHost)
	if err != nil {
		panic(err)
	}
	return session
}
Ejemplo n.º 18
0
func main() {
	var urls = flag.String("nats", nats.DefaultURL, "The nats server URLs (separated by comma)")
	var mgoDB = flag.String("db", "localhost:27017", "Mongo databast URL")
	var showTime = flag.Bool("t", false, "Display timestamps")

	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()

	args := flag.Args()
	if len(args) < 1 {
		usage()
		fmt.Println("mgoDB", mgoDB)
	}

	opts := nats.DefaultOptions
	opts.Servers = strings.Split(*urls, ",")
	for i, s := range opts.Servers {
		opts.Servers[i] = strings.Trim(s, " ")
	}

	nc, err := opts.Connect()
	if err != nil {
		log.Fatalf("Can't connect: %v\n", err)
	}

	subj, i := args[0], 0

	nc.Subscribe(subj, func(msg *nats.Msg) {
		// ok we need to write this to a mgo database and assume that it's mostly valid ;)
		// we will use the last part of the subj as the collection and the first part as the db.
		// First we convert the Msg into a json obj.
		// then we dump the json into Bson and into mongo.

		var jsonObj map[string]interface{}

		err := json.Unmarshal([]byte(msg.Data), &jsonObj)
		if err != nil {
			// Bad json.
			log.Fatalf("Bad json passed: (%s)\n", msg.Data)
		}

		// ok let's split the msg subject and use part 1 for db and part 2 for collection. throwing away the rest
		foo := strings.Split(subj, ".")

		// Create mgo session
		session, err := mgo.Dial(*mgoDB)
		c := session.Copy().DB(foo[0]).C(foo[1]) // Add the mongo db stuff
		c.Insert(jsonObj)

		printMsg(msg, i)
	})

	log.Printf("Listening on [%s]\n", subj)
	if *showTime {
		log.SetFlags(log.LstdFlags)
	}

	runtime.Goexit()
}
Ejemplo n.º 19
0
func NewMongoSession(host string) (*mgo.Session, error) {
	session, err := mgo.Dial(host)
	if err != nil {
		return nil, err
	}

	return session, nil
}
Ejemplo n.º 20
0
func DBSession() *mgo.Session {
	session, err := mgo.Dial("localhost")
	if err != nil {
		// log error
		panic(err)
	}
	return session
}
Ejemplo n.º 21
0
Archivo: pool.go Proyecto: Cdim/pholcus
// 新建数据库连接
func (*MgoSrc) New() pool.Src {
	session, err := mgo.Dial(config.MGO.CONN_STR)
	if err != nil {
		logs.Log.Error("MongoDB: %v", err)
		return nil
	}
	return &MgoSrc{Session: session}
}
Ejemplo n.º 22
0
func main() {
	config := loadConfig()
	config.print()

	var err error
	fmt.Println(config.SecretKey)
	secretKey, err = hex.DecodeString(config.SecretKey)
	fmt.Println(secretKey)

	specialBranch = config.SpecialBranch
	specialRef = "refs/heads/" + config.SpecialBranch

	dbSession, err = mgo.Dial(config.MongoURL)
	if err != nil {
		panic(err)
	}
	defer dbSession.Close()

	users = dbSession.DB("hugo-pages").C("users")
	repos = dbSession.DB("hugo-pages").C("repos")

	handlers = make(map[int]*comm)
	handlersMtx = &sync.RWMutex{}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		payload, err := validate(r)
		if len(err) > 0 {
			log.Println(err)
			http.Error(w, err, http.StatusBadRequest)
			return
		}

		if payload == nil {
			return
		}

		fullname := *payload.Repo.FullName
		id := *payload.Repo.ID
		url := *payload.Repo.URL

		go func() {
			log.Printf("Got: %s", fullname)
			workerComm := synchronize(id)
			w := newWorker(id, url, workerComm)
			w.work()
			change := bson.M{
				"$set": bson.M{
					"lastbuildoutput": w.log,
					"lastbuildstatus": w.status,
				},
			}
			repos.UpdateId(id, change)
		}()
	})

	log.Println("Listening")
	log.Fatal(http.ListenAndServe(config.Address, nil))
}
Ejemplo n.º 23
0
func (application *Application) ConnectToDatabase() {
	var err error
	application.DBSession, err = mgo.Dial(application.Configuration.Database.Hosts)

	if err != nil {
		glog.Fatalf("Can't connect to the database: %v", err)
		panic(err)
	}
}
Ejemplo n.º 24
0
func (driver *MngMongoDBDriver) Init(host, port string) (int, error) {
	hostinfo := "mongodb://" + host + ":" + port + "/mng"
	session, err := mgo.Dial(hostinfo)
	if err != nil {
		return -1, err
	}
	driver.session = session
	return 0, nil
}
Ejemplo n.º 25
0
Archivo: db.go Proyecto: saml/jscan
func dbConnect(url string) *mgo.Session {
	log.Printf("Connecting to mongo @ %s", url)
	session, err := mgo.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	session.SetMode(mgo.Eventual, true)
	return session
}
Ejemplo n.º 26
0
func getDB(t *testing.T) *mgo.Database {
	session, err := mgo.Dial(os.Getenv("MONGODB_TEST_SERVER"))
	test.Fatal(t, err, nil)
	if verbose == true {
		mgo.SetLogger(MongoLogger{t})
		mgo.SetDebug(true)
	}
	return session.DB(os.Getenv("MONGODB_TEST_DB"))
}
Ejemplo n.º 27
0
func (context *Context) connect() {
	var err error
	context.session, err = mgo.Dial(context.host)
	if err != nil {
		panic(err)
	}
	context.session.SetMode(mgo.Monotonic, true)
	context.db = context.session.DB(context.dbName)
}
Ejemplo n.º 28
0
func Refresh() {
	session, err = mgo.Dial(CONN_STR)
	if err != nil {
		log.Printf("MongoDB:%v\n", err)
	} else if err = session.Ping(); err != nil {
		log.Printf("MongoDB:%v\n", err)
	} else {
		session.SetPoolLimit(MAX_CONN)
	}
}
Ejemplo n.º 29
0
func Refresh() {
	session, err = mgo.Dial(config.MGO_CONN_STR)
	if err != nil {
		logs.Log.Error("MongoDB:%v\n", err)
	} else if err = session.Ping(); err != nil {
		logs.Log.Error("MongoDB:%v\n", err)
	} else {
		session.SetPoolLimit(config.MGO_CONN_CAP)
	}
}
Ejemplo n.º 30
0
// NewIns make a new instance
func NewIns(host, db, user, pass string, port uint16) {
	var err error
	mg := &MongoInfo{}
	createMongoURL(host, db, user, pass, port)

	mg.Session, err = mgo.Dial(mongoURL)
	if err != nil {
		panic(err)
	}
}