rawquery.go 2.3 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. // SRawQueryField is a struct represents a field of a raw SQL query
  16. // a raw query is a query that not follow standard SELECT ... FROM ... pattern
  17. // e.g. show tables
  18. // the struct implements IQueryField interface
  19. type SRawQueryField struct {
  20. name string
  21. db *SDatabase
  22. }
  23. // Expression implementation of SRawQueryField for IQueryField
  24. func (rqf *SRawQueryField) Expression() string {
  25. return rqf.name
  26. }
  27. // Name implementation of SRawQueryField for IQueryField
  28. func (rqf *SRawQueryField) Name() string {
  29. return rqf.name
  30. }
  31. // Reference implementation of SRawQueryField for IQueryField
  32. func (rqf *SRawQueryField) Reference() string {
  33. return rqf.name
  34. }
  35. // Label implementation of SRawQueryField for IQueryField
  36. func (rqf *SRawQueryField) Label(label string) IQueryField {
  37. return rqf
  38. }
  39. // Variables implementation of SRawQueryField for IQueryField
  40. func (rqf *SRawQueryField) Variables() []interface{} {
  41. return nil
  42. }
  43. // ConvertFromValue implementation of SRawQueryField for IQueryField
  44. func (rqf *SRawQueryField) ConvertFromValue(val interface{}) interface{} {
  45. return val
  46. }
  47. func (rqf *SRawQueryField) database() *SDatabase {
  48. return rqf.db
  49. }
  50. // NewRawQuery returns an instance of SQuery with raw SQL query. e.g. show tables
  51. func NewRawQuery(sqlStr string, fields ...string) *SQuery {
  52. return GetDefaultDB().NewRawQuery(sqlStr, fields...)
  53. }
  54. // NewRawQuery returns an instance of SQuery with raw SQL query for a database, e.g. show tables
  55. func (db *SDatabase) NewRawQuery(sqlStr string, fields ...string) *SQuery {
  56. qfs := make([]IQueryField, len(fields))
  57. for i, f := range fields {
  58. rqf := SRawQueryField{
  59. name: f,
  60. db: db,
  61. }
  62. qfs[i] = &rqf
  63. }
  64. q := SQuery{
  65. db: db,
  66. rawSql: sqlStr,
  67. fields: qfs,
  68. }
  69. return &q
  70. }