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

create unqiue index in indexes and related children in contrib.postgres/sqlite.indexes #1642

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
27 changes: 26 additions & 1 deletion tortoise/contrib/postgres/indexes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import Optional, Tuple
from typing import Optional, Tuple, Type

from pypika.terms import Term, ValueWrapper

from tortoise.backends.base.schema_generator import BaseSchemaGenerator
from tortoise.indexes import PartialIndex
from tortoise.models import Model


class PostgreSQLIndex(PartialIndex):
Expand Down Expand Up @@ -49,3 +51,26 @@ class HashIndex(PostgreSQLIndex):

class SpGistIndex(PostgreSQLIndex):
INDEX_TYPE = "SPGIST"


class PostgresUniqueIndex(PostgreSQLIndex):
INDEX_CREATE_TEMPLATE = PostgreSQLIndex.INDEX_CREATE_TEMPLATE.replace(
"CREATE", "CREATE UNIQUE"
).replace("USING", "")

def __init__(
self,
*expressions: Term,
fields: Optional[Tuple[str]] = None,
name: Optional[str] = None,
condition: Optional[dict] = None,
nulls_not_distinct: bool = False,
):
super().__init__(*expressions, fields=fields, name=name, condition=condition)
if nulls_not_distinct:
self.extra = " nulls not distinct".upper() + self.extra

def get_sql(self, schema_generator: BaseSchemaGenerator, model: Type[Model], safe: bool):
if self.INDEX_TYPE:
self.INDEX_TYPE = f"USING {self.INDEX_TYPE}"
Comment on lines +74 to +75
Copy link
Member

Choose a reason for hiding this comment

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

Sorry, I was wrong about this, I forgot that postgresql allows only default b-tree index to be unique, so it is something we don't need to support

return super().get_sql(schema_generator, model, safe)
46 changes: 46 additions & 0 deletions tortoise/contrib/sqlite/indexes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from typing import Dict, Optional, Tuple

from pypika.terms import Term, ValueWrapper

from tortoise.indexes import PartialIndex


class SqliteIndex(PartialIndex):
INDEX_CREATE_TEMPLATE = PartialIndex.INDEX_CREATE_TEMPLATE.replace("INDEX", "INDEX {exists} ")


class SqliteUniqueIndex(SqliteIndex):
INDEX_TYPE = "unique".upper()
Copy link
Member

Choose a reason for hiding this comment

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

Why not just "UNIQUE"?


def __init__(
self,
*expressions: Term,
fields: Optional[Tuple[str, ...]] = None,
name: Optional[str] = None,
condition: Optional[Dict[str, str]] = None,
where_expre: Optional[str] = None,
Copy link
Member

Choose a reason for hiding this comment

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

I am a little at lost here
Why do we need both condition and where_expre?

):
_condition = condition
if condition:
condition = None
super().__init__(*expressions, fields=fields, name=name, condition=condition)
if _condition:
# TODO: what is the best practice to inject where expression?
self.extra = where_expre or self._gen_condition(_condition)

@classmethod
def _gen_field_cond(cls, kv: tuple):
Copy link
Member

Choose a reason for hiding this comment

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

Add return typing

key, cond = kv
op = (
""
if isinstance(cond, str)
and cond.strip().lower().startswith(("is ", "isnot ", "<", ">", "=", "!="))
else "="
)
if op == "=":
cond = ValueWrapper(cond)
return str(f"{key} {op} {cond}")

def _gen_condition(self, conditions: Dict[str, str]):
conditions = " AND ".join(tuple(map(self._gen_field_cond, conditions.items())))
Copy link
Member

Choose a reason for hiding this comment

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

please use comprehensions

" AND ".join(self._gen_field_cond(k, v) for k, v in condition.items())

With that you will also be able to make better signature and typing for _gen_field_cond

return f" where {conditions}"