si3nloong / sqlgen

SQL code generator, no extra runtime cost! It's blazingly fast!!! 🚀🚀🚀
MIT License
17 stars 0 forks source link

Support nested fields #129

Open si3nloong opened 2 months ago

si3nloong commented 2 months ago

For example, if we have a struct like following.

type Ptr struct {
  *embedded
}

type embedded struct {
  EmbeddedTime *time.Time
}

For embedded struct pointer, the generated codes are as follows :

func(v Ptr) Values() []any {
  return []any{v.embedded.EmbeddedTime}
}

And this is not prefect, because the program will encounter invalid memory address or nil pointer dereference error. Instead, we should generate the following codes

Values

func(v Ptr) Values() []any {
  values := make([]any, 1)
  if v.embedded != nil {
    values[0] = types.Time(v.embedded.EmbeddedTime)
  }
  return values
}

Addrs

func(v Ptr) Addrs() []any {
  addrs := make([]any, 1)
  if v.embedded == nil {
    v.embedded = new(embedded)
  }
  if v.embedded.EmbeddedTime == nil {
    v.embedded.EmbeddedTime = new(time.Time)
  }
  addrs[0] = types.Time(v.embedded.EmbeddedTime)
  return addrs
}
si3nloong commented 1 week ago

This can be solve easily using reflect but comes with performance penalty, preferable to use native code to do the initialisation.