Skip to content

First level cache

Derevtsov Konstantin edited this page Jul 10, 2020 · 3 revisions

To reduce database queries, D3 provides the first-level cache. D3 remembers the entities extracted during the session and when analyzing the next request, within the same session, if D3 understands that it has all the requested entities, then the database will not be requested. Simple example:

ctx := o.orm.CtxWithSession(context.Background())
userRepository, err := orm.MakeRepository((*User)(nil))
if err != nil {
    log.Fatal(err)
}

// this call generate SELECT query
user, err := userRepository.FindOne(ctx, userRepository.Select().Where("users.id", "=", 1))
if err != nil {
    log.Fatal(err)
}

// in this call no new db query will be created
sameUser, err := userRepository.FindOne(ctx, userRepository.Select().Where("users.id", "=", 1))
if err != nil {
    log.Fatal(err)
}

More complex example:

ctx := o.orm.CtxWithSession(context.Background())
userRepository, err := orm.MakeRepository((*User)(nil))
if err != nil {
    log.Fatal(err)
}

q := userRepository.Select().Where("age", ">", 18)
q.With("myModule/myPkg/Profile")
// this call generate SELECT query and return collection of users
users, err := userRepository.Find(ctx, q)
if err != nil {
    log.Fatal(err)
}

profileRepository, err := orm.MakeRepository((*Profile)(nil))
if err != nil {
    log.Fatal(err)
}

// if profiles with id's 1 and 2 fetched in previous query, then no new db query will not be created
profiles, err := profileRepository.Find(ctx, profileRepository.Select().Where("id", "in", 1, 2))
if err != nil {
    log.Fatal(err)
}
Clone this wiki locally