File: SqlServerSqlProvider.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (285 lines) | stat: -rw-r--r-- 11,273 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#region MIT license
// 
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// 
#endregion

using System;
using System.Linq;
using System.Collections.Generic;

using DbLinq.Vendor.Implementation;

using DbLinq.Data.Linq.Sql;
using DbLinq.Data.Linq.Sugar.Expressions;

namespace DbLinq.SqlServer
{
#if !MONO_STRICT
    public
#endif
    class SqlServerSqlProvider : SqlProvider
    {
        public override ExpressionTranslator GetTranslator()
        {
            return new SqlServerExpressionTranslator();
        }

        protected override char SafeNameStartQuote { get { return '['; } }
        protected override char SafeNameEndQuote { get { return ']'; } }

        /// <summary>
        /// Returns a table alias
        /// Ensures about the right case
        /// </summary>
        /// <param name="table"></param>
        /// <param name="alias"></param>
        /// <returns></returns>
        public override string GetTableAsAlias(string table, string alias)
        {
            return string.Format("{0} AS {1}", GetTable(table), GetTableAlias(alias));
        }

        /// <summary>
        /// Returns a table alias
        /// Ensures about the right case
        /// </summary>
        /// <param name="table"></param>
        /// <param name="alias"></param>
        /// <returns></returns>
        public override string GetSubQueryAsAlias(string subquery, string alias)
        {
            return string.Format("({0}) AS {1}", subquery, GetTableAlias(alias));
        }

        public override SqlStatement GetLiteral(bool literal)
        {
            if (literal)
                return "1";
            return "0";
        }

        public override SqlStatement GetLiteral(DateTime literal)
        {
            return "'" + literal.ToString("o").Substring(0,23) + "'";
        }

        public override string GetParameterName(string nameBase)
        {
            return string.Format("@{0}", nameBase);
        }

        public override SqlStatement GetLiteralLimit(SqlStatement select, SqlStatement limit)
        {
            var trimSelect = "SELECT ";
            if (select.Count > 0 && select[0].Sql.StartsWith(trimSelect))
            {
                var selectBuilder = new SqlStatementBuilder(select);
                var remaining = select[0].Sql.Substring(trimSelect.Length);
                selectBuilder.Parts[0] = new SqlLiteralPart(remaining);
                return SqlStatement.Format("SELECT TOP ({0}) {1}", limit, selectBuilder.ToSqlStatement());
            }
            throw new ArgumentException("S0051: Unknown select format");
        }

        public override SqlStatement GetLiteralLimit(SqlStatement select, SqlStatement limit, SqlStatement offset, SqlStatement offsetAndLimit)
        {
            var from    = "FROM ";
            var orderBy = "ORDER BY ";
            var selectK = "SELECT ";
            int fromIdx     = select[0].Sql.IndexOf(from);
            int orderByIdx  = select[0].Sql.IndexOf(orderBy);

            if (fromIdx < 0)
                throw new ArgumentException("S0051: Unknown select format: " + select[0].Sql);

            string orderByClause = null;
            string sourceClause = null;
            if (orderByIdx >= 0)
            {
                orderByClause = select[0].Sql.Substring(orderByIdx);
                sourceClause = select[0].Sql.Substring(fromIdx, orderByIdx - fromIdx);
            }
            else
            {
                orderByClause = "ORDER BY " + select[0].Sql.Substring(selectK.Length, fromIdx - selectK.Length);
                sourceClause = select[0].Sql.Substring(fromIdx);
            }

            var selectFieldsClause = select[0].Sql.Substring(0, fromIdx);

            return SqlStatement.Format(
                "SELECT *{0}" +
                "FROM ({0}" +
                "    {1},{0}" +
                "    ROW_NUMBER() OVER({2}) AS [__ROW_NUMBER]{0}" +
                "    {3}" +
                "    ) AS [t0]{0}" +
                "WHERE [__ROW_NUMBER] BETWEEN {4}+1 AND {4}+{5}{0}" +
                "ORDER BY [__ROW_NUMBER]",
                NewLine, selectFieldsClause, orderByClause, sourceClause, offset, limit);
        }

        protected override SqlStatement GetLiteralDateDiff(SqlStatement dateA, SqlStatement dateB)
        {
            return SqlStatement.Format("(CONVERT(BigInt,DATEDIFF(DAY, {0}, {1}))) * 86400000 +" //diffierence in milliseconds regards days
                     + "DATEDIFF(MILLISECOND, "

                                // (DateA-DateB) in days +DateB = difference in time
                                + @"DATEADD(DAY, 
                                      DATEDIFF(DAY, {0}, {1})
                                      ,{0})"

                                + ",{1})", dateB, dateA);

            //this trick is needed in sqlserver since DATEDIFF(MILLISECONDS,{0},{1}) usually crhases in the database engine due an overflow:
            //System.Data.SqlClient.SqlException : Difference of two datetime columns caused overflow at runtime.
        }

