Skip to content

Commit cab1a64

Browse files
author
Peng Ren
committed
Fix something
1 parent 7bebabc commit cab1a64

22 files changed

+7808
-49524
lines changed

.coveragerc

Lines changed: 0 additions & 20 deletions
This file was deleted.

.flake8

Lines changed: 0 additions & 3 deletions
This file was deleted.

.github/workflows/ci.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ jobs:
4040
uses: actions/cache@v3
4141
with:
4242
path: ~/.cache/pip
43-
key: ${{ runner.os }}-py${{ matrix.python-version }}-mongo${{ matrix.mongodb-version }}-pip-${{ hashFiles('**/requirements-test.txt') }}
43+
key: ${{ runner.os }}-py${{ matrix.python-version }}-mongo${{ matrix.mongodb-version }}-pip-${{ hashFiles('**/requirements-test.txt', 'pyproject.toml') }}
4444
restore-keys: |
4545
${{ runner.os }}-py${{ matrix.python-version }}-mongo${{ matrix.mongodb-version }}-pip-
4646
@@ -83,7 +83,7 @@ jobs:
8383
8484
- name: Run tests with coverage
8585
run: |
86-
python -m pytest tests/ --cov=pymongosql --cov-report=term-missing --cov-report=xml --cov-config=.coveragerc
86+
python -m pytest tests/ --cov=pymongosql --cov-report=term-missing --cov-report=xml
8787
8888
- name: Upload coverage reports
8989
uses: codecov/codecov-action@v4

pymongosql/common.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,7 @@ def execute(
4141
raise NotImplementedError # pragma: no cover
4242

4343
@abstractmethod
44-
def executemany(
45-
self, operation: str, seq_of_parameters: List[Optional[Dict[str, Any]]]
46-
) -> None:
44+
def executemany(self, operation: str, seq_of_parameters: List[Optional[Dict[str, Any]]]) -> None:
4745
raise NotImplementedError # pragma: no cover
4846

4947
@abstractmethod
@@ -82,9 +80,7 @@ def arraysize(self, value: int) -> None:
8280
if value <= 0:
8381
raise ValueError("arraysize must be positive")
8482
if value > self.DEFAULT_FETCH_SIZE:
85-
raise ProgrammingError(
86-
f"MaxResults is more than maximum allowed length {self.DEFAULT_FETCH_SIZE}."
87-
)
83+
raise ProgrammingError(f"MaxResults is more than maximum allowed length {self.DEFAULT_FETCH_SIZE}.")
8884
self._arraysize = value
8985

9086
@property

pymongosql/connection.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,7 @@ def _connect(self) -> None:
7474
try:
7575
# Build connection string
7676
if self._username and self._password:
77-
auth_string = (
78-
f"{quote_plus(self._username)}:{quote_plus(self._password)}@"
79-
)
77+
auth_string = f"{quote_plus(self._username)}:{quote_plus(self._password)}@"
8078
else:
8179
auth_string = ""
8280

@@ -107,9 +105,7 @@ def _connect(self) -> None:
107105
if self._database_name:
108106
self._database = self._client[self._database_name]
109107

110-
_logger.info(
111-
f"Successfully connected to MongoDB at {self._host}:{self._port}"
112-
)
108+
_logger.info(f"Successfully connected to MongoDB at {self._host}:{self._port}")
113109

114110
except ConnectionFailure as e:
115111
_logger.error(f"Failed to connect to MongoDB: {e}")
@@ -258,9 +254,7 @@ def commit(self) -> None:
258254
self._autocommit = True
259255

260256
def rollback(self) -> None:
261-
raise NotSupportedError(
262-
"MongoDB doesn't support rollback in the traditional SQL sense"
263-
)
257+
raise NotSupportedError("MongoDB doesn't support rollback in the traditional SQL sense")
264258

265259
def test_connection(self) -> bool:
266260
"""Test if the connection is alive"""

pymongosql/cursor.py

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -111,23 +111,17 @@ def _execute_query_plan(self, query_plan: QueryPlan) -> None:
111111
find_projection = None
112112
if query_plan.projection_stage:
113113
# Convert {"field": "alias"} to {"field": 1} for MongoDB
114-
find_projection = {
115-
field: 1 for field in query_plan.projection_stage.keys()
116-
}
114+
find_projection = {field: 1 for field in query_plan.projection_stage.keys()}
117115

118-
_logger.debug(
119-
f"Executing MongoDB query: filter={find_filter}, projection={find_projection}"
120-
)
116+
_logger.debug(f"Executing MongoDB query: filter={find_filter}, projection={find_projection}")
121117

122118
# Execute find query
123119
self._mongo_cursor = collection.find(find_filter, find_projection)
124120

125121
# Apply sort if specified
126122
if query_plan.sort_stage:
127123
sort_spec = [
128-
(field, direction)
129-
for sort_dict in query_plan.sort_stage
130-
for field, direction in sort_dict.items()
124+
(field, direction) for sort_dict in query_plan.sort_stage for field, direction in sort_dict.items()
131125
]
132126
self._mongo_cursor = self._mongo_cursor.sort(sort_spec)
133127

@@ -144,9 +138,7 @@ def _execute_query_plan(self, query_plan: QueryPlan) -> None:
144138
mongo_cursor=self._mongo_cursor, query_plan=query_plan, **self._kwargs
145139
)
146140

147-
_logger.info(
148-
f"Query executed successfully on collection '{query_plan.collection}'"
149-
)
141+
_logger.info(f"Query executed successfully on collection '{query_plan.collection}'")
150142

