Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CHARINDEX function for sqlserver #1675

Merged
merged 5 commits into from
May 4, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ class Trim<T : String?>(
override fun toQueryBuilder(queryBuilder: QueryBuilder): Unit = queryBuilder { append("TRIM(", expr, ")") }
}

/**
* Represents an SQL function that returns the index of the first occurrence of [char] in [expr] or 0
*/
class CharIndex<T : String?>(val expr: Expression<T>, val char: String) : Function<Int>(IntegerColumnType()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a more generic function called Position in PostgreSQL and MySQL
https://www.postgresql.org/docs/15/functions-string.html
https://dev.mysql.com/doc/refman/8.0/en/string-functions.html

I wonder if calling this Position and implementing it as CharIndex only for MSSQL would be a better option here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing that out!

Yeah, that makes sense. CharIndex seems to be specific to SQL server, while Position is used in 2 systems. Though I wonder if it even should be Locate, as it's used in MySQL, H2 and Maria DB.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. It seems that LOCATE() is the most generic, as it has also the third parameter of start position, that can be defaulted.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I renamed the function and added implementation for all supported dialects.
I wonder if all dialects are tested on PRs? If not how can I run tests for the remaining ones on CI?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK, all dialects are tested, unless you exclude them.

override fun toQueryBuilder(queryBuilder: QueryBuilder) =
currentDialect.functionProvider.charIndex(queryBuilder, expr, char)
}

// General-Purpose Aggregate Functions

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ fun <T : String?> Expression<T>.substring(start: Int, length: Int): Substring<T>
/** Removes the longest string containing only spaces from both ends of string expression. */
fun <T : String?> Expression<T>.trim(): Trim<T> = Trim(this)

/** Returns the index of the first occurrence of [char] in this string expression or 0 if it doesn't contain [char] */
fun <T : String?> Expression<T>.charIndex(char: String): CharIndex<T> = CharIndex(this, char)

// General-Purpose Aggregate Functions

/** Returns the minimum value of this expression across all non-null input values, or `null` if there are no non-null values. */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package org.jetbrains.exposed.sql.vendors

import org.jetbrains.exposed.exceptions.UnsupportedByDialectException
import org.jetbrains.exposed.exceptions.throwUnsupportedException
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.TransactionManager
import java.nio.ByteBuffer
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import kotlin.collections.HashMap
import kotlin.collections.LinkedHashSet

/**
* Provides definitions for all the supported SQL data types.
Expand Down Expand Up @@ -208,6 +207,21 @@ abstract class FunctionProvider {
append(")")
}

/**
* SQL function that returns the index of the first occurrence of the given substring [char]
* in the string expression [expr]
*
* @param queryBuilder Query builder to append the SQL function to.
* @param expr String expression to find the substring in.
* @param char: Substring to find
* @return index of the first occurrence of [char] in [expr] starting from 1 or 0 if [expr] doesn't contain [char]
*/
open fun <T : String?> charIndex(queryBuilder: QueryBuilder, expr: Expression<T>, char: String) {
throw UnsupportedByDialectException(
"There's no generic SQL for CHARINDEX. There must be vendor specific implementation.", currentDialect
)
}

// Pattern matching

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ internal object SQLServerFunctionProvider : FunctionProvider() {
}
}

override fun <T : String?> charIndex(queryBuilder: QueryBuilder, expr: Expression<T>, char: String) = queryBuilder {
append("CHARINDEX(\'", char, "\',", expr, ")")
}

override fun <T : String?> regexp(
expr1: Expression<T>,
pattern: Expression<String>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,42 @@ class FunctionsTests : DatabaseTestsBase() {
}
}

@Test
fun testCharIndex() {
withCitiesAndUsers(TestDB.values().asList().minus(TestDB.SQLSERVER)) { cities, _, _ ->
val charIndex = cities.name.charIndex("e")
val results = cities.slice(charIndex).selectAll().toList()

assertEquals(6, results[0][charIndex]) // St. Petersburg
assertEquals(0, results[1][charIndex]) // Munich
assertEquals(6, results[2][charIndex]) // Prague
}
}

@Test
fun testCharIndex02() {
withCitiesAndUsers(TestDB.values().asList().minus(TestDB.SQLSERVER)) { cities, _, _ ->
val charIndex = cities.name.charIndex("Peter")
val results = cities.slice(charIndex).selectAll().toList()

assertEquals(5, results[0][charIndex]) // St. Petersburg
assertEquals(0, results[1][charIndex]) // Munich
assertEquals(0, results[2][charIndex]) // Prague
}
}

@Test
fun testCharIndex03() {
withCitiesAndUsers(TestDB.values().asList().minus(TestDB.SQLSERVER)) { cities, _, _ ->
val charIndex = cities.name.charIndex("p")
val results = cities.slice(charIndex).selectAll().toList()

assertEquals(5, results[0][charIndex]) // St. Petersburg
assertEquals(0, results[1][charIndex]) // Munich
assertEquals(1, results[2][charIndex]) // Prague
}
}

@Test
fun testRandomFunction01() {
val t = DMLTestsData.Cities
Expand Down