clickhouse_send_query.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package clickhouse
  2. import (
  3. "context"
  4. "github.com/ClickHouse/clickhouse-go/lib/data"
  5. "github.com/ClickHouse/clickhouse-go/lib/protocol"
  6. )
  7. func (ch *clickhouse) sendQuery(ctx context.Context, query string, externalTables []ExternalTable) error {
  8. ch.logf("[send query] %s", query)
  9. if err := ch.encoder.Uvarint(protocol.ClientQuery); err != nil {
  10. return err
  11. }
  12. var queryID string
  13. queryIDValue := ctx.Value(queryIDKey)
  14. if queryIDValue != nil {
  15. if queryIdStr, ok := queryIDValue.(string); ok {
  16. queryID = queryIdStr
  17. }
  18. }
  19. if err := ch.encoder.String(queryID); err != nil {
  20. return err
  21. }
  22. { // client info
  23. ch.encoder.Uvarint(1)
  24. ch.encoder.String("")
  25. ch.encoder.String("")
  26. ch.encoder.String("[::ffff:127.0.0.1]:0")
  27. ch.encoder.Uvarint(1) // iface type TCP
  28. ch.encoder.String(hostname)
  29. ch.encoder.String(hostname)
  30. }
  31. if err := ch.ClientInfo.Write(ch.encoder); err != nil {
  32. return err
  33. }
  34. if ch.ServerInfo.Revision >= protocol.DBMS_MIN_REVISION_WITH_QUOTA_KEY_IN_CLIENT_INFO {
  35. ch.encoder.String("")
  36. }
  37. // the settings are written as list of contiguous name-value pairs, finished with empty name
  38. if !ch.settings.IsEmpty() {
  39. ch.logf("[query settings] %s", ch.settings.settingsStr)
  40. if err := ch.settings.Serialize(ch.encoder); err != nil {
  41. return err
  42. }
  43. }
  44. // empty string is a marker of the end of the settings
  45. if err := ch.encoder.String(""); err != nil {
  46. return err
  47. }
  48. if err := ch.encoder.Uvarint(protocol.StateComplete); err != nil {
  49. return err
  50. }
  51. compress := protocol.CompressDisable
  52. if ch.compress {
  53. compress = protocol.CompressEnable
  54. }
  55. if err := ch.encoder.Uvarint(compress); err != nil {
  56. return err
  57. }
  58. if err := ch.encoder.String(query); err != nil {
  59. return err
  60. }
  61. if err := ch.sendExternalTables(externalTables); err != nil {
  62. return err
  63. }
  64. if err := ch.writeBlock(&data.Block{}, ""); err != nil {
  65. return err
  66. }
  67. return ch.encoder.Flush()
  68. }