Skip to content

Use "?" for parameter markers in both native query and query translation #78

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,37 @@ void testGetByPrimaryKeyWithNullValueField() {
}
}

@Nested
class NativeQueryTests {

@Test
void testNative() {
var book = new Book();
book.id = 1;
book.title = "In Search of Lost Time";
book.publishYear = 1913;

sessionFactoryScope.inTransaction(session -> session.persist(book));

var nativeQuery =
"""
{
aggregate: "books",
pipeline: [
{ $match : { _id: { $eq: :id } } },
{ $project: { _id: 1, publishYear: 1, title: 1, author: 1 } }
]
}
""";
sessionFactoryScope.inTransaction(session -> {
var query = session.createNativeQuery(nativeQuery, Book.class)
.setParameter("id", book.id);
var queriedBook = query.getSingleResult();
assertThat(queriedBook).usingRecursiveComparison().isEqualTo(book);
});
}
}

private static void assertCollectionContainsExactly(BsonDocument expectedDoc) {
assertThat(mongoCollection.find()).containsExactly(expectedDoc);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,13 @@
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.bson.BsonUndefined;
import org.bson.json.Converter;
import org.bson.json.JsonMode;
import org.bson.json.JsonWriter;
import org.bson.json.JsonWriterSettings;
import org.bson.json.StrictJsonWriter;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.util.collections.Stack;
import org.hibernate.persister.entity.EntityPersister;
Expand Down Expand Up @@ -151,7 +155,9 @@

abstract class AbstractMqlTranslator<T extends JdbcOperation> implements SqlAstTranslator<T> {
private static final JsonWriterSettings JSON_WRITER_SETTINGS =
JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build();
JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED)
.undefinedConverter((bsonUndefined, strictJsonWriter) -> strictJsonWriter.writeRaw("?"))
.build();

private final SessionFactoryImplementor sessionFactory;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Copyright 2025-present MongoDB, Inc.
*
* 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 com.mongodb.hibernate.jdbc;

class MongoParameterRecognizer {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Adopted from JsonScanner in Java driver.


static String replace(String json) {
StringBuilder builder = new StringBuilder(json.length());

int i = 0;
while (i < json.length()) {
char c = json.charAt(i++);
switch (c) {
case '{':
case '}':
case '[':
case ']':
case ':':
case ',':
case ' ':
builder.append(c);
break;
case '\'':
case '"':
i = scanString(c, i, json, builder);
break;
case '?':
builder.append("{$undefined: true}");
break;
default:
if (c == '-' || Character.isDigit(c)) {
i = scanNumber(c, i, json, builder);
} else if (c == '$' || c == '_' || Character.isLetter(c)) {
i = scanUnquotedString(c, i, json, builder);
} else {
builder.append(c); // or throw exception, as this isn't valid JSON
}
}
}
return builder.toString();
}

private static int scanNumber(char firstCharacter, int startIndex, String json, StringBuilder builder) {
builder.append(firstCharacter);
int i = startIndex;
char c = json.charAt(i++);
while (i < json.length() && Character.isDigit(c)) {
builder.append(c);
c = json.charAt(i++);
}
return i - 1;
}

private static int scanUnquotedString(final char firstCharacter, final int startIndex, final String json, final StringBuilder builder) {
builder.append(firstCharacter);
int i = startIndex;
char c = json.charAt(i++);
while (i < json.length() && Character.isLetterOrDigit(c)) {
builder.append(c);
c = json.charAt(i++);
}
return i - 1;
}

private static int scanString(final char quoteCharacter, final int startIndex, final String json, final StringBuilder builder) {
int i = startIndex;
builder.append(quoteCharacter);
while (i < json.length()) {
char c = json.charAt(i++);
if (c == '\\') {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I didn't include explicit support for escapes like \uFEBA. It will still work as is so long as the string is not malformed, but could add back what is in JsonScanner.

builder.append(c);
if (i < json.length()) {
c = json.charAt(i++);
builder.append(c);
}
} else if (c == quoteCharacter) {
builder.append(c);
return i;
} else {
builder.append(c);
}
}
return i;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ final class MongoPreparedStatement extends MongoStatement implements PreparedSta
MongoDatabase mongoDatabase, ClientSession clientSession, MongoConnection mongoConnection, String mql)
throws SQLSyntaxErrorException {
super(mongoDatabase, clientSession, mongoConnection);
this.command = MongoStatement.parse(mql);
this.command = MongoStatement.parse(MongoParameterRecognizer.replace(mql));
this.parameterValueSetters = new ArrayList<>();
parseParameters(command, parameterValueSetters);
}
Expand Down
28 changes: 25 additions & 3 deletions src/main/java/com/mongodb/hibernate/jdbc/MongoResultSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -210,13 +210,18 @@ public double getDouble(int columnIndex) throws SQLException {
@Override
public ResultSetMetaData getMetaData() throws SQLException {
checkClosed();
return new MongoResultSetMetadata();
return new MongoResultSetMetadata(fieldNames);
}

@Override
public int findColumn(String columnLabel) throws SQLException {
checkClosed();
throw new SQLFeatureNotSupportedException("To be implemented in scope of native query tickets");
for (int i = 0; i < fieldNames.size(); i++) {
if (fieldNames.get(i).equals(columnLabel)) {
return i + 1;
}
}
throw new SQLException("Unknown column label " + columnLabel);
}

@Override
Expand Down Expand Up @@ -263,5 +268,22 @@ private void checkColumnIndex(int columnIndex) throws SQLException {
}
}

private static final class MongoResultSetMetadata implements ResultSetMetaDataAdapter {}
private static final class MongoResultSetMetadata implements ResultSetMetaDataAdapter {
private final List<String> fieldNames;

public MongoResultSetMetadata(List<String> fieldNames) {
this.fieldNames = fieldNames;
}

@Override
public int getColumnCount() {
return fieldNames.size();
}


@Override
public String getColumnLabel(int column) {
return fieldNames.get(column - 1);
}
}
}