Skip to content

Implementation of FreeText translation for SqlServer - #10408

Closed
Djangoum wants to merge 1 commit into
dotnet:devfrom
Djangoum:dev
Closed

Djangoum wants to merge 1 commit into
dotnet:devfrom
Djangoum:dev

Conversation

@Djangoum

Copy link
Copy Markdown
Contributor

Hi!

In a project in my company we had the need to support full index text searches mainly using FREETEXT method on SQL Server. We were also using EntityFrameworkCore as our main ORM so when i saw the roadmap with DbFunctions i decided to implement the translator for FREETEXT for SqlServer.

I've implemented and i would like someone to review my pull request because i've some doubts. Mostly about the testing.

First about the code :

  • Is my new extension method and usage propertly written ? (Expression.IsVoidReturnCall)
  • I've created a new DbFunctions extensions class specific for SqlServer due to specificness of FREETEXT method.
  • My only thought on FreeText in memory implementation is the string.contains method due to the complexity of SqlServer FREETEXT behaviour. (Any thoguhts?)

And then about the tests :

  • I could not run my own written test because the usage of FREETEXT is dependent on SqlServer's FullText services to be installed and propertly running. This is not even possible with LocalDb.

  • So i'm wondering how i must proceed with this issue and how to provide a quality test code that can be executed on all machines.

Usage example

var result = context
	.Employees
	.Count(c => EF.Functions.FreeText(c.Notes, "free_text"));

var result = context
	.Employees
	.Count(c => EF.Functions.FreeText(c.Notes, "free_text", 1033));

SQL result queries

 SELECT COUNT(*)
            FROM [Employees] AS [c]
            WHERE FREETEXT([c].[Notes],N'free_text')

 SELECT COUNT(*)
            FROM [Employees] AS [c]
            WHERE FREETEXT([c].[Notes],N'free_text', LANGUAGE 1033)

@smitpatel

Copy link
Copy Markdown
Contributor

To answer the questions

For testing,
Can you list out what are the restrictions for testing? like,

  • localdb/external server
  • Min Sql Server Version
  • Features explicitly required to be installed

We can get conditional tests working if needed. Similar to how we do memory optimized table.

@smitpatel smitpatel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

#9143 shouldn't really block this. It would print extra =true. If that is causing issue let me know.

new SqlServerStringTrimStartTranslator(),
new SqlServerStringTrimTranslator()
new SqlServerStringTrimTranslator(),
new SqlServerFreeTextMethodCallTranslator()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Alphabetical sorting.

/// <summary>
/// Represents a FREETEXT T-SQL method call
/// </summary>
public class FreeTextExpression : Expression

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No new expression. Use SqlFunctionExpression with correct set of parameters to represent this.

}

return expression.IsComparisonOperation()
|| expression.IsVoidReturnCall()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

An expression with type void is not correct.
Without this it may produce extra = true calls. Are those causing an issue?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, i had this issue.

When translating my expression, EntityFramework does write an extra " = 1" after my FREETEXT call and the query fails.

