sql_dictionary.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. """
  2. ***************************************************************************
  3. sql_dictionary.py
  4. ---------------------
  5. Date : December 2015
  6. Copyright : (C) 2015 by Hugo Mercier
  7. Email : hugo dot mercier at oslandia dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Hugo Mercier'
  18. __date__ = 'December 2015'
  19. __copyright__ = '(C) 2015, Hugo Mercier'
  20. # keywords
  21. keywords = [
  22. # TODO get them from a reference page
  23. "action", "add", "after", "all", "alter", "analyze", "and", "as", "asc",
  24. "before", "begin", "between", "by", "cascade", "case", "cast", "check",
  25. "collate", "column", "commit", "constraint", "create", "cross", "current_date",
  26. "current_time", "current_timestamp", "default", "deferrable", "deferred",
  27. "delete", "desc", "distinct", "drop", "each", "else", "end", "escape",
  28. "except", "exists", "for", "foreign", "from", "full", "group", "having",
  29. "ignore", "immediate", "in", "initially", "inner", "insert", "intersect",
  30. "into", "is", "isnull", "join", "key", "left", "like", "limit", "match",
  31. "natural", "no", "not", "notnull", "null", "of", "offset", "on", "or", "order",
  32. "outer", "primary", "references", "release", "restrict", "right", "rollback",
  33. "row", "savepoint", "select", "set", "table", "temporary", "then", "to",
  34. "transaction", "trigger", "union", "unique", "update", "using", "values",
  35. "view", "when", "where",
  36. "abort", "attach", "autoincrement", "conflict", "database", "detach",
  37. "exclusive", "explain", "fail", "glob", "if", "index", "indexed", "instead",
  38. "plan", "pragma", "query", "raise", "regexp", "reindex", "rename", "replace",
  39. "temp", "vacuum", "virtual"
  40. ]
  41. spatialite_keywords = []
  42. # functions
  43. functions = [
  44. # TODO get them from a reference page
  45. "changes", "coalesce", "glob", "ifnull", "hex", "last_insert_rowid",
  46. "nullif", "quote", "random",
  47. "randomblob", "replace", "round", "soundex", "total_change",
  48. "typeof", "zeroblob", "date", "datetime", "julianday", "strftime"
  49. ]
  50. operators = [
  51. ' AND ', ' OR ', '||', ' < ', ' <= ', ' > ', ' >= ', ' = ', ' <> ', ' IS ', ' IS NOT ', ' IN ', ' LIKE ', ' GLOB ', ' MATCH ', ' REGEXP '
  52. ]
  53. math_functions = [
  54. # SQL math functions
  55. "Abs", "ACos", "ASin", "ATan", "Cos", "Cot", "Degrees", "Exp", "Floor", "Log", "Log2",
  56. "Log10", "Pi", "Radians", "Round", "Sign", "Sin", "Sqrt", "StdDev_Pop", "StdDev_Samp", "Tan",
  57. "Var_Pop", "Var_Samp"]
  58. string_functions = ["Length", "Lower", "Upper", "Like", "Trim", "LTrim", "RTrim", "Replace", "Substr"]
  59. aggregate_functions = [
  60. "Max", "Min", "Avg", "Count", "Sum", "Group_Concat", "Total", "Var_Pop", "Var_Samp", "StdDev_Pop", "StdDev_Samp"
  61. ]
  62. spatialite_functions = [ # from www.gaia-gis.it/spatialite-2.3.0/spatialite-sql-2.3.0.html
  63. # SQL utility functions for BLOB objects
  64. "*iszipblob", "*ispdfblob", "*isgifblob", "*ispngblob", "*isjpegblob", "*isexifblob",
  65. "*isexifgpsblob", "*geomfromexifgpsblob", "MakePoint", "BuildMbr", "*buildcirclembr", "ST_MinX",
  66. "ST_MinY", "ST_MaxX", "ST_MaxY",
  67. # SQL functions for constructing a geometric object given its Well-known Text Representation
  68. "ST_GeomFromText", "*pointfromtext",
  69. # SQL functions for constructing a geometric object given its Well-known Binary Representation
  70. "*geomfromwkb", "*pointfromwkb",
  71. # SQL functions for obtaining the Well-known Text / Well-known Binary Representation of a geometric object
  72. "ST_AsText", "ST_AsBinary",
  73. # SQL functions supporting exotic geometric formats
  74. "*assvg", "*asfgf", "*geomfromfgf",
  75. # SQL functions on type Geometry
  76. "ST_Dimension", "ST_GeometryType", "ST_Srid", "ST_SetSrid", "ST_isEmpty", "ST_isSimple", "ST_isValid", "ST_Boundary",
  77. "ST_Envelope",
  78. # SQL functions on type Point
  79. "ST_X", "ST_Y",
  80. # SQL functions on type Curve [Linestring or Ring]
  81. "ST_StartPoint", "ST_EndPoint", "ST_Length", "ST_isClosed", "ST_isRing", "ST_Simplify",
  82. "*simplifypreservetopology",
  83. # SQL functions on type LineString
  84. "ST_NumPoints", "ST_PointN",
  85. # SQL functions on type Surface [Polygon or Ring]
  86. "ST_Centroid", "ST_PointOnSurface", "ST_Area",
  87. # SQL functions on type Polygon
  88. "ST_ExteriorRing", "ST_InteriorRingN",
  89. # SQL functions on type GeomCollection
  90. "ST_NumGeometries", "ST_GeometryN",
  91. # SQL functions that test approximative spatial relationships via MBRs
  92. "MbrEqual", "MbrDisjoint", "MbrTouches", "MbrWithin", "MbrOverlaps", "MbrIntersects",
  93. "MbrContains",
  94. # SQL functions that test spatial relationships
  95. "ST_Equals", "ST_Disjoint", "ST_Touches", "ST_Within", "ST_Overlaps", "ST_Crosses", "ST_Intersects", "ST_Contains",
  96. "ST_Relate",
  97. # SQL functions for distance relationships
  98. "ST_Distance",
  99. # SQL functions that implement spatial operators
  100. "ST_Intersection", "ST_Difference", "ST_Union", "ST_SymDifference", "ST_Buffer", "ST_ConvexHull",
  101. # SQL functions for coordinate transformations
  102. "ST_Transform",
  103. # SQL functions for Spatial-MetaData and Spatial-Index handling
  104. "*initspatialmetadata", "*addgeometrycolumn", "*recovergeometrycolumn", "*discardgeometrycolumn",
  105. "*createspatialindex", "*creatembrcache", "*disablespatialindex",
  106. # SQL functions implementing FDO/OGR compatibility
  107. "*checkspatialmetadata", "*autofdostart", "*autofdostop", "*initfdospatialmetadata",
  108. "*addfdogeometrycolumn", "*recoverfdogeometrycolumn", "*discardfdogeometrycolumn",
  109. # SQL functions for MbrCache-based queries
  110. "*filtermbrwithin", "*filtermbrcontains", "*filtermbrintersects", "*buildmbrfilter"
  111. ]
  112. qgis_functions = [
  113. "atan2", "round", "rand", "randf", "clamp", "scale_linear", "scale_polynomial", "scale_exponential", "_pi", "to_int", "toint", "to_real", "toreal",
  114. "to_string", "tostring", "to_datetime", "todatetime", "to_date", "todate", "to_time", "totime", "to_interval", "tointerval",
  115. "regexp_match", "now", "_now", "age", "year", "month", "week", "day", "hour", "minute", "second", "day_of_week", "title",
  116. "levenshtein", "longest_common_substring", "hamming_distance", "wordwrap", "regexp_replace", "regexp_substr", "concat",
  117. "strpos", "_left", "_right", "rpad", "lpad", "format", "format_number", "format_date", "color_rgb", "color_rgba", "ramp_color",
  118. "color_hsl", "color_hsla", "color_hsv", "color_hsva", "color_cmyk", "color_cmyka", "color_part", "darker", "lighter",
  119. "set_color_part", "point_n", "start_point", "end_point", "nodes_to_points", "segments_to_lines", "make_point",
  120. "make_point_m", "make_line", "make_polygon", "x_min", "xmin", "x_max", "xmax", "y_min", "ymin", "y_max", "ymax", "geom_from_wkt",
  121. "geomFromWKT", "geom_from_gml", "relate", "intersects_bbox", "bbox", "translate", "buffer", "point_on_surface", "reverse",
  122. "exterior_ring", "interior_ring_n", "geometry_n", "bounds", "num_points", "num_interior_rings", "num_rings", "num_geometries",
  123. "bounds_width", "bounds_height", "is_closed", "convex_hull", "sym_difference", "combine", "_union", "geom_to_wkt", "geomToWKT",
  124. "transform", "uuid", "_uuid", "layer_property", "var", "_specialcol_", "project_color"]
  125. # constants
  126. constants = ["null", "false", "true"]
  127. spatialite_constants = []
  128. def getSqlDictionary(spatial=True):
  129. def strip_star(s):
  130. if s[0] == '*':
  131. return s.lower()[1:]
  132. else:
  133. return s.lower()
  134. k, c, f = list(keywords), list(constants), list(functions)
  135. if spatial:
  136. k += spatialite_keywords
  137. f += spatialite_functions
  138. f += qgis_functions
  139. c += spatialite_constants
  140. return {'keyword': list(map(strip_star, k)), 'constant': list(map(strip_star, c)), 'function': list(map(strip_star, f))}
  141. def getQueryBuilderDictionary():
  142. # concat functions
  143. def ff(l):
  144. return [s for s in l if s[0] != '*']
  145. def add_paren(l):
  146. return [s + "(" for s in l]
  147. foo = sorted(add_paren(ff(list(set.union(set(functions), set(spatialite_functions), set(qgis_functions))))))
  148. m = sorted(add_paren(ff(math_functions)))
  149. agg = sorted(add_paren(ff(aggregate_functions)))
  150. op = ff(operators)
  151. s = sorted(add_paren(ff(string_functions)))
  152. return {'function': foo, 'math': m, 'aggregate': agg, 'operator': op, 'string': s}