Datastore Query return data not as expected

Should I expect the iterator to handle the []string properties of this structure.
I have three plans in the data base.

**Plan 1** ContinuingServiceTypes and InitialServiceTypes
{
  "values": [
    {
      "stringValue": "s1"
    },
    {
      "stringValue": "s2"
    },
    {
      "stringValue": "s3"
    }
  ]
}
**Plan 2** ContinuingServiceTypes and InitialServiceTypes
{
  "values": [
    {
      "stringValue": "s2"
    },
    {
      "stringValue": "s3"
    }
   ]
}
**Plan 2** ContinuingServiceTypes and InitialServiceTypes
{
  "values": [
    {
      "stringValue": "s3"
    }
   ]
}
type Plan struct {
	ContinuingDuration     int      `json:"continuingDuration"`
	ContinuingServiceTypes []string `json:"continuingServiceTypes"`
	InitialAssesment       bool     `json:"initialAssesment"`
	InitialDuration        int      `json:"continuingDuration"`
	InitialServiceTypes    []string `json:"initialServiceTypes"`
	OngoingMonitoring      bool     `json:"ongoingMonitoring"`
}
// goGetPlan returns an array of plan entities from datastore for testing
func goGetPlan(ts TherapistService) {
	var thePlan Plan
	query := datastore.NewQuery("Plan")
	items := ts.DSClient.Run(ts.Ctx, query)

	for {
		_, err := items.Next(&thePlan)
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatalf("Error fetching next Plan: %v", err)
		}
		log.Printf("The Plan %v  %v", thePlan.ContinuingServiceTypes, thePlan.InitialServiceTypes)
	}
}

The output from the log statement is
Plan1 [s1 s2 s3] [s1 s2 s3]
Plan2 [s2 s3 s3] [s2 s3 s3]
Plan3 [s3 s3 s3] [s3 s3 s3]
UNLESS I initialise the []string slices after each iteration and then the output is as expected. I have traced the source through to the datastore pkg load module and then unfortunately get lost.

Is this the type of code I should have to implement or should it be handled by the library?

Thanks for any help you may provide.
John

Hi

You are using the same instance of Plan to read into. And because the number of element varies from read to read will sometimes old elements be left. Move the declaration of the plan to inside the for-loop will you get a new instance every time.

Johan,
Thank You
I guess my old roots were telling me to watch out for memory consumption (pre garbage collection days). I have implemented your suggestion. And now I know a lot more about query.go and load.go.

Thanks again,

John

1 Like

Good i could help you

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.