Skip to content

Implement Builder::toSql using JSON representation of the MQL #2931

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file.

## [4.4.0] - unreleased

* Implement `Builder::toSql` using JSON representation of the MQL by @GromNaN in [#2931](https://github.com/mongodb/laravel-mongodb/pull/2931)
* Support collection name prefix by @GromNaN in [#2930](https://github.com/mongodb/laravel-mongodb/pull/2930)

## [4.3.0] - 2024-04-26
Expand Down
2 changes: 2 additions & 0 deletions src/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ class Builder extends EloquentBuilder
'raw',
'sum',
'tomql',
'tosql',
'torawsql',
];

/**
Expand Down
25 changes: 21 additions & 4 deletions src/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use InvalidArgumentException;
use LogicException;
use MongoDB\BSON\Binary;
use MongoDB\BSON\Document;
use MongoDB\BSON\ObjectID;
use MongoDB\BSON\Regex;
use MongoDB\BSON\UTCDateTime;
Expand Down Expand Up @@ -1446,16 +1447,26 @@ public function __call($method, $parameters)
return parent::__call($method, $parameters);
}

/** @internal This method is not supported by MongoDB. */
/**
* Return the JSON representation of the MongoDB Query.
* Naming is inherited and used for compatibility with third-party packages.
*
* @internal
Copy link
Member

Choose a reason for hiding this comment

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

Should this still be @internal?

I don't have enough context to understand how/why rappasoft/laravel-livewire-tables needs to support MongoDB, but isn't there some concern that returning JSON strings here might break other packages that expect these methods to return actual SQL statements?

My thinking is that packages wishing to support this library should be the ones to change and conditionally call toMql().

Copy link
Member Author

Choose a reason for hiding this comment

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

It's used for debugging: https://tables.laravel-boilerplate.com/tailwind
But Laravel Debugbar would provide the same information.

And I agree this can lead to other problems if packages expect SQL and use the returned value as such.

*/
public function toSql()
{
throw new BadMethodCallException('This method is not supported by MongoDB. Try "toMql()" instead.');
return Document::fromPHP($this->toMql())->toCanonicalExtendedJSON();
}

/** @internal This method is not supported by MongoDB. */
/**
* Return the JSON representation of the MongoDB Query.
* Naming is inherited and used for compatibility with third-party packages.
*
* @internal
*/
public function toRawSql()
{
throw new BadMethodCallException('This method is not supported by MongoDB. Try "toMql()" instead.');
return $this->toSql();
}

/** @internal This method is not supported by MongoDB. */
Expand Down Expand Up @@ -1535,4 +1546,10 @@ public function orWhereIntegerNotInRaw($column, $values, $boolean = 'and')
{
throw new BadMethodCallException('This method is not supported by MongoDB');
}

/** @internal This method is not supported by MongoDB. */
public function insertUsing(array $columns, $query)
Copy link
Member Author

Choose a reason for hiding this comment

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

We relied on the exception thrown by the parent method that uses toSql.

{
throw new BadMethodCallException('This method is not supported by MongoDB');
}
}
51 changes: 23 additions & 28 deletions tests/Eloquent/CallBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,34 +24,36 @@ protected function tearDown(): void
}

#[Dataprovider('provideFunctionNames')]
public function testCallingABuilderMethodDoesNotReturnTheBuilderInstance(string $method, string $className, $parameters = []): void
public function testCallingABuilderMethodDoesNotReturnTheBuilderInstance(string $method, $parameters = []): void
{
$builder = User::query()->newQuery();
assert($builder instanceof Builder);

self::assertNotInstanceOf(expected: $className, actual: $builder->{$method}(...$parameters));
self::assertNotInstanceOf(Builder::class, $builder->{$method}(...$parameters));
}