151143
except PyMongoError as e:
152144
_logger.error(f"MongoDB query execution failed: {e}")
@@ -155,9 +147,7 @@ def _execute_query_plan(self, query_plan: QueryPlan) -> None:
155147
_logger.error(f"Unexpected error during query execution: {e}")
156148
raise OperationalError(f"Query execution error: {e}")
157149

158-
def execute(
159-
self: _T, operation: str, parameters: Optional[Dict[str, Any]] = None
160-
) -> _T:
150+
def execute(self: _T, operation: str, parameters: Optional[Dict[str, Any]] = None) -> _T:
161151
"""Execute a SQL statement
162152
163153
Args:
@@ -170,9 +160,7 @@ def execute(
170160
self._check_closed()
171161

172162
if parameters:
173-
_logger.warning(
174-
"Parameter substitution not yet implemented, ignoring parameters"
175-
)
163+
_logger.warning("Parameter substitution not yet implemented, ignoring parameters")
176164

177165
try:
178166
# Parse SQL to QueryPlan
@@ -202,9 +190,7 @@ def executemany(
202190
self._check_closed()
203191

204192
# For now, just execute once and ignore parameters
205-
_logger.warning(
206-
"executemany not fully implemented, executing once without parameters"
207-
)
193+
_logger.warning("executemany not fully implemented, executing once without parameters")
208194
self.execute(operation)
209195

210196
def execute_transaction(self) -> None:

pymongosql/result_set.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,7 @@ def __init__(
2929
self._cached_results: List[Dict[str, Any]] = []
3030
self._cache_exhausted = False
3131
self._total_fetched = 0
32-
self._description: Optional[
33-
List[Tuple[str, str, None, None, None, None, None]]
34-
] = None
32+
self._description: Optional[List[Tuple[str, str, None, None, None, None, None]]] = None
3533
self._errors: List[Dict[str, str]] = []
3634

3735
# Build description from projection
@@ -125,8 +123,7 @@ def description(
125123
# Build description from first result
126124
first_result = self._cached_results[0]
127125
self._description = [
128-
(col_name, "VARCHAR", None, None, None, None, None)
129-
for col_name in first_result.keys()
126+
(col_name, "VARCHAR", None, None, None, None, None) for col_name in first_result.keys()
130127
]
131128
except Exception as e:
132129
_logger.warning(f"Could not build dynamic description: {e}")
@@ -187,9 +184,7 @@ def fetchall(self) -> List[Dict[str, Any]]:
187184
remaining_docs = list(self._mongo_cursor)
188185
if remaining_docs:
189186
# Process results through projection mapping
190-
processed_docs = [
191-
self._process_document(doc) for doc in remaining_docs
192-
]
187+
processed_docs = [self._process_document(doc) for doc in remaining_docs]
193188
all_results.extend(processed_docs)
194189
self._total_fetched += len(remaining_docs)
195190

pymongosql/sql/ast.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,7 @@ def visitFromClause(self, ctx: PartiQLParser.FromClauseContext) -> Any:
101101
_logger.warning(f"Error processing FROM clause: {e}")
102102
return self.visitChildren(ctx)
103103

104-
def visitWhereClauseSelect(
105-
self, ctx: PartiQLParser.WhereClauseSelectContext
106-
) -> Any:
104+
def visitWhereClauseSelect(self, ctx: PartiQLParser.WhereClauseSelectContext) -> Any:
107105
"""Handle WHERE clause for filtering"""
108106
_logger.debug("Processing WHERE clause")
109107
try:

pymongosql/sql/builder.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,10 @@ def validate(self) -> bool:
3838
if not self.collection:
3939
errors.append("Collection name is required")
4040

41-
if self.limit_stage is not None and (
42-
not isinstance(self.limit_stage, int) or self.limit_stage < 0
43-
):
41+
if self.limit_stage is not None and (not isinstance(self.limit_stage, int) or self.limit_stage < 0):
4442
errors.append("Limit must be a non-negative integer")
4543

46-
if self.skip_stage is not None and (
47-
not isinstance(self.skip_stage, int) or self.skip_stage < 0
48-
):
44+
if self.skip_stage is not None and (not isinstance(self.skip_stage, int) or self.skip_stage < 0):
4945
errors.append("Skip must be a non-negative integer")
5046

5147
if errors:
@@ -153,9 +149,7 @@ def where_in(self, field: str, values: List[Any]) -> "MongoQueryBuilder":
153149
"""Add a WHERE field IN (values) condition"""
154150
return self.filter({field: {"$in": values}})
155151

156-
def where_between(
157-
self, field: str, min_val: Any, max_val: Any
158-
) -> "MongoQueryBuilder":
152+
def where_between(self, field: str, min_val: Any, max_val: Any) -> "MongoQueryBuilder":
159153
"""Add a WHERE field BETWEEN min AND max condition"""
160154
return self.filter({field: {"$gte": min_val, "$lte": max_val}})
161155

@@ -165,9 +159,7 @@ def where_like(self, field: str, pattern: str) -> "MongoQueryBuilder":
165159
regex_pattern = pattern.replace("%", ".*").replace("_", ".")
166160
return self.filter({field: {"$regex": regex_pattern, "$options": "i"}})
167161

168-
def _build_condition(
169-
self, field: str, operator: str, value: Any
170-
) -> Optional[Dict[str, Any]]:
162+
def _build_condition(self, field: str, operator: str, value: Any) -> Optional[Dict[str, Any]]:
171163
"""Build a MongoDB condition from field, operator, and value"""
172164
operator_map = {
173165
"=": "$eq",

0 commit comments

Comments
 (0)