utils.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package dolphin
  2. import (
  3. pcast "github.com/pingcap/parser/ast"
  4. "github.com/kyleconroy/sqlc/internal/sql/ast"
  5. )
  6. type nodeSearch struct {
  7. list []pcast.Node
  8. check func(pcast.Node) bool
  9. }
  10. func (s *nodeSearch) Enter(n pcast.Node) (pcast.Node, bool) {
  11. if s.check(n) {
  12. s.list = append(s.list, n)
  13. }
  14. return n, false // skipChildren
  15. }
  16. func (s *nodeSearch) Leave(n pcast.Node) (pcast.Node, bool) {
  17. return n, true // ok
  18. }
  19. func collect(root pcast.Node, f func(pcast.Node) bool) []pcast.Node {
  20. if root == nil {
  21. return nil
  22. }
  23. ns := &nodeSearch{check: f}
  24. root.Accept(ns)
  25. return ns.list
  26. }
  27. type nodeVisit struct {
  28. fn func(pcast.Node)
  29. }
  30. func (s *nodeVisit) Enter(n pcast.Node) (pcast.Node, bool) {
  31. s.fn(n)
  32. return n, false // skipChildren
  33. }
  34. func (s *nodeVisit) Leave(n pcast.Node) (pcast.Node, bool) {
  35. return n, true // ok
  36. }
  37. func visit(root pcast.Node, f func(pcast.Node)) {
  38. if root == nil {
  39. return
  40. }
  41. ns := &nodeVisit{fn: f}
  42. root.Accept(ns)
  43. }
  44. // Maybe not useful?
  45. func text(nodes []pcast.Node) []string {
  46. str := make([]string, len(nodes))
  47. for i := range nodes {
  48. if nodes[i] == nil {
  49. continue
  50. }
  51. str[i] = nodes[i].Text()
  52. }
  53. return str
  54. }
  55. func parseTableName(n *pcast.TableName) *ast.TableName {
  56. return &ast.TableName{
  57. Schema: identifier(n.Schema.String()),
  58. Name: identifier(n.Name.String()),
  59. }
  60. }
  61. func toList(node pcast.Node) *ast.List {
  62. var items []ast.Node
  63. switch n := node.(type) {
  64. case *pcast.TableName:
  65. if schema := n.Schema.String(); schema != "" {
  66. items = append(items, NewIdentifer(schema))
  67. }
  68. items = append(items, NewIdentifer(n.Name.String()))
  69. default:
  70. return nil
  71. }
  72. return &ast.List{Items: items}
  73. }
  74. func isNotNull(n *pcast.ColumnDef) bool {
  75. for i := range n.Options {
  76. if n.Options[i].Tp == pcast.ColumnOptionNotNull {
  77. return true
  78. }
  79. if n.Options[i].Tp == pcast.ColumnOptionPrimaryKey {
  80. return true
  81. }
  82. }
  83. return false
  84. }