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

Implementation of a StaticValue class #719

Open
GregoirePelegrin opened this issue Feb 13, 2023 · 1 comment
Open

Implementation of a StaticValue class #719

GregoirePelegrin opened this issue Feb 13, 2023 · 1 comment

Comments

@GregoirePelegrin
Copy link

GregoirePelegrin commented Feb 13, 2023

Objective

I needed to generate the following SQL query:

SELECT CAST('some_constant' AS VARCHAR) "column_name" 
FROM "table"

I didn't seem to find any existing way to do it, so here is my proposal

StaticValue class

In pypika.terms

class StaticValue(Term):
    def __init__(self, value, alias: Optional[str] = None) -> None:
        super().__init__(alias)
        self._value = value

    def get_sql(self, **kwargs: Any) -> str:
        return format_alias_sql_new(self._value, self.alias, static_quote_char="'", **kwargs)

This class also introduces format_alias_sql_new() (in pypika.utils), which is an evolution of format_alias_sql() with an added static_quote_char parameter:

def format_alias_sql_new(
    sql: str, alias: Optional[str], quote_char: Optional[str] = None, alias_quote_char: Optional[str] = None,
    static_quote_char: Optional[str] = None, as_keyword: bool = False, **kwargs: Any,
) -> str:
    if alias is None:
        return format_quotes(value=sql, quote_char=static_quote_char)
    return "{sql}{_as}{alias}".format(
        sql=format_quotes(value=sql, quote_char=static_quote_char), _as=' AS ' if as_keyword else ' ',
        alias=format_quotes(alias, alias_quote_char or quote_char)
    )

format_quotes here being the normal pypika.utils.format_quotes.

@varunsinghal
Copy link

you may also try an alternative approach:

from pypika import Query, Table, functions as fn 

table = Table('my-table')
Query.from_(table).select('*', fn.LiteralValue("'some_constant'").as_("column_name"))

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

No branches or pull requests

2 participants