public static function provideFunctionNames(): Generator
{
yield 'does not exist' => ['doesntExist', Builder::class];
yield 'get bindings' => ['getBindings', Builder::class];
yield 'get connection' => ['getConnection', Builder::class];
yield 'get grammar' => ['getGrammar', Builder::class];
yield 'insert get id' => ['insertGetId', Builder::class, [['user' => 'foo']]];
yield 'to Mql' => ['toMql', Builder::class];
yield 'average' => ['average', Builder::class, ['name']];
yield 'avg' => ['avg', Builder::class, ['name']];
yield 'count' => ['count', Builder::class, ['name']];
yield 'exists' => ['exists', Builder::class];
yield 'insert' => ['insert', Builder::class, [['name']]];
yield 'max' => ['max', Builder::class, ['name']];
yield 'min' => ['min', Builder::class, ['name']];
yield 'pluck' => ['pluck', Builder::class, ['name']];
yield 'pull' => ['pull', Builder::class, ['name']];
yield 'push' => ['push', Builder::class, ['name']];
yield 'raw' => ['raw', Builder::class];
yield 'sum' => ['sum', Builder::class, ['name']];
yield 'does not exist' => ['doesntExist'];
yield 'get bindings' => ['getBindings'];
yield 'get connection' => ['getConnection'];
yield 'get grammar' => ['getGrammar'];
yield 'insert get id' => ['insertGetId', [['user' => 'foo']]];
yield 'to Mql' => ['toMql'];
yield 'to Sql' => ['toSql'];
yield 'to Raw Sql' => ['toRawSql'];
yield 'average' => ['average', ['name']];
yield 'avg' => ['avg', ['name']];
yield 'count' => ['count', ['name']];
yield 'exists' => ['exists'];
yield 'insert' => ['insert', [['name']]];
yield 'max' => ['max', ['name']];
yield 'min' => ['min', ['name']];
yield 'pluck' => ['pluck', ['name']];
yield 'pull' => ['pull', ['name']];
yield 'push' => ['push', ['name']];
yield 'raw' => ['raw'];
yield 'sum' => ['sum', ['name']];
}

#[Test]
Expand Down Expand Up @@ -79,14 +81,7 @@ public static function provideUnsupportedMethods(): Generator
yield 'insert using' => [
'insertUsing',
BadMethodCallException::class,
'This method is not supported by MongoDB. Try "toMql()" instead',
[[['name' => 'Jane']], fn (QueryBuilder $builder) => $builder],
];

yield 'to sql' => [
'toSql',
BadMethodCallException::class,
'This method is not supported by MongoDB. Try "toMql()" instead',
'This method is not supported by MongoDB',
[[['name' => 'Jane']], fn (QueryBuilder $builder) => $builder],
];
}
Expand Down
15 changes: 12 additions & 3 deletions tests/Query/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1396,6 +1396,18 @@ public static function provideExceptions(): iterable
];
}

public function testToSql()
{
$builder = self::getBuilder();
$builder
->where('foo', 'bar')
->limit(10);

$expected = '{ "find" : [ { "foo" : "bar" }, { "limit" : { "$numberInt" : "10" }, "typeMap" : { "root" : "array", "document" : "array" } } ] }';
$this->assertSame($expected, $builder->toSql());
$this->assertSame($expected, $builder->toRawSql());
}

/** @dataProvider getEloquentMethodsNotSupported */
public function testEloquentMethodsNotSupported(Closure $callback)
{
Expand All @@ -1412,9 +1424,6 @@ public static function getEloquentMethodsNotSupported()
// Most of this methods can be implemented using aggregation framework
// whereInRaw, whereNotInRaw, orWhereInRaw, orWhereNotInRaw, whereBetweenColumns

yield 'toSql' => [fn (Builder $builder) => $builder->toSql()];
yield 'toRawSql' => [fn (Builder $builder) => $builder->toRawSql()];

/** @see DatabaseQueryBuilderTest::testBasicWhereColumn() */
/** @see DatabaseQueryBuilderTest::testArrayWhereColumn() */
yield 'whereColumn' => [fn (Builder $builder) => $builder->whereColumn('first_name', 'last_name')];
Expand Down