github.com/gogf/gf@v1.16.9/database/gdb/gdb_model_fields.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gdb
     8  
     9  import (
    10  	"fmt"
    11  	"github.com/gogf/gf/container/gset"
    12  	"github.com/gogf/gf/text/gstr"
    13  	"github.com/gogf/gf/util/gconv"
    14  	"github.com/gogf/gf/util/gutil"
    15  )
    16  
    17  // Fields appends `fieldNamesOrMapStruct` to the operation fields of the model, multiple fields joined using char ','.
    18  // The parameter `fieldNamesOrMapStruct` can be type of string/map/*map/struct/*struct.
    19  func (m *Model) Fields(fieldNamesOrMapStruct ...interface{}) *Model {
    20  	length := len(fieldNamesOrMapStruct)
    21  	if length == 0 {
    22  		return m
    23  	}
    24  	switch {
    25  	// String slice.
    26  	case length >= 2:
    27  		return m.appendFieldsByStr(gstr.Join(
    28  			m.mappingAndFilterToTableFields(gconv.Strings(fieldNamesOrMapStruct), true),
    29  			",",
    30  		))
    31  	// It needs type asserting.
    32  	case length == 1:
    33  		switch r := fieldNamesOrMapStruct[0].(type) {
    34  		case string:
    35  			return m.appendFieldsByStr(gstr.Join(
    36  				m.mappingAndFilterToTableFields([]string{r}, false), ",",
    37  			))
    38  		case []string:
    39  			return m.appendFieldsByStr(gstr.Join(
    40  				m.mappingAndFilterToTableFields(r, true), ",",
    41  			))
    42  		default:
    43  			return m.appendFieldsByStr(gstr.Join(
    44  				m.mappingAndFilterToTableFields(gutil.Keys(r), true), ",",
    45  			))
    46  		}
    47  	}
    48  	return m
    49  }
    50  
    51  // FieldsEx appends `fieldNamesOrMapStruct` to the excluded operation fields of the model,
    52  // multiple fields joined using char ','.
    53  // Note that this function supports only single table operations.
    54  // The parameter `fieldNamesOrMapStruct` can be type of string/map/*map/struct/*struct.
    55  func (m *Model) FieldsEx(fieldNamesOrMapStruct ...interface{}) *Model {
    56  	length := len(fieldNamesOrMapStruct)
    57  	if length == 0 {
    58  		return m
    59  	}
    60  	model := m.getModel()
    61  	switch {
    62  	case length >= 2:
    63  		model.fieldsEx = gstr.Join(m.mappingAndFilterToTableFields(gconv.Strings(fieldNamesOrMapStruct), true), ",")
    64  		return model
    65  	case length == 1:
    66  		switch r := fieldNamesOrMapStruct[0].(type) {
    67  		case string:
    68  			model.fieldsEx = gstr.Join(m.mappingAndFilterToTableFields([]string{r}, false), ",")
    69  		case []string:
    70  			model.fieldsEx = gstr.Join(m.mappingAndFilterToTableFields(r, true), ",")
    71  		default:
    72  			model.fieldsEx = gstr.Join(m.mappingAndFilterToTableFields(gutil.Keys(r), true), ",")
    73  		}
    74  		return model
    75  	}
    76  	return m
    77  }
    78  
    79  // FieldCount formats and appends commonly used field `COUNT(column)` to the select fields of model.
    80  func (m *Model) FieldCount(column string, as ...string) *Model {
    81  	asStr := ""
    82  	if len(as) > 0 && as[0] != "" {
    83  		asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0]))
    84  	}
    85  	return m.appendFieldsByStr(fmt.Sprintf(`COUNT(%s)%s`, m.db.GetCore().QuoteWord(column), asStr))
    86  }
    87  
    88  // FieldSum formats and appends commonly used field `SUM(column)` to the select fields of model.
    89  func (m *Model) FieldSum(column string, as ...string) *Model {
    90  	asStr := ""
    91  	if len(as) > 0 && as[0] != "" {
    92  		asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0]))
    93  	}
    94  	return m.appendFieldsByStr(fmt.Sprintf(`SUM(%s)%s`, m.db.GetCore().QuoteWord(column), asStr))
    95  }
    96  
    97  // FieldMin formats and appends commonly used field `MIN(column)` to the select fields of model.
    98  func (m *Model) FieldMin(column string, as ...string) *Model {
    99  	asStr := ""
   100  	if len(as) > 0 && as[0] != "" {
   101  		asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0]))
   102  	}
   103  	return m.appendFieldsByStr(fmt.Sprintf(`MIN(%s)%s`, m.db.GetCore().QuoteWord(column), asStr))
   104  }
   105  
   106  // FieldMax formats and appends commonly used field `MAX(column)` to the select fields of model.
   107  func (m *Model) FieldMax(column string, as ...string) *Model {
   108  	asStr := ""
   109  	if len(as) > 0 && as[0] != "" {
   110  		asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0]))
   111  	}
   112  	return m.appendFieldsByStr(fmt.Sprintf(`MAX(%s)%s`, m.db.GetCore().QuoteWord(column), asStr))
   113  }
   114  
   115  // FieldAvg formats and appends commonly used field `AVG(column)` to the select fields of model.
   116  func (m *Model) FieldAvg(column string, as ...string) *Model {
   117  	asStr := ""
   118  	if len(as) > 0 && as[0] != "" {
   119  		asStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0]))
   120  	}
   121  	return m.appendFieldsByStr(fmt.Sprintf(`AVG(%s)%s`, m.db.GetCore().QuoteWord(column), asStr))
   122  }
   123  
   124  func (m *Model) appendFieldsByStr(fields string) *Model {
   125  	if fields != "" {
   126  		model := m.getModel()
   127  		if model.fields == defaultFields {
   128  			model.fields = ""
   129  		}
   130  		if model.fields != "" {
   131  			model.fields += ","
   132  		}
   133  		model.fields += fields
   134  		return model
   135  	}
   136  	return m
   137  }
   138  
   139  func (m *Model) appendFieldsExByStr(fieldsEx string) *Model {
   140  	if fieldsEx != "" {
   141  		model := m.getModel()
   142  		if model.fieldsEx != "" {
   143  			model.fieldsEx += ","
   144  		}
   145  		model.fieldsEx += fieldsEx
   146  		return model
   147  	}
   148  	return m
   149  }
   150  
   151  // Filter marks filtering the fields which does not exist in the fields of the operated table.
   152  // Note that this function supports only single table operations.
   153  // Deprecated, filter feature is automatically enabled from GoFrame v1.16.0, it is so no longer used.
   154  func (m *Model) Filter() *Model {
   155  	if gstr.Contains(m.tables, " ") {
   156  		panic("function Filter supports only single table operations")
   157  	}
   158  	model := m.getModel()
   159  	model.filter = true
   160  	return model
   161  }
   162  
   163  // FieldsStr retrieves and returns all fields from the table, joined with char ','.
   164  // The optional parameter `prefix` specifies the prefix for each field, eg: FieldsStr("u.").
   165  // Deprecated, use GetFieldsStr instead.
   166  func (m *Model) FieldsStr(prefix ...string) string {
   167  	return m.GetFieldsStr(prefix...)
   168  }
   169  
   170  // GetFieldsStr retrieves and returns all fields from the table, joined with char ','.
   171  // The optional parameter `prefix` specifies the prefix for each field, eg: GetFieldsStr("u.").
   172  func (m *Model) GetFieldsStr(prefix ...string) string {
   173  	prefixStr := ""
   174  	if len(prefix) > 0 {
   175  		prefixStr = prefix[0]
   176  	}
   177  	tableFields, err := m.TableFields(m.tablesInit)
   178  	if err != nil {
   179  		panic(err)
   180  	}
   181  	if len(tableFields) == 0 {
   182  		panic(fmt.Sprintf(`empty table fields for table "%s"`, m.tables))
   183  	}
   184  	fieldsArray := make([]string, len(tableFields))
   185  	for k, v := range tableFields {
   186  		fieldsArray[v.Index] = k
   187  	}
   188  	newFields := ""
   189  	for _, k := range fieldsArray {
   190  		if len(newFields) > 0 {
   191  			newFields += ","
   192  		}
   193  		newFields += prefixStr + k
   194  	}
   195  	newFields = m.db.GetCore().QuoteString(newFields)
   196  	return newFields
   197  }
   198  
   199  // FieldsExStr retrieves and returns fields which are not in parameter `fields` from the table,
   200  // joined with char ','.
   201  // The parameter `fields` specifies the fields that are excluded.
   202  // The optional parameter `prefix` specifies the prefix for each field, eg: FieldsExStr("id", "u.").
   203  // Deprecated, use GetFieldsExStr instead.
   204  func (m *Model) FieldsExStr(fields string, prefix ...string) string {
   205  	return m.GetFieldsExStr(fields, prefix...)
   206  }
   207  
   208  // GetFieldsExStr retrieves and returns fields which are not in parameter `fields` from the table,
   209  // joined with char ','.
   210  // The parameter `fields` specifies the fields that are excluded.
   211  // The optional parameter `prefix` specifies the prefix for each field, eg: FieldsExStr("id", "u.").
   212  func (m *Model) GetFieldsExStr(fields string, prefix ...string) string {
   213  	prefixStr := ""
   214  	if len(prefix) > 0 {
   215  		prefixStr = prefix[0]
   216  	}
   217  	tableFields, err := m.TableFields(m.tablesInit)
   218  	if err != nil {
   219  		panic(err)
   220  	}
   221  	if len(tableFields) == 0 {
   222  		panic(fmt.Sprintf(`empty table fields for table "%s"`, m.tables))
   223  	}
   224  	fieldsExSet := gset.NewStrSetFrom(gstr.SplitAndTrim(fields, ","))
   225  	fieldsArray := make([]string, len(tableFields))
   226  	for k, v := range tableFields {
   227  		fieldsArray[v.Index] = k
   228  	}
   229  	newFields := ""
   230  	for _, k := range fieldsArray {
   231  		if fieldsExSet.Contains(k) {
   232  			continue
   233  		}
   234  		if len(newFields) > 0 {
   235  			newFields += ","
   236  		}
   237  		newFields += prefixStr + k
   238  	}
   239  	newFields = m.db.GetCore().QuoteString(newFields)
   240  	return newFields
   241  }
   242  
   243  // HasField determine whether the field exists in the table.
   244  func (m *Model) HasField(field string) (bool, error) {
   245  	tableFields, err := m.TableFields(m.tablesInit)
   246  	if err != nil {
   247  		return false, err
   248  	}
   249  	if len(tableFields) == 0 {
   250  		return false, fmt.Errorf(`empty table fields for table "%s"`, m.tables)
   251  	}
   252  	fieldsArray := make([]string, len(tableFields))
   253  	for k, v := range tableFields {
   254  		fieldsArray[v.Index] = k
   255  	}
   256  	for _, f := range fieldsArray {
   257  		if f == field {
   258  			return true, nil
   259  		}
   260  	}
   261  	return false, nil
   262  }