How can i resolve that without returning a void in the expression ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Once you convert it to SqlFunction, there is no longer expression of void type. (it doesn't make any sense anyway). That is where you would hit #9143
Provider has no way to override and effectively tell us that this SqlFunction is of value type or condition type. Unless that is fixed you cannot do anything inside this visitor.

There is a way to work-around it though. Basically this visitor is going to create FREETEXT(...) = 1 binary Expression. in SqlServerQuerySqlGenerator inside VisitBinary method, evaluate for that pattern and remove =1 part from binaryexpression to generate correct SQL.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ok i'll work on this for the moment until #9143 is solved.

Thank you for your support!


if (Equals(methodCallExpression.Method, _methodInfo))
{
return new FreeTextExpression(methodCallExpression.Arguments[1], methodCallExpression.Arguments[2]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Use SqlFunctionExpression


private static bool FreeTextCore(string columnName, string freeText, int? languageTerm)
{
return columnName.Contains(freeText);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Throw NotImplemented instead

/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public static bool IsVoidReturnCall([NotNull] this Expression expression)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove


namespace Microsoft.EntityFrameworkCore.Query
{
[SqlServerConfiguredCondition]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The whole assembly is marked with this attribute. It is redundant.

}
}

[Fact]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ConditionalFact


namespace Microsoft.EntityFrameworkCore.TestUtilities
{
public class SqlServerConfiguredConditionIsFullTextInstalled : Attribute, ITestCondition

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove this whole class. Instead update SqlServerConditionAttribute.IsMet property to check with TestEnvironment
And in TestEnvironment, put this code as fallback to config (like DefaultConnection)
That will allow to disable the feature in config as needed and fallback based on server otherwise.

{
using (var sql = new SqlConnection(SqlServerTestStore.CreateConnectionString("sample")))
{
var command = new SqlCommand("SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')", sql);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

use using around command & reader

@Djangoum

Copy link
Copy Markdown
Contributor Author

@smitpatel Hi i've to work a little bit more on the test, but my requirements are:

external server
SQL 2008 or higher
Full Text search installed and enabled on SQL server

I'll also need a database with at least one table containing a full text index. I will generate this database and attach to SqlServer testing project like Northwind.sql database or adventureworks.sql and generate my own database with my needs to test my code.

On my next commit i'll attach the new testing database if it's possible.

i've written the workaround you told me to remove the extra "= 1" i think is propertly written.

@smitpatel smitpatel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Add tests for variety not just count or SingleOrDefault especially using where so that we can verify the results.
Tests for passing column lists in FREETEXT
?

/// </returns>
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
if(((SqlFunctionExpression)binaryExpression.Left).FunctionName == "FREETEXT")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is unsafe casting. It will throw exception is Left is not SqlFunctionExpression. Use pattern matching like
if (binaryExpression.Left is SqlFunctionExpression sqlFunctionExpression && sqlFunctionExpression.FunctionName == "FREETEXT")

{
Visit(binaryExpression.Left);

return binaryExpression.Left;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

return just binaryExpression. This visitor returns the same expression. It is just about Visiting parts & generate SQL

[CanBeNull] string columnName,
[CanBeNull] string freeText,
int languageTerm
) => FreeTextCore(columnName, freeText, languageTerm);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: ) goes on the line before.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why CanBeNull instead of NotNull what happens when you pass null to columnName?

{
var result = context.Employees.Count(c => EF.Functions.FreeText(c.FirstName, "grade"));

Assert.Equal(result, 0);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Try to find a test which gives non-zero result and assert the some part of result to verify it returned expected result.

{
FreeText_Search_Literal();

Assert.Equal(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Inline SQL assertions in the test running query itself and remove all tests which are just sql assertions

{
var result = context.Employees.Count(c => EF.Functions.FreeText(c.Notes, c.FirstName));

Assert.NotEqual(result, 0);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

verify exact count.


public static bool IsTeamCity => Environment.GetEnvironmentVariable("TEAMCITY_VERSION") != null;

public static bool SupportsFullTextSearching

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Align all names to this concept in conditional testing to SupportsFullTextSearch

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I did't understand what you are asking for here

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Properties named SupportsFullTextSearching or SupportsFullTextSearches should be renamed to SupportsFullTextSearch

@Djangoum

Djangoum commented Dec 1, 2017

Copy link
Copy Markdown
Contributor Author

@smitpatel Hi again.

I'm about to push a commit with the changes and new passing test implemented, but i'm wondering how to give support to column list.

Shold i make an overload like :

[...] FreeText(IEnumerable<string> columns, [....]) (maybe this is the best)

or like this :

FreeText([...], params string[] columns) (with this i miss original parameter ordering)

or Just allow the user to write down columns separated by ',' (I think this can cause a lot of problems)

@smitpatel

Copy link
Copy Markdown
Contributor

@Djangoum - Interesting question. It seems that implementing it would be non-trivial. I filed #10462 for that. And you can leave it out of the scope of this PR.


if (methodCallExpression.Arguments[2].NodeType != ExpressionType.Constant)
{
throw new ArgumentException(SqlServerStrings.InvalidArgumentToDbFunction(nameof(SqlServerDbFunctionsExtensions.FreeText), ExpressionType.Constant));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why this needs to be type of constant? Can it be parameter?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You are rigth. It can be Parameter. I'll add some more test for this and i'll push soon.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What is the error when it is neither of those? Like using another column here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

When the sql is like:

SELECT TOP(1) [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title]\r\nFROM [Employees] AS [e]\r\nWHERE FREETEXT([e].[City], [e].[FirstName])

SqlServer throws : Incorrect Syntax near '[e]', Expecting STRING, TEXT_LEX or VARIABLE.

And when the Sql is like :

SELECT TOP(1) [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title]\r\nFROM [Employees] AS [e]\r\nWHERE FREETEXT([e].[City], N'')

Null or empty full-text predicate.

And when:

SELECT TOP(1) [e].[EmployeeID], [e].[City], [e].[Country], [e].[FirstName], [e].[ReportsTo], [e].[Title]\r\nFROM [Employees] AS [e]\r\nWHERE FREETEXT([e].[City], NULL)

Incorrect syntax near the keyword 'NULL'.

@Djangoum Djangoum Dec 1, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In my last commit i check for all these cases and i've added a test that expect for ArgumentException thrown by the translator on these cases.


private bool ValidateFreeTextArguments(ReadOnlyCollection<Expression> arguments)
{
var expressionDelegate = Expression.Lambda(arguments[2]).Compile();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You cannot evaluate this. Especially for parameters.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove this check

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, you are rigth. Should i let SqlServer throw the syntax error ?

public static bool FreeText(
[CanBeNull] this DbFunctions _,
[NotNull] string columnName,
[CanBeNull] string freeText,

@smitpatel smitpatel Dec 1, 2017 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Make freeText non-null & add Check function for Check.NotEmpty

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Put NotNull annotation for freeText parameter.

if (!ValidateFreeTextArguments(methodCallExpression.Arguments)
&& _supportedExpressionNodeTypes.Contains(methodCallExpression.Arguments[2].NodeType))
{
throw new ArgumentException(SqlServerStrings.InvalidArgumentToDbFunction(nameof(SqlServerDbFunctionsExtensions.FreeText), ExpressionType.Constant));

@smitpatel smitpatel Dec 1, 2017 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

InvalidArgumentToFreeTextFunction

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No checks needed. Just let it pass because SqlServer would throw exception anyway. We don't have alternate pipeline to evaluate this. So all that is happening here is capturing an exception which sql server would have thrown anyway.

/// <summary>
/// Invalid argument passed to {dbFunction}. Argument must be a {expressionNodeType} expression
/// </summary>
public static string InvalidArgumentToDbFunction([CanBeNull] object dbFunction, [CanBeNull] object expressionNodeType)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove exception throwing mechanism

public static bool FreeText(
[CanBeNull] this DbFunctions _,
[NotNull] string columnName,
[CanBeNull] string freeText,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Put NotNull annotation for freeText parameter.

@smitpatel smitpatel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please squash all commits into 1 and rebase on latest dev.

{
/// <summary>
/// <para>
/// An implementation of the T-SQL FREEETEXT method. It is used to perform full text searches on full text indexed columns

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@divega @ajcvickers - Doc comments for this? It is not implementation because we don't evaluate it on client.

@smitpatel

Copy link
Copy Markdown
Contributor

@Djangoum - I am not able to run tests locally or on appveyor. For testing we need something additional work. Can you describe how you got tests to work on your machine?

@Djangoum

Djangoum commented Dec 4, 2017

Copy link
Copy Markdown
Contributor Author

Hi @smitpatel,

What i do is modify the connection string on the SqlServer.FunctionalTests project (config.json) to point to my instance of SqlServer with advanced services (wich includes the full text search and is not localdb).

If the Full text serch is not installed on sql server (it's never on LocalDb) the test will be skipped.

I'm running the tests with TestDriven.Net.

@smitpatel

Copy link
Copy Markdown
Contributor

@Djangoum - Thanks for help. I am able to run tests now.

@smitpatel

Copy link
Copy Markdown
Contributor

Merged alongwith #10480

Thanks for contribution @Djangoum

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants