PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/Signum.Engine/Engine/SqlUtils.cs

https://github.com/mutharasank/framework
C# | 269 lines | 260 code | 9 blank | 0 comment | 6 complexity | f04a77846f8cabfc98b86ff9c56789f2 MD5 | raw file
Possible License(s): GPL-3.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Signum.Utilities;
  6. using System.Text.RegularExpressions;
  7. using Signum.Engine.SchemaInfoTables;
  8. using Signum.Engine.Maps;
  9. namespace Signum.Engine
  10. {
  11. public static class SqlUtils
  12. {
  13. static HashSet<string> Keywords =
  14. @"ADD
  15. ALL
  16. ALTER
  17. AND
  18. ANY
  19. AS
  20. ASC
  21. AUTHORIZATION
  22. AVG
  23. BACKUP
  24. BEGIN
  25. BETWEEN
  26. BREAK
  27. BROWSE
  28. BULK
  29. BY
  30. CASCADE
  31. CASE
  32. CHECK
  33. CHECKPOINT
  34. CLOSE
  35. CLUSTERED
  36. COALESCE
  37. COLUMN
  38. COMMIT
  39. COMMITTED
  40. COMPUTE
  41. CONFIRM
  42. CONSTRAINT
  43. CONTAINS
  44. CONTAINSTABLE
  45. CONTINUE
  46. CONTROLROW
  47. CONVERT
  48. COUNT
  49. CREATE
  50. CROSS
  51. CURRENT
  52. CURRENT_DATE
  53. CURRENT_TIME
  54. CURRENT_TIMESTAMP
  55. CURRENT_USER
  56. CURSOR
  57. DATABASE
  58. DBCC
  59. DEALLOCATE
  60. DECLARE
  61. DEFAULT
  62. DELETE
  63. DENY
  64. DESC
  65. DISK
  66. DISTINCT
  67. DISTRIBUTED
  68. DOUBLE
  69. DROP
  70. DUMMY
  71. DUMP
  72. ELSE
  73. END
  74. ERRLVL
  75. ERROREXIT
  76. ESCAPE
  77. EXCEPT
  78. EXEC
  79. EXECUTE
  80. EXISTS
  81. EXIT
  82. FETCH
  83. FILE
  84. FILLFACTOR
  85. FLOPPY
  86. FOR
  87. FOREIGN
  88. FREETEXT
  89. FREETEXTTABLE
  90. FROM
  91. FULL
  92. GOTO
  93. GRANT
  94. GROUP
  95. HAVING
  96. HOLDLOCK
  97. IDENTITY
  98. IDENTITY_INSERT
  99. IDENTITYCOL
  100. IF
  101. IN
  102. INDEX
  103. INNER
  104. INSERT
  105. INTERSECT
  106. INTO
  107. IS
  108. ISOLATION
  109. JOIN
  110. KEY
  111. KILL
  112. LEFT
  113. LEVEL
  114. LIKE
  115. LINENO
  116. LOAD
  117. MAX
  118. MIN
  119. MIRROREXIT
  120. NATIONAL
  121. NOCHECK
  122. NONCLUSTERED
  123. NOT
  124. NULL
  125. NULLIF
  126. OF
  127. OFF
  128. OFFSETS
  129. ON
  130. ONCE
  131. ONLY
  132. OPEN
  133. OPENDATASOURCE
  134. OPENQUERY
  135. OPENROWSET
  136. OPTION
  137. OR
  138. ORDER
  139. OUTER
  140. OVER
  141. PERCENT
  142. PERM
  143. PERMANENT
  144. PIPE
  145. PLAN
  146. PRECISION
  147. PREPARE
  148. PRIMARY
  149. PRINT
  150. PRIVILEGES
  151. PROC
  152. PROCEDURE
  153. PROCESSEXIT
  154. PUBLIC
  155. RAISERROR
  156. READ
  157. READTEXT
  158. RECONFIGURE
  159. REFERENCES
  160. REPEATABLE
  161. REPLICATION
  162. RESTORE
  163. RESTRICT
  164. RETURN
  165. REVOKE
  166. RIGHT
  167. ROLLBACK
  168. ROWCOUNT
  169. ROWGUIDCOL
  170. RULE
  171. SAVE
  172. SCHEMA
  173. SELECT
  174. SERIALIZABLE
  175. SESSION_USER
  176. SET
  177. SETUSER
  178. SHUTDOWN
  179. SOME
  180. STATISTICS
  181. SUM
  182. SYSTEM_USER
  183. TABLE
  184. TAPE
  185. TEMP
  186. TEMPORARY
  187. TEXTSIZE
  188. THEN
  189. TO
  190. TOP
  191. TRAN
  192. TRANSACTION
  193. TRIGGER
  194. TRUNCATE
  195. TSEQUAL
  196. UNCOMMITTED
  197. UNION
  198. UNIQUE
  199. UPDATE
  200. UPDATETEXT
  201. USE
  202. USER
  203. VALUES
  204. VARYING
  205. VIEW
  206. WAITFOR
  207. WHEN
  208. WHERE
  209. WHILE
  210. WITH
  211. WORK
  212. WRITETEXT".Lines().Select(a => a.Trim().ToUpperInvariant()).ToHashSet();
  213. public static string SqlScape(this string ident)
  214. {
  215. if (Keywords.Contains(ident.ToUpperInvariant()) || Regex.IsMatch(ident, @"-\d|[áéíóúàèìòùÁÉÍÓÚÀÈÌÒÙ]"))
  216. return "[" + ident + "]";
  217. return ident;
  218. }
  219. public static SqlPreCommand RemoveDuplicatedIndices()
  220. {
  221. var plainData = (from s in Database.View<SysSchemas>()
  222. from t in s.Tables()
  223. from ix in t.Indices()
  224. from ic in ix.IndexColumns()
  225. from c in t.Columns()
  226. where ic.column_id == c.column_id
  227. select new
  228. {
  229. table = new ObjectName(new SchemaName(null, s.name), t.name),
  230. index = ix.name,
  231. ix.is_unique,
  232. column = c.name,
  233. ic.is_descending_key,
  234. ic.is_included_column,
  235. ic.key_ordinal
  236. }).ToList();
  237. var tables = plainData.AgGroupToDictionary(a => a.table,
  238. gr => gr.AgGroupToDictionary(a => new { a.index, a.is_unique },
  239. gr2 => gr2.OrderBy(a => a.key_ordinal)
  240. .Select(a => a.column + (a.is_included_column ? "(K)" : "(I)") + (a.is_descending_key ? "(D)" : "(A)"))
  241. .ToString("|")));
  242. var result = tables.SelectMany(t =>
  243. t.Value.GroupBy(a => a.Value, a => a.Key)
  244. .Where(gr => gr.Count() > 1)
  245. .Select(gr =>
  246. {
  247. var best = gr.OrderByDescending(a => a.is_unique).ThenByDescending(a => a.index.StartsWith("IX")).ThenByDescending(a => a.index).First();
  248. return gr.Where(g => g != best)
  249. .Select(g => SqlBuilder.DropIndex(t.Key, g.index))
  250. .PreAnd(new SqlPreCommandSimple("-- DUPLICATIONS OF {0}".Formato(best.index))).Combine(Spacing.Simple);
  251. })
  252. ).Combine(Spacing.Double);
  253. if (result == null)
  254. return null;
  255. return SqlPreCommand.Combine(Spacing.Double,
  256. new SqlPreCommandSimple("use {0}".Formato(Connector.Current.DatabaseName())),
  257. result);
  258. }
  259. }
  260. }