How to use Read method of mgo Package

Best Keploy code snippet using mgo.Read

settings_test.go

Source:settings_test.go Github

copy

Full Screen

...63 c.Assert(err, gc.IsNil)64 _, err = createSettings(s.state, s.key, nil)65 c.Assert(err, gc.ErrorMatches, "cannot overwrite existing settings")66}67func (s *SettingsSuite) TestCannotReadMissing(c *gc.C) {68 _, err := readSettings(s.state, s.key)69 c.Assert(err, gc.ErrorMatches, "settings not found")70 c.Assert(err, jc.Satisfies, errors.IsNotFoundError)71}72func (s *SettingsSuite) TestCannotWriteMissing(c *gc.C) {73 node, err := createSettings(s.state, s.key, nil)74 c.Assert(err, gc.IsNil)75 err = removeSettings(s.state, s.key)76 c.Assert(err, gc.IsNil)77 node.Set("foo", "bar")78 _, err = node.Write()79 c.Assert(err, gc.ErrorMatches, "settings not found")80 c.Assert(err, jc.Satisfies, errors.IsNotFoundError)81}82func (s *SettingsSuite) TestUpdateWithWrite(c *gc.C) {83 node, err := createSettings(s.state, s.key, nil)84 c.Assert(err, gc.IsNil)85 options := map[string]interface{}{"alpha": "beta", "one": 1}86 node.Update(options)87 changes, err := node.Write()88 c.Assert(err, gc.IsNil)89 c.Assert(changes, gc.DeepEquals, []ItemChange{90 {ItemAdded, "alpha", nil, "beta"},91 {ItemAdded, "one", nil, 1},92 })93 // Check local state.94 c.Assert(node.Map(), gc.DeepEquals, options)95 // Check MongoDB state.96 mgoData := make(map[string]interface{}, 0)97 err = s.MgoSuite.Session.DB("juju").C("settings").FindId(s.key).One(&mgoData)98 c.Assert(err, gc.IsNil)99 cleanSettingsMap(mgoData)100 c.Assert(mgoData, gc.DeepEquals, options)101}102func (s *SettingsSuite) TestConflictOnSet(c *gc.C) {103 // Check version conflict errors.104 nodeOne, err := createSettings(s.state, s.key, nil)105 c.Assert(err, gc.IsNil)106 nodeTwo, err := readSettings(s.state, s.key)107 c.Assert(err, gc.IsNil)108 optionsOld := map[string]interface{}{"alpha": "beta", "one": 1}109 nodeOne.Update(optionsOld)110 nodeOne.Write()111 nodeTwo.Update(optionsOld)112 changes, err := nodeTwo.Write()113 c.Assert(err, gc.IsNil)114 c.Assert(changes, gc.DeepEquals, []ItemChange{115 {ItemAdded, "alpha", nil, "beta"},116 {ItemAdded, "one", nil, 1},117 })118 // First test node one.119 c.Assert(nodeOne.Map(), gc.DeepEquals, optionsOld)120 // Write on node one.121 optionsNew := map[string]interface{}{"alpha": "gamma", "one": "two"}122 nodeOne.Update(optionsNew)123 changes, err = nodeOne.Write()124 c.Assert(err, gc.IsNil)125 c.Assert(changes, gc.DeepEquals, []ItemChange{126 {ItemModified, "alpha", "beta", "gamma"},127 {ItemModified, "one", 1, "two"},128 })129 // Verify that node one reports as expected.130 c.Assert(nodeOne.Map(), gc.DeepEquals, optionsNew)131 // Verify that node two has still the old data.132 c.Assert(nodeTwo.Map(), gc.DeepEquals, optionsOld)133 // Now issue a Set/Write from node two. This will134 // merge the data deleting 'one' and updating135 // other values.136 optionsMerge := map[string]interface{}{"alpha": "cappa", "new": "next"}137 nodeTwo.Update(optionsMerge)138 nodeTwo.Delete("one")139 expected := map[string]interface{}{"alpha": "cappa", "new": "next"}140 changes, err = nodeTwo.Write()141 c.Assert(err, gc.IsNil)142 c.Assert(changes, gc.DeepEquals, []ItemChange{143 {ItemModified, "alpha", "beta", "cappa"},144 {ItemAdded, "new", nil, "next"},145 {ItemDeleted, "one", 1, nil},146 })147 c.Assert(expected, gc.DeepEquals, nodeTwo.Map())148 // But node one still reflects the former data.149 c.Assert(nodeOne.Map(), gc.DeepEquals, optionsNew)150}151func (s *SettingsSuite) TestSetItem(c *gc.C) {152 // Check that Set works as expected.153 node, err := createSettings(s.state, s.key, nil)154 c.Assert(err, gc.IsNil)155 options := map[string]interface{}{"alpha": "beta", "one": 1}156 node.Set("alpha", "beta")157 node.Set("one", 1)158 changes, err := node.Write()159 c.Assert(err, gc.IsNil)160 c.Assert(changes, gc.DeepEquals, []ItemChange{161 {ItemAdded, "alpha", nil, "beta"},162 {ItemAdded, "one", nil, 1},163 })164 // Check local state.165 c.Assert(node.Map(), gc.DeepEquals, options)166 // Check MongoDB state.167 mgoData := make(map[string]interface{}, 0)168 err = s.MgoSuite.Session.DB("juju").C("settings").FindId(s.key).One(&mgoData)169 c.Assert(err, gc.IsNil)170 cleanSettingsMap(mgoData)171 c.Assert(mgoData, gc.DeepEquals, options)172}173func (s *SettingsSuite) TestSetItemEscape(c *gc.C) {174 // Check that Set works as expected.175 node, err := createSettings(s.state, s.key, nil)176 c.Assert(err, gc.IsNil)177 options := map[string]interface{}{"$bar": 1, "foo.alpha": "beta"}178 node.Set("foo.alpha", "beta")179 node.Set("$bar", 1)180 changes, err := node.Write()181 c.Assert(err, gc.IsNil)182 c.Assert(changes, gc.DeepEquals, []ItemChange{183 {ItemAdded, "$bar", nil, 1},184 {ItemAdded, "foo.alpha", nil, "beta"},185 })186 // Check local state.187 c.Assert(node.Map(), gc.DeepEquals, options)188 // Check MongoDB state.189 mgoOptions := map[string]interface{}{"\uff04bar": 1, "foo\uff0ealpha": "beta"}190 mgoData := make(map[string]interface{}, 0)191 err = s.MgoSuite.Session.DB("juju").C("settings").FindId(s.key).One(&mgoData)192 c.Assert(err, gc.IsNil)193 cleanMgoSettings(mgoData)194 c.Assert(mgoData, gc.DeepEquals, mgoOptions)195 // Now get another state by reading from the database instance and196 // check read state has replaced '.' and '$' after fetching from197 // MongoDB.198 nodeTwo, err := readSettings(s.state, s.key)199 c.Assert(err, gc.IsNil)200 c.Assert(nodeTwo.disk, gc.DeepEquals, options)201 c.Assert(nodeTwo.core, gc.DeepEquals, options)202}203func (s *SettingsSuite) TestReplaceSettingsEscape(c *gc.C) {204 // Check that replaceSettings works as expected.205 node, err := createSettings(s.state, s.key, nil)206 c.Assert(err, gc.IsNil)207 node.Set("foo.alpha", "beta")208 node.Set("$bar", 1)209 _, err = node.Write()210 c.Assert(err, gc.IsNil)211 options := map[string]interface{}{"$baz": 1, "foo.bar": "beta"}212 rop, settingsChanged, err := replaceSettingsOp(s.state, s.key, options)213 c.Assert(err, gc.IsNil)214 ops := []txn.Op{rop}215 err = node.st.runTransaction(ops)216 c.Assert(err, gc.IsNil)217 changed, err := settingsChanged()218 c.Assert(err, gc.IsNil)219 c.Assert(changed, gc.Equals, true)220 // Check MongoDB state.221 mgoOptions := map[string]interface{}{"\uff04baz": 1, "foo\uff0ebar": "beta"}222 mgoData := make(map[string]interface{}, 0)223 err = s.MgoSuite.Session.DB("juju").C("settings").FindId(s.key).One(&mgoData)224 c.Assert(err, gc.IsNil)225 cleanMgoSettings(mgoData)226 c.Assert(mgoData, gc.DeepEquals, mgoOptions)227}228func (s *SettingsSuite) TestCreateSettingsEscape(c *gc.C) {229 // Check that createSettings works as expected.230 options := map[string]interface{}{"$baz": 1, "foo.bar": "beta"}231 node, err := createSettings(s.state, s.key, options)232 c.Assert(err, gc.IsNil)233 // Check local state.234 c.Assert(node.Map(), gc.DeepEquals, options)235 // Check MongoDB state.236 mgoOptions := map[string]interface{}{"\uff04baz": 1, "foo\uff0ebar": "beta"}237 mgoData := make(map[string]interface{}, 0)238 err = s.MgoSuite.Session.DB("juju").C("settings").FindId(s.key).One(&mgoData)239 c.Assert(err, gc.IsNil)240 cleanMgoSettings(mgoData)241 c.Assert(mgoData, gc.DeepEquals, mgoOptions)242}243func (s *SettingsSuite) TestMultipleReads(c *gc.C) {244 // Check that reads without writes always resets the data.245 nodeOne, err := createSettings(s.state, s.key, nil)246 c.Assert(err, gc.IsNil)247 nodeOne.Update(map[string]interface{}{"alpha": "beta", "foo": "bar"})248 value, ok := nodeOne.Get("alpha")249 c.Assert(ok, gc.Equals, true)250 c.Assert(value, gc.Equals, "beta")251 value, ok = nodeOne.Get("foo")252 c.Assert(ok, gc.Equals, true)253 c.Assert(value, gc.Equals, "bar")254 value, ok = nodeOne.Get("baz")255 c.Assert(ok, gc.Equals, false)256 // A read resets the data to the empty state.257 err = nodeOne.Read()258 c.Assert(err, gc.IsNil)259 c.Assert(nodeOne.Map(), gc.DeepEquals, map[string]interface{}{})260 nodeOne.Update(map[string]interface{}{"alpha": "beta", "foo": "bar"})261 changes, err := nodeOne.Write()262 c.Assert(err, gc.IsNil)263 c.Assert(changes, gc.DeepEquals, []ItemChange{264 {ItemAdded, "alpha", nil, "beta"},265 {ItemAdded, "foo", nil, "bar"},266 })267 // A write retains the newly set values.268 value, ok = nodeOne.Get("alpha")269 c.Assert(ok, gc.Equals, true)270 c.Assert(value, gc.Equals, "beta")271 value, ok = nodeOne.Get("foo")272 c.Assert(ok, gc.Equals, true)273 c.Assert(value, gc.Equals, "bar")274 // Now get another state instance and change underlying state.275 nodeTwo, err := readSettings(s.state, s.key)276 c.Assert(err, gc.IsNil)277 nodeTwo.Update(map[string]interface{}{"foo": "different"})278 changes, err = nodeTwo.Write()279 c.Assert(err, gc.IsNil)280 c.Assert(changes, gc.DeepEquals, []ItemChange{281 {ItemModified, "foo", "bar", "different"},282 })283 // This should pull in the new state into node one.284 err = nodeOne.Read()285 c.Assert(err, gc.IsNil)286 value, ok = nodeOne.Get("alpha")287 c.Assert(ok, gc.Equals, true)288 c.Assert(value, gc.Equals, "beta")289 value, ok = nodeOne.Get("foo")290 c.Assert(ok, gc.Equals, true)291 c.Assert(value, gc.Equals, "different")292}293func (s *SettingsSuite) TestDeleteEmptiesState(c *gc.C) {294 node, err := createSettings(s.state, s.key, nil)295 c.Assert(err, gc.IsNil)296 node.Set("a", "foo")297 changes, err := node.Write()298 c.Assert(err, gc.IsNil)299 c.Assert(changes, gc.DeepEquals, []ItemChange{300 {ItemAdded, "a", nil, "foo"},301 })302 node.Delete("a")303 changes, err = node.Write()304 c.Assert(err, gc.IsNil)305 c.Assert(changes, gc.DeepEquals, []ItemChange{306 {ItemDeleted, "a", "foo", nil},307 })308 c.Assert(node.Map(), gc.DeepEquals, map[string]interface{}{})309}310func (s *SettingsSuite) TestReadResync(c *gc.C) {311 // Check that read pulls the data into the node.312 nodeOne, err := createSettings(s.state, s.key, nil)313 c.Assert(err, gc.IsNil)314 nodeOne.Set("a", "foo")315 changes, err := nodeOne.Write()316 c.Assert(err, gc.IsNil)317 c.Assert(changes, gc.DeepEquals, []ItemChange{318 {ItemAdded, "a", nil, "foo"},319 })320 nodeTwo, err := readSettings(s.state, s.key)321 c.Assert(err, gc.IsNil)322 nodeTwo.Delete("a")323 changes, err = nodeTwo.Write()324 c.Assert(err, gc.IsNil)325 c.Assert(changes, gc.DeepEquals, []ItemChange{326 {ItemDeleted, "a", "foo", nil},327 })328 nodeTwo.Set("a", "bar")329 changes, err = nodeTwo.Write()330 c.Assert(err, gc.IsNil)331 c.Assert(changes, gc.DeepEquals, []ItemChange{332 {ItemAdded, "a", nil, "bar"},333 })334 // Read of node one should pick up the new value.335 err = nodeOne.Read()336 c.Assert(err, gc.IsNil)337 value, ok := nodeOne.Get("a")338 c.Assert(ok, gc.Equals, true)339 c.Assert(value, gc.Equals, "bar")340}341func (s *SettingsSuite) TestMultipleWrites(c *gc.C) {342 // Check that multiple writes only do the right changes.343 node, err := createSettings(s.state, s.key, nil)344 c.Assert(err, gc.IsNil)345 node.Update(map[string]interface{}{"foo": "bar", "this": "that"})346 changes, err := node.Write()347 c.Assert(err, gc.IsNil)348 c.Assert(changes, gc.DeepEquals, []ItemChange{349 {ItemAdded, "foo", nil, "bar"},350 {ItemAdded, "this", nil, "that"},351 })352 node.Delete("this")353 node.Set("another", "value")354 changes, err = node.Write()355 c.Assert(err, gc.IsNil)356 c.Assert(changes, gc.DeepEquals, []ItemChange{357 {ItemAdded, "another", nil, "value"},358 {ItemDeleted, "this", "that", nil},359 })360 expected := map[string]interface{}{"foo": "bar", "another": "value"}361 c.Assert(expected, gc.DeepEquals, node.Map())362 changes, err = node.Write()363 c.Assert(err, gc.IsNil)364 c.Assert(changes, gc.DeepEquals, []ItemChange{})365 err = node.Read()366 c.Assert(err, gc.IsNil)367 c.Assert(expected, gc.DeepEquals, node.Map())368 changes, err = node.Write()369 c.Assert(err, gc.IsNil)370 c.Assert(changes, gc.DeepEquals, []ItemChange{})371}372func (s *SettingsSuite) TestMultipleWritesAreStable(c *gc.C) {373 node, err := createSettings(s.state, s.key, nil)374 c.Assert(err, gc.IsNil)375 node.Update(map[string]interface{}{"foo": "bar", "this": "that"})376 _, err = node.Write()377 c.Assert(err, gc.IsNil)378 mgoData := make(map[string]interface{})379 err = s.MgoSuite.Session.DB("juju").C("settings").FindId(s.key).One(&mgoData)380 c.Assert(err, gc.IsNil)381 version := mgoData["version"]382 for i := 0; i < 100; i++ {383 node.Set("value", i)384 node.Set("foo", "bar")385 node.Delete("value")386 node.Set("this", "that")387 _, err := node.Write()388 c.Assert(err, gc.IsNil)389 }390 mgoData = make(map[string]interface{})391 err = s.MgoSuite.Session.DB("juju").C("settings").FindId(s.key).One(&mgoData)392 c.Assert(err, gc.IsNil)393 newVersion := mgoData["version"]394 c.Assert(version, gc.Equals, newVersion)395}396func (s *SettingsSuite) TestWriteTwice(c *gc.C) {397 // Check the correct writing into a node by two config nodes.398 nodeOne, err := createSettings(s.state, s.key, nil)399 c.Assert(err, gc.IsNil)400 nodeOne.Set("a", "foo")401 changes, err := nodeOne.Write()402 c.Assert(err, gc.IsNil)403 c.Assert(changes, gc.DeepEquals, []ItemChange{404 {ItemAdded, "a", nil, "foo"},405 })406 nodeTwo, err := readSettings(s.state, s.key)407 c.Assert(err, gc.IsNil)408 nodeTwo.Set("a", "bar")409 changes, err = nodeTwo.Write()410 c.Assert(err, gc.IsNil)411 c.Assert(changes, gc.DeepEquals, []ItemChange{412 {ItemModified, "a", "foo", "bar"},413 })414 // Shouldn't write again. Changes were already415 // flushed and acted upon by other parties.416 changes, err = nodeOne.Write()417 c.Assert(err, gc.IsNil)418 c.Assert(changes, gc.DeepEquals, []ItemChange{})419 err = nodeOne.Read()420 c.Assert(err, gc.IsNil)421 c.Assert(nodeOne.key, gc.Equals, nodeTwo.key)422 c.Assert(nodeOne.disk, gc.DeepEquals, nodeTwo.disk)423 c.Assert(nodeOne.core, gc.DeepEquals, nodeTwo.core)424}425// cleanMgoSettings will remove MongoDB-specific settings but not unescape any426// keys, as opposed to cleanSettingsMap which does unescape keys.427func cleanMgoSettings(in map[string]interface{}) {428 delete(in, "_id")429 delete(in, "txn-revno")430 delete(in, "txn-queue")431}...

Full Screen

Full Screen

client.go

Source:client.go Github

copy

Full Screen

...20 DefaultURI = "mongodb://127.0.0.1:27017/test"21 // DefaultSessionTimeout is the default timeout after which the22 // session times out when unable to connect to the provided URI.23 DefaultSessionTimeout = 10 * time.Second24 // DefaultReadPreference when connecting to a mongo replica set.25 DefaultReadPreference = mgo.Primary26)27var (28 // DefaultSafety is the default saftey mode used for the underlying session.29 // These default settings are only good for local use as it makes not guarantees for writes.30 DefaultSafety = mgo.Safe{}31 _ client.Client = &Client{}32 _ client.Closer = &Client{}33)34// OplogAccessError wraps the underlying error when access to the oplog fails.35type OplogAccessError struct {36 reason string37}38func (e OplogAccessError) Error() string {39 return fmt.Sprintf("oplog access failed, %s", e.reason)40}41// InvalidReadPreferenceError represents the error when an incorrect mongo read preference has been set.42type InvalidReadPreferenceError struct {43 ReadPreference string44}45func (e InvalidReadPreferenceError) Error() string {46 return fmt.Sprintf("Invalid Read Preference, %s", e.ReadPreference)47}48// ClientOptionFunc is a function that configures a Client.49// It is used in NewClient.50type ClientOptionFunc func(*Client) error51// Client represents a client to the underlying MongoDB source.52type Client struct {53 uri string54 safety mgo.Safe55 tlsConfig *tls.Config56 sessionTimeout time.Duration57 tail bool58 readPreference mgo.Mode59 mgoSession *mgo.Session60}61// NewClient creates a new client to work with MongoDB.62//63// The caller can configure the new client by passing configuration options64// to the func.65//66// Example:67//68// client, err := NewClient(69// WithURI("mongodb://localhost:27017"),70// WithTimeout("30s"))71//72// If no URI is configured, it uses defaultURI by default.73//74// An error is also returned when some configuration option is invalid75func NewClient(options ...ClientOptionFunc) (*Client, error) {76 // Set up the client77 c := &Client{78 uri: DefaultURI,79 sessionTimeout: DefaultSessionTimeout,80 safety: DefaultSafety,81 tlsConfig: nil,82 tail: false,83 readPreference: DefaultReadPreference,84 }85 // Run the options on it86 for _, option := range options {87 if err := option(c); err != nil {88 return nil, err89 }90 }91 return c, nil92}93// WithURI defines the full connection string of the MongoDB database.94func WithURI(uri string) ClientOptionFunc {95 return func(c *Client) error {96 _, err := mgo.ParseURL(uri)97 if err != nil {98 return client.InvalidURIError{URI: uri, Err: err.Error()}99 }100 c.uri = uri101 return nil102 }103}104// WithTimeout overrides the DefaultSessionTimeout and should be parseable by time.ParseDuration105func WithTimeout(timeout string) ClientOptionFunc {106 return func(c *Client) error {107 if timeout == "" {108 c.sessionTimeout = DefaultSessionTimeout109 return nil110 }111 t, err := time.ParseDuration(timeout)112 if err != nil {113 return client.InvalidTimeoutError{Timeout: timeout}114 }115 c.sessionTimeout = t116 return nil117 }118}119// WithSSL configures the database connection to connect via TLS.120func WithSSL(ssl bool) ClientOptionFunc {121 return func(c *Client) error {122 if ssl {123 tlsConfig := &tls.Config{InsecureSkipVerify: true}124 tlsConfig.RootCAs = x509.NewCertPool()125 c.tlsConfig = tlsConfig126 }127 return nil128 }129}130// WithCACerts configures the RootCAs for the underlying TLS connection131func WithCACerts(certs []string) ClientOptionFunc {132 return func(c *Client) error {133 if len(certs) > 0 {134 roots := x509.NewCertPool()135 for _, cert := range certs {136 if _, err := os.Stat(cert); err != nil {137 return errors.New("Cert file not found")138 }139 c, err := ioutil.ReadFile(cert)140 if err != nil {141 return err142 }143 if ok := roots.AppendCertsFromPEM(c); !ok {144 return client.ErrInvalidCert145 }146 }147 if c.tlsConfig != nil {148 c.tlsConfig.RootCAs = roots149 } else {150 c.tlsConfig = &tls.Config{RootCAs: roots}151 }152 c.tlsConfig.InsecureSkipVerify = false153 }154 return nil155 }156}157// WithWriteConcern configures the write concern option for the session (Default: 0).158func WithWriteConcern(wc int) ClientOptionFunc {159 return func(c *Client) error {160 if wc > 0 {161 c.safety.W = wc162 }163 return nil164 }165}166// WithFsync configures whether the server will wait for Fsync to complete before returning167// a response (Default: false).168func WithFsync(fsync bool) ClientOptionFunc {169 return func(c *Client) error {170 c.safety.FSync = fsync171 return nil172 }173}174// WithTail set the flag to tell the Client whether or not access to the oplog will be175// needed (Default: false).176func WithTail(tail bool) ClientOptionFunc {177 return func(c *Client) error {178 c.tail = tail179 return nil180 }181}182// WithReadPreference sets the MongoDB read preference based on the provided string.183func WithReadPreference(readPreference string) ClientOptionFunc {184 return func(c *Client) error {185 if readPreference == "" {186 c.readPreference = DefaultReadPreference187 return nil188 }189 switch strings.ToLower(readPreference) {190 case "primary":191 c.readPreference = mgo.Primary192 case "primarypreferred":193 c.readPreference = mgo.PrimaryPreferred194 case "secondary":195 c.readPreference = mgo.Secondary196 case "secondarypreferred":197 c.readPreference = mgo.SecondaryPreferred198 case "nearest":199 c.readPreference = mgo.Nearest200 default:201 return InvalidReadPreferenceError{ReadPreference: readPreference}202 }203 return nil204 }205}206// Connect tests the mongodb connection and initializes the mongo session207func (c *Client) Connect() (client.Session, error) {208 if c.mgoSession == nil {209 if err := c.initConnection(); err != nil {210 return nil, err211 }212 }213 return c.session(), nil214}215// Close satisfies the Closer interface and handles closing the initial mgo.Session....

Full Screen

Full Screen

mongodb.go

Source:mongodb.go Github

copy

Full Screen

1package helper2import (3 "gopkg.in/mgo.v2"4 "github.com/spf13/viper"5)6func MgoChaos() {7 GMgoConnectionStringURI = viper.GetString("mongodb.addr")8 GMgoDatabaseName = viper.GetString("mongodb.database")9}10var gMgoSession *mgo.Session11//mgo.PrimaryPreferred12//5 mode:13//primary Perform all read operations on the master node14//primaryPreferred Priority on the main node to read, if the primary node is not available, and then from the slave operation15//secondary All read operations are performed on the slave node16//secondaryPreferred Priority to read from the slave node, if all slave nodes are unavailable, and then from the master node operation。17//nearest According to the network delay time, the nearest read operation, regardless of the node type。18//default is strong mode its named primary. eg. gMgoSession.SetMode(mgo.Strong)19//des:https://segmentfault.com/a/119000000046048920var GMgoConnectionStringURI = ""21var GMgoDatabaseName = ""22func NewMgoSession() *mgo.Session {23 if gMgoSession == nil {24 var err error25 gMgoSession, err = mgo.Dial(GMgoConnectionStringURI)26 if err != nil {27 panic(err)28 }29 if err = gMgoSession.Ping(); err != nil {30 panic(err)31 }32 gMgoSession.SetMode(mgo.PrimaryPreferred, false)33 }34 return gMgoSession35}36func MgoExecute(colName string, q func(*mgo.Collection) error) error {37 s := NewMgoSession().Clone()38 defer s.Close()39 return q(s.DB(GMgoDatabaseName).C(colName))40}41func MgoExecuteBulk(colName string, q func(*mgo.Bulk) error) error {42 s := NewMgoSession().Clone()43 defer s.Close()44 return q(s.DB(GMgoDatabaseName).C(colName).Bulk())45}...

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2type Person struct {3}4func main() {5 session, err := mgo.Dial("localhost")6 if err != nil {7 panic(err)8 }9 defer session.Close()10 c := session.DB("test").C("people")11 err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, &Person{"Cla", "+55 53 8402 8510"})12 if err != nil {13 panic(err)14 }15 result := Person{}16 err = c.Find(bson.M{"name": "Ale"}).One(&result)17 if err != nil {18 panic(err)19 }20 fmt.Println("Phone:", result.Phone)21}22import (23type Person struct {24}25func main() {26 session, err := mgo.Dial("localhost")27 if err != nil {28 panic(err)29 }30 defer session.Close()31 c := session.DB("test").C("people")32 err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, &Person{"Cla", "+55 53 8402 8510"})33 if err != nil {34 panic(err)35 }36 result := []Person{}37 err = c.Find(bson.M{"name": "Ale"}).All(&result)38 if err != nil {39 panic(err)40 }41 fmt.Println("Phone:", result[0].Phone)42}43import (44type Person struct {45}46func main() {

Full Screen

Full Screen

Read

Using AI Code Generation

copy

Full Screen

1import (2type Employee struct {3}4func main() {5 if err != nil {6 panic(err)7 }8 defer session.Close()9 session.SetMode(mgo.Monotonic, true)10 c := session.DB("test").C("employee")11 result := Employee{}12 err = c.Find(bson.M{"id": "1"}).One(&result)13 if err != nil {14 panic(err)15 }16 fmt.Println("Id:", result.Id)17 fmt.Println("Name:", result.Name)18}19import (20type Employee struct {21}22func main() {23 if err != nil {24 panic(err)25 }26 defer session.Close()27 session.SetMode(mgo.Monotonic, true)28 c := session.DB("test").C("employee")29 result := []Employee{}30 err = c.Find(bson.M{"id": "1"}).All(&result)31 if err != nil {32 panic(err)33 }34 fmt.Println("Id:", result[0].Id)35 fmt.Println("Name:", result[0].Name)36}37import (38type Employee struct {39}40func main() {41 if err != nil {42 panic(err)43 }44 defer session.Close()45 session.SetMode(mgo

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Keploy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful