queryfield.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sqlchemy
  15. import "fmt"
  16. type sQueryField struct {
  17. from IQuerySource
  18. name string
  19. alias string
  20. }
  21. // the string after select
  22. func (sqf *sQueryField) Expression() string {
  23. qChar := sqf.from.database().backend.QuoteChar()
  24. return fmt.Sprintf("%s%s%s.%s%s%s", qChar, sqf.from.Alias(), qChar, qChar, sqf.name, qChar)
  25. }
  26. // the name of thie field
  27. func (sqf *sQueryField) Name() string {
  28. if len(sqf.alias) > 0 {
  29. return sqf.alias
  30. }
  31. return sqf.name
  32. }
  33. // the reference string in where clause
  34. func (sqf *sQueryField) Reference() string {
  35. qChar := sqf.from.database().backend.QuoteChar()
  36. return fmt.Sprintf("%s%s%s.%s%s%s", qChar, sqf.from.Alias(), qChar, qChar, sqf.Name(), qChar)
  37. }
  38. // give this field an alias name
  39. func (sqf *sQueryField) Label(label string) IQueryField {
  40. sqf.alias = label
  41. return sqf
  42. }
  43. // return variables
  44. func (sqf *sQueryField) Variables() []interface{} {
  45. return nil
  46. }
  47. // ConvertFromValue returns the SQL representation of a value for this
  48. func (sqf *sQueryField) ConvertFromValue(val interface{}) interface{} {
  49. field := sqf.from.Field(sqf.name)
  50. if field == nil {
  51. return val
  52. }
  53. return field.ConvertFromValue(val)
  54. }
  55. // Database returns the database of this IQuerySource
  56. func (sqf *sQueryField) database() *SDatabase {
  57. return sqf.from.database()
  58. }
  59. func newQueryField(from IQuerySource, name string) *sQueryField {
  60. return &sQueryField{
  61. from: from,
  62. name: name,
  63. }
  64. }
  65. type queryFieldList []IQueryField
  66. func (a queryFieldList) Len() int { return len(a) }
  67. func (a queryFieldList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  68. func (a queryFieldList) Less(i, j int) bool { return a[i].Name() < a[j].Name() }