sql_dictionary.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. """
  2. ***************************************************************************
  3. sql_dictionary.py
  4. ---------------------
  5. Date : April 2012
  6. Copyright : (C) 2012 by Giuseppe Sucameli
  7. Email : brush dot tyler at gmail 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__ = 'Giuseppe Sucameli'
  18. __date__ = 'April 2012'
  19. __copyright__ = '(C) 2012, Giuseppe Sucameli'
  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. "absolute", "admin", "aggregate", "alias", "allocate", "analyse", "any", "are",
  37. "array", "asensitive", "assertion", "asymmetric", "at", "atomic",
  38. "authorization", "avg", "bigint", "binary", "bit", "bit_length", "blob",
  39. "boolean", "both", "breadth", "call", "called", "cardinality", "cascaded",
  40. "catalog", "ceil", "ceiling", "char", "character", "character_length",
  41. "char_length", "class", "clob", "close", "coalesce", "collation", "collect",
  42. "completion", "condition", "connect", "connection", "constraints",
  43. "constructor", "continue", "convert", "corr", "corresponding", "count",
  44. "covar_pop", "covar_samp", "cube", "cume_dist", "current",
  45. "current_default_transform_group", "current_path", "current_role",
  46. "current_transform_group_for_type", "current_user", "cursor", "cycle", "data",
  47. "date", "day", "deallocate", "dec", "decimal", "declare", "dense_rank",
  48. "depth", "deref", "describe", "descriptor", "destroy", "destructor",
  49. "deterministic", "diagnostics", "dictionary", "disconnect", "do", "domain",
  50. "double", "dynamic", "element", "end-exec", "equals", "every", "exception",
  51. "exec", "execute", "exp", "external", "extract", "false", "fetch", "filter",
  52. "first", "float", "floor", "found", "free", "freeze", "function", "fusion",
  53. "general", "get", "global", "go", "goto", "grant", "grouping", "hold", "host",
  54. "hour", "identity", "ilike", "indicator", "initialize", "inout", "input",
  55. "insensitive", "int", "integer", "intersection", "interval", "isolation",
  56. "iterate", "language", "large", "last", "lateral", "leading", "less", "level",
  57. "ln", "local", "localtime", "localtimestamp", "locator", "lower", "map", "max",
  58. "member", "merge", "method", "min", "minute", "mod", "modifies", "modify",
  59. "module", "month", "multiset", "names", "national", "nchar", "nclob", "new",
  60. "next", "none", "normalize", "nullif", "numeric", "object", "octet_length",
  61. "off", "old", "only", "open", "operation", "option", "ordinality", "out",
  62. "output", "over", "overlaps", "overlay", "pad", "parameter", "parameters",
  63. "partial", "partition", "path", "percentile_cont", "percentile_disc",
  64. "percent_rank", "placing", "position", "postfix", "power", "precision",
  65. "prefix", "preorder", "prepare", "preserve", "prior", "privileges",
  66. "procedure", "public", "range", "rank", "read", "reads", "real", "recursive",
  67. "ref", "referencing", "regr_avgx", "regr_avgy", "regr_count", "regr_intercept",
  68. "regr_r2", "regr_slope", "regr_sxx", "regr_sxy", "regr_syy", "relative",
  69. "result", "return", "returning", "returns", "revoke", "role", "rollup",
  70. "routine", "rows", "row_number", "schema", "scope", "scroll", "search",
  71. "second", "section", "sensitive", "sequence", "session", "session_user",
  72. "sets", "similar", "size", "smallint", "some", "space", "specific",
  73. "specifictype", "sql", "sqlcode", "sqlerror", "sqlexception", "sqlstate",
  74. "sqlwarning", "sqrt", "start", "state", "statement", "static", "stddev_pop",
  75. "stddev_samp", "structure", "submultiset", "substring", "sum", "symmetric",
  76. "system", "system_user", "tablesample", "terminate", "than", "time",
  77. "timestamp", "timezone_hour", "timezone_minute", "trailing", "translate",
  78. "translation", "treat", "trim", "true", "uescape", "under", "unknown",
  79. "unnest", "upper", "usage", "user", "value", "varchar", "variable", "varying",
  80. "var_pop", "var_samp", "verbose", "whenever", "width_bucket", "window", "with",
  81. "within", "without", "work", "write", "xml", "xmlagg", "xmlattributes",
  82. "xmlbinary", "xmlcomment", "xmlconcat", "xmlelement", "xmlforest",
  83. "xmlnamespaces", "xmlparse", "xmlpi", "xmlroot", "xmlserialize", "year", "zone"
  84. ]
  85. postgis_keywords = []
  86. # functions
  87. functions = [
  88. "coalesce",
  89. "nullif", "quote", "random",
  90. "replace", "soundex"
  91. ]
  92. operators = [
  93. ' AND ', ' OR ', '||', ' < ', ' <= ', ' > ', ' >= ', ' = ', ' <> ', ' IS ', ' IS NOT ', ' IN ', ' LIKE ', ' GLOB ', ' MATCH ', ' REGEXP '
  94. ]
  95. math_functions = [
  96. # SQL math functions
  97. "Abs", "ACos", "ASin", "ATan", "Cos", "Cot", "Degrees", "Exp", "Floor", "Log", "Log2",
  98. "Log10", "Pi", "Radians", "Round", "Sign", "Sin", "Sqrt", "StdDev_Pop", "StdDev_Samp", "Tan",
  99. "Var_Pop", "Var_Samp"]
  100. string_functions = ["Length", "Lower", "Upper", "Like", "Trim", "LTrim", "RTrim", "Replace", "Substr"]
  101. aggregate_functions = [
  102. "Max", "Min", "Avg", "Count", "Sum", "Group_Concat", "Total", "Var_Pop", "Var_Samp", "StdDev_Pop", "StdDev_Samp"
  103. ]
  104. postgis_functions = [ # from http://www.postgis.org/docs/reference.html
  105. # 7.1. PostgreSQL PostGIS Types
  106. "*box2d", "*box3d", "*box3d_extent", "*geometry", "*geometry_dump", "*geography",
  107. # 7.2. Management Functions
  108. "*addgeometrycolumn", "*dropgeometrycolumn", "*dropgeometrytable", "*postgis_full_version",
  109. "*postgis_geos_version", "*postgis_libxml_version", "*postgis_lib_build_date",
  110. "*postgis_lib_version", "*postgis_proj_version", "*postgis_scripts_build_date",
  111. "*postgis_scripts_installed", "*postgis_scripts_released", "*postgis_uses_stats", "*postgis_version",
  112. "*populate_geometry_columns", "*probe_geometry_columns", "*updategeometrysrid",
  113. # 7.3. Geometry Constructors
  114. "*ST_bdpolyfromtext", "*ST_bdmpolyfromtext", "*ST_geogfromtext", "*ST_geographyfromtext",
  115. "*ST_geogfromwkb", "*ST_geomcollfromtext", "*ST_geomfromewkb", "*ST_geomfromewkt",
  116. "*ST_geometryfromtext", "*ST_geomfromgml", "*ST_geomfromkml", "*ST_gmltosql", "*ST_geomfromtext",
  117. "*ST_geomfromwkb", "*ST_linefrommultipoint", "*ST_linefromtext", "*ST_linefromwkb",
  118. "*ST_linestringfromwkb", "*ST_makebox2d", "*ST_makebox3d", "ST_MakeLine", "*ST_makeenvelope",
  119. "ST_MakePolygon", "ST_MakePoint", "ST_MakePointM", "*ST_MLinefromtext", "*ST_mpointfromtext",
  120. "*ST_mpolyfromtext", "ST_Point", "*ST_pointfromtext", "*ST_pointfromwkb", "ST_Polygon",
  121. "*ST_polygonfromtext", "*ST_wkbtosql", "*ST_wkttosql",
  122. # 7.4. Geometry Accessors
  123. "GeometryType", "ST_Boundary", "*ST_coorddim", "ST_Dimension", "ST_EndPoint", "ST_Envelope",
  124. "ST_ExteriorRing", "ST_GeometryN", "ST_GeometryType", "ST_InteriorRingN", "ST_isClosed",
  125. "ST_isEmpty", "ST_isRing", "ST_isSimple", "ST_isValid", "ST_isValidReason", "ST_M", "ST_NDims",
  126. "ST_NPoints", "ST_NRings", "ST_NumGeometries", "ST_NumInteriorrings", "ST_NumInteriorring",
  127. "ST_NumPoints", "ST_PointN", "ST_Srid", "ST_StartPoint", "ST_Summary", "ST_X", "ST_Y", "ST_Z",
  128. "*ST_zmflag",
  129. # 7.5. Geometry Editors
  130. "ST_AddPoint", "ST_Affine", "ST_Force2D", "*ST_Force3D", "*ST_Force3dZ", "*ST_Force3DM",
  131. "*ST_Force_4d", "*ST_force_collection", "*ST_forcerhr", "*ST_linemerge", "*ST_collectionextract",
  132. "ST_Multi", "*ST_removepoint", "*ST_reverse", "*ST_rotate", "*ST_rotatex", "*ST_rotatey",
  133. "*ST_rotatez", "*ST_scale", "*ST_segmentize", "*ST_setpoint", "ST_SetSrid", "ST_SnapToGrid",
  134. "ST_Transform", "ST_Translate", "*ST_transscale",
  135. # 7.6. Geometry Outputs
  136. "*ST_asbinary", "*ST_asewkb", "*ST_asewkt", "*ST_asgeojson", "*ST_asgml", "*ST_ashexewkb", "*ST_askml",
  137. "*ST_assvg", "*ST_geohash", "ST_Astext",
  138. # 7.7. Operators
  139. # 7.8. Spatial Relationships and Measurements
  140. "ST_Area", "ST_Azimuth", "ST_Centroid", "ST_ClosestPoint", "ST_Contains", "ST_ContainsProperly",
  141. "ST_Covers", "ST_CoveredBy", "ST_Crosses", "*ST_linecrossingdirection", "ST_Cisjoint",
  142. "ST_Distance", "*ST_hausdorffdistance", "*ST_maxdistance", "ST_Distance_Sphere",
  143. "ST_Distance_Spheroid", "*ST_DFullyWithin", "ST_DWithin", "ST_Equals", "*ST_hasarc",
  144. "ST_Intersects", "ST_Length", "*ST_Length2d", "*ST_length3d", "ST_Length_Spheroid",
  145. "*ST_length2d_spheroid", "*ST_length3d_spheroid", "*ST_longestline", "*ST_orderingequals",
  146. "ST_Overlaps", "*ST_perimeter", "*ST_perimeter2d", "*ST_perimeter3d", "ST_PointOnSurface",
  147. "ST_Relate", "ST_ShortestLine", "ST_Touches", "ST_Within",
  148. # 7.9. Geometry Processing Functions
  149. "ST_Buffer", "ST_BuildArea", "ST_Collect", "ST_ConvexHull", "*ST_curvetoline", "ST_Difference",
  150. "ST_Dump", "*ST_dumppoints", "*ST_dumprings", "ST_Intersection", "*ST_linetocurve", "*ST_memunion",
  151. "*ST_minimumboundingcircle", "*ST_polygonize", "*ST_shift_longitude", "ST_Simplify",
  152. "ST_SimplifyPreserveTopology", "ST_SymDifference", "ST_Union",
  153. # 7.10. Linear Referencing
  154. "ST_Line_Interpolate_Point", "ST_Line_Locate_Point", "ST_Line_Substring",
  155. "*ST_locate_along_measure", "*ST_locate_between_measures", "*ST_locatebetweenelevations",
  156. "*ST_addmeasure",
  157. # 7.11. Long Transactions Support
  158. "*addauth", "*checkauth", "*disablelongtransactions", "*enablelongtransactions", "*lockrow",
  159. "*unlockrows",
  160. # 7.12. Miscellaneous Functions
  161. "*ST_accum", "*box2d", "*box3d", "*ST_estimated_extent", "*ST_expand", "ST_Extent", "*ST_extent3d",
  162. "*find_srid", "*ST_mem_size", "*ST_point_inside_circle", "ST_XMax", "ST_XMin", "ST_YMax", "ST_YMin",
  163. "ST_ZMax", "ST_ZMin",
  164. # 7.13. Exceptional Functions
  165. "*postgis_addbbox", "*postgis_dropbbox", "*postgis_hasbbox",
  166. # Raster functions
  167. "AddRasterConstraints", "DropRasterConstraints", "AddOverviewConstraints", "DropOverviewConstraints",
  168. "PostGIS_GDAL_Version", "PostGIS_Raster_Lib_Build_Date", "PostGIS_Raster_Lib_Version", "ST_GDALDrivers",
  169. "UpdateRasterSRID", "ST_CreateOverview", "ST_AddBand", "ST_AsRaster", "ST_Band", "ST_MakeEmptyCoverage",
  170. "ST_MakeEmptyRaster", "ST_Tile", "ST_Retile", "ST_FromGDALRaster", "ST_GeoReference", "ST_Height",
  171. "ST_IsEmpty", "ST_MemSize", "ST_MetaData", "ST_NumBands", "ST_PixelHeight", "ST_PixelWidth", "ST_ScaleX",
  172. "ST_ScaleY", "ST_RasterToWorldCoord", "ST_RasterToWorldCoordX", "ST_RasterToWorldCoordY", "ST_Rotation",
  173. "ST_SkewX", "ST_SkewY", "ST_SRID", "ST_Summary", "ST_UpperLeftX", "ST_UpperLeftY", "ST_Width",
  174. "ST_WorldToRasterCoord", "ST_WorldToRasterCoordX", "ST_WorldToRasterCoordY", "ST_BandMetaData",
  175. "ST_BandNoDataValue", "ST_BandIsNoData", "ST_BandPath", "ST_BandFileSize", "ST_BandFileTimestamp",
  176. "ST_BandPixelType", "ST_MinPossibleValue", "ST_HasNoBand", "ST_PixelAsPolygon", "ST_PixelAsPolygons",
  177. "ST_PixelAsPoint", "ST_PixelAsPoints", "ST_PixelAsCentroid", "ST_PixelAsCentroids", "ST_Value",
  178. "ST_NearestValue", "ST_Neighborhood", "ST_SetValue", "ST_SetValues", "ST_DumpValues", "ST_PixelOfValue",
  179. "ST_SetGeoReference", "ST_SetRotation", "ST_SetScale", "ST_SetSkew", "ST_SetSRID", "ST_SetUpperLeft",
  180. "ST_Resample", "ST_Rescale", "ST_Reskew", "ST_SnapToGrid", "ST_Resize", "ST_Transform",
  181. "ST_SetBandNoDataValue", "ST_SetBandIsNoData", "ST_SetBandPath", "ST_SetBandIndex", "ST_Count",
  182. "ST_CountAgg", "ST_Histogram", "ST_Quantile", "ST_SummaryStats", "ST_SummaryStatsAgg", "ST_ValueCount",
  183. "ST_RastFromWKB", "ST_RastFromHexWKB", "ST_AsBinary", "ST_AsWKB", "ST_AsHexWKB", "ST_AsGDALRaster",
  184. "ST_AsJPEG", "ST_AsPNG", "ST_AsTIFF", "ST_Clip", "ST_ColorMap", "ST_Grayscale", "ST_Intersection",
  185. "ST_MapAlgebra", "ST_MapAlgebraExpr", "ST_MapAlgebraFct", "ST_MapAlgebraFctNgb", "ST_Reclass", "ST_Union",
  186. "ST_Distinct4ma", "ST_InvDistWeight4ma", "ST_Max4ma", "ST_Mean4ma", "ST_Min4ma", "ST_MinDist4ma",
  187. "ST_Range4ma", "ST_StdDev4ma", "ST_Sum4ma", "ST_Aspect", "ST_HillShade", "ST_Roughness", "ST_Slope",
  188. "ST_TPI", "ST_TRI",
  189. ]
  190. # constants
  191. constants = ["null", "false", "true"]
  192. postgis_constants = []
  193. def getSqlDictionary(spatial=True):
  194. def strip_star(s):
  195. if s[0] == '*':
  196. return s.lower()[1:]
  197. else:
  198. return s.lower()
  199. k, c, f = list(keywords), list(constants), list(functions)
  200. if spatial:
  201. k += postgis_keywords
  202. f += postgis_functions
  203. c += postgis_constants
  204. return {'keyword': list(map(strip_star, k)), 'constant': list(map(strip_star, c)), 'function': list(map(strip_star, f))}
  205. def getQueryBuilderDictionary():
  206. # concat functions
  207. def ff(l):
  208. return [s for s in l if s[0] != '*']
  209. def add_paren(l):
  210. return [s + "(" for s in l]
  211. foo = sorted(add_paren(ff(list(set.union(set(functions), set(postgis_functions))))))
  212. m = sorted(add_paren(ff(math_functions)))
  213. agg = sorted(add_paren(ff(aggregate_functions)))
  214. op = ff(operators)
  215. s = sorted(add_paren(ff(string_functions)))
  216. return {'function': foo, 'math': m, 'aggregate': agg, 'operator': op, 'string': s}