-
Notifications
You must be signed in to change notification settings - Fork 2
/
SqlGeneratorMicrosoft.scala
218 lines (184 loc) · 7.75 KB
/
SqlGeneratorMicrosoft.scala
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
/*
* Copyright 2022 ABSA Group Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package za.co.absa.pramen.core.sql
import za.co.absa.pramen.api.sql.SqlGeneratorBase.{needsEscaping, validateIdentifier}
import za.co.absa.pramen.api.sql.{SqlColumnType, SqlConfig, SqlGenerator}
import za.co.absa.pramen.core.utils.MutableStack
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import scala.collection.mutable.ListBuffer
class SqlGeneratorMicrosoft(sqlConfig: SqlConfig) extends SqlGenerator {
private val dateFormatterApp = DateTimeFormatter.ofPattern(sqlConfig.dateFormatApp)
private val isIso = sqlConfig.dateFormatApp.toLowerCase.startsWith("yyyy-mm-dd")
// 23 is "yyyy-MM-dd", see https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
private val isoFormatMsSqlRef = 23
val beginEndEscapeChars: (Char, Char) = ('[', ']')
val escapeChar2 = '\"'
override def getDtable(sql: String): String = {
if (sql.exists(_ == ' ')) {
getAliasExpression(s"($sql)", "tbl")
} else {
sql
}
}
def getCountQuery(tableName: String): String = {
s"SELECT ${getAliasExpression("COUNT(*)", "CNT")} FROM ${escape(tableName)} WITH (NOLOCK)"
}
def getCountQuery(tableName: String, infoDateBegin: LocalDate, infoDateEnd: LocalDate): String = {
val where = getWhere(infoDateBegin, infoDateEnd)
s"SELECT ${getAliasExpression("COUNT(*)", "CNT")} FROM ${escape(tableName)} WITH (NOLOCK) WHERE $where"
}
override def getCountQueryForSql(filteredSql: String): String = {
s"SELECT COUNT(*) FROM ($filteredSql) AS query"
}
override def getDataQuery(tableName: String, columns: Seq[String], limit: Option[Int]): String = {
s"SELECT ${getLimit(limit)}${columnExpr(columns)} FROM ${escape(tableName)} WITH (NOLOCK)"
}
override def getDataQuery(tableName: String, infoDateBegin: LocalDate, infoDateEnd: LocalDate, columns: Seq[String], limit: Option[Int]): String = {
val where = getWhere(infoDateBegin, infoDateEnd)
s"SELECT ${getLimit(limit)}${columnExpr(columns)} FROM ${escape(tableName)} WITH (NOLOCK) WHERE $where"
}
override def getWhere(dateBegin: LocalDate, dateEnd: LocalDate): String = {
val dateBeginLit = getDateLiteral(dateBegin)
val dateEndLit = getDateLiteral(dateEnd)
val infoDateColumnAdjusted = if (sqlConfig.infoDateType == SqlColumnType.DATETIME) {
s"CONVERT(DATE, $infoDateColumn, $isoFormatMsSqlRef)"
} else if (sqlConfig.infoDateType == SqlColumnType.STRING && isIso) {
s"TRY_CONVERT(DATE, $infoDateColumn, $isoFormatMsSqlRef)"
} else {
infoDateColumn
}
if (dateBeginLit == dateEndLit) {
s"$infoDateColumnAdjusted = $dateBeginLit"
} else {
s"$infoDateColumnAdjusted >= $dateBeginLit AND $infoDateColumnAdjusted <= $dateEndLit"
}
}
override def getDateLiteral(date: LocalDate): String = {
sqlConfig.infoDateType match {
case SqlColumnType.DATE =>
val dateStr = DateTimeFormatter.ISO_LOCAL_DATE.format(date)
s"CONVERT(DATE, '$dateStr', $isoFormatMsSqlRef)"
case SqlColumnType.DATETIME =>
val dateStr = DateTimeFormatter.ISO_LOCAL_DATE.format(date)
s"CONVERT(DATE, '$dateStr', $isoFormatMsSqlRef)"
case SqlColumnType.STRING =>
if (isIso) {
val dateStr = DateTimeFormatter.ISO_LOCAL_DATE.format(date)
s"CONVERT(DATE, '$dateStr', $isoFormatMsSqlRef)"
} else {
val dateStr = dateFormatterApp.format(date)
s"'$dateStr'"
}
case SqlColumnType.NUMBER =>
val dateStr = dateFormatterApp.format(date)
s"$dateStr"
}
}
override def getAliasExpression(expression: String, alias: String): String = {
s"$expression AS ${escape(alias)}"
}
override def quote(identifier: String): String = {
validateIdentifier(identifier)
splitComplexIdentifier(identifier).map(quoteSingleIdentifier).mkString(".")
}
override def escape(identifier: String): String = {
if (needsEscaping(sqlConfig.identifierQuotingPolicy, identifier)) {
quote(identifier)
} else {
identifier
}
}
private def getLimit(limit: Option[Int]): String = {
limit.map(n => s"TOP $n ").getOrElse("")
}
private def columnExpr(columns: Seq[String]): String = {
if (columns.isEmpty) {
"*"
} else {
columns.map(col => escape(col)).mkString(", ")
}
}
private def infoDateColumn: String = {
escape(sqlConfig.infoDateColumn)
}
private def quoteSingleIdentifier(identifier: String): String = {
val (escapeBegin, escapeEnd) = beginEndEscapeChars
if (
(identifier.startsWith(s"$escapeBegin") && identifier.endsWith(s"$escapeEnd")) ||
(identifier.startsWith(s"$escapeChar2") && identifier.endsWith(s"$escapeChar2"))
) {
identifier
} else {
s"$escapeBegin$identifier$escapeEnd"
}
}
private[core] def splitComplexIdentifier(identifier: String): Seq[String] = {
val trimmedIdentifier = identifier.trim
if (trimmedIdentifier.isEmpty) {
throw new IllegalArgumentException(f"Found an empty table name or column name ('$identifier').")
}
val (escapeBegin1, escapeEnd1) = beginEndEscapeChars
val output = new ListBuffer[String]
val curColumn = new StringBuffer()
val len = trimmedIdentifier.length
val nestingChar = new MutableStack[Char]
var i = 0
while (i < len) {
val c = trimmedIdentifier(i)
val nextChar = if (i == len - 1) ' ' else trimmedIdentifier(i + 1)
if (nestingChar.isEmpty && c == '.') {
output += curColumn.toString
curColumn.setLength(0)
} else {
curColumn.append(c)
}
if (c == escapeChar2) {
if (curColumn.length() > 1 && i < len - 1 && nextChar != '.')
throw new IllegalArgumentException(f"Invalid character '$escapeChar2' in the identifier '$identifier', position $i.")
nestingChar.pop() match {
case Some(ch) =>
if (ch != escapeChar2)
throw new IllegalArgumentException(f"Invalid character '$escapeChar2' in the identifier '$identifier', position $i.")
case None =>
nestingChar.push(escapeChar2)
}
} else if (c == escapeBegin1) {
if (nestingChar.nonEmpty && nestingChar.peek() == escapeChar2) {
throw new IllegalArgumentException(f"Invalid character '$escapeChar2' in the identifier '$identifier', position $i.")
}
if (curColumn.length() > 1 && i < len - 1 && nextChar != '.')
throw new IllegalArgumentException(f"Invalid character '$escapeBegin1' in the identifier '$identifier', position $i.")
nestingChar.push(escapeBegin1)
} else if (c == escapeEnd1) {
nestingChar.pop() match {
case Some(ch) =>
if (ch == escapeChar2)
throw new IllegalArgumentException(f"Found not matching '$escapeChar2' in the identifier '$identifier'.")
case None =>
throw new IllegalArgumentException(f"Found not matching '$escapeEnd1' in the identifier '$identifier'.")
}
}
i += 1
}
nestingChar.pop().foreach{ch =>
throw new IllegalArgumentException(f"Found not matching '$ch' in the identifier '$identifier'.")
}
if (curColumn.toString.nonEmpty)
output += curColumn.toString
output.toSeq
}
}