        protected override SqlStatement GetLiteralDateTimePart(SqlStatement dateExpression, SpecialExpressionType operationType)
        {
            return SqlStatement.Format("DATEPART({0},{1})", operationType.ToString().ToUpper(), dateExpression);
        }

        protected override SqlStatement GetLiteralMathPow(SqlStatement p, SqlStatement p_2)
        {
            return SqlStatement.Format("POWER({0},{1})", p, p_2);
        }

        protected override SqlStatement GetLiteralMathLog(SqlStatement p, SqlStatement p_2)
        {
            return SqlStatement.Format("(LOG({0})/LOG({1}))", p, p_2);
        }

        protected override SqlStatement GetLiteralMathLn(SqlStatement p)
        {
            return GetLiteralMathLog(p, string.Format("{0}", Math.E));
        }

        protected override SqlStatement GetLiteralStringLength(SqlStatement a)
        {
            return SqlStatement.Format("LEN({0})", a);
        }

        protected override SqlStatement GetLiteralSubString(SqlStatement baseString, SqlStatement startIndex, SqlStatement count)
        {
            //in standard sql base string index is 1 instead 0
            return SqlStatement.Format("SUBSTRING({0}, {1}, {2})", baseString, startIndex, count);
        }

        protected override SqlStatement GetLiteralSubString(SqlStatement baseString, SqlStatement startIndex)
        {
            return GetLiteralSubString(baseString, startIndex, GetLiteralStringLength(baseString));
        }

        protected override SqlStatement GetLiteralTrim(SqlStatement a)
        {
            return SqlStatement.Format("RTRIM(LTRIM({0}))", a);
        }

        protected override SqlStatement GetLiteralStringConcat(SqlStatement a, SqlStatement b)
        {
            return SqlStatement.Format("{0} + {1}", a.Replace("sql_variant", "varchar", false), b.Replace("sql_variant", "varchar", false));
        }

        protected override SqlStatement GetLiteralStringToLower(SqlStatement a)
        {
            return SqlStatement.Format("LOWER({0})", a);
        }

        protected override SqlStatement GetLiteralStringToUpper(SqlStatement a)
        {
            return SqlStatement.Format("UPPER({0})", a);
        }

        protected override SqlStatement GetLiteralStringIndexOf(SqlStatement baseString, SqlStatement searchString)
        {
            return GetLiteralSubtract(SqlStatement.Format("CHARINDEX({0},{1})", searchString, baseString), "1");
        }

        protected override SqlStatement GetLiteralStringIndexOf(SqlStatement baseString, SqlStatement searchString, SqlStatement startIndex)
        {
            return GetLiteralSubtract(SqlStatement.Format("CHARINDEX({0},{1},{2})", searchString, baseString, startIndex), "1");
        }

        protected override SqlStatement GetLiteralStringIndexOf(SqlStatement baseString, SqlStatement searchString, SqlStatement startIndex, SqlStatement count)
        {
            return GetLiteralSubtract(SqlStatement.Format("CHARINDEX({0},{1},{2})", searchString, GetLiteralSubString(baseString, "1", GetLiteralStringConcat(count, startIndex)), startIndex), "1");
        }

        //http://msdn.microsoft.com/en-us/library/4e5xt97a(VS.71).aspx
        public static readonly Dictionary<Type, string> typeMapping = new Dictionary<Type, string>
        {
            {typeof(int),"int"},
            {typeof(uint),"int"},

            {typeof(long),"bigint"},
            {typeof(ulong),"bigint"},

            {typeof(float),"float"}, //TODO: could be float or real. check ranges.
            {typeof(double),"float"}, //TODO: could be float or real. check ranges.
            
            {typeof(decimal),"numeric"},

            {typeof(short),"tinyint"},
            {typeof(ushort),"tinyint"},

            {typeof(bool),"bit"},

            // trunk? They could be: varchar, char,nchar, ntext,text... it should be the most flexible string type. TODO: check wich of them is better.
            {typeof(string),"varchar"}, 
            {typeof(char[]),"varchar"},

            {typeof(char),"char"},

            {typeof(DateTime),"datetime"},
            {typeof(Guid),"uniqueidentifier"}

            // there are more types: timestamps, images ... TODO: check what is the official behaviour
        };

        public override SqlStatement GetLiteralConvert(SqlStatement a, Type type)
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                type = type.GetGenericArguments().First();

            if (type.IsValueType && a[0].Sql.StartsWith("@"))
                return a;

            SqlStatement sqlTypeName;
            if (typeMapping.ContainsKey(type))
                sqlTypeName = typeMapping[type];
            else
                sqlTypeName = "sql_variant";

            return SqlStatement.Format("CONVERT({0},{1})", sqlTypeName, a);
        }

        public override string GetColumn(string table, string column)
        {
            if (column != "*")
                return base.GetColumn(table, column);
            return "*";
        }
    }
}