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

Add magic arguments to pass variables into templated queries #7

Open
psychemedia opened this issue Aug 24, 2024 · 1 comment
Open

Comments

@psychemedia
Copy link
Contributor

Generalise how line magic elements are handled and then add support for passing in py variables that can be used in the sql queries as template parameters.

@psychemedia psychemedia changed the title Add magic arguments ro sipport template queries Add magic arguments to pass variables into templated queries Aug 24, 2024
@psychemedia
Copy link
Contributor Author

Currently, the pglite_df_insert can accept a pandas.Dataframe which it will try insert into a specified table. The datarame value is picked up from the local_ns via local_ns[args.dataframe].

    @line_magic
    @needs_local_scope
    @magic_arguments()
    @argument("-t", "--table", type=str, help="Table name")
    @argument("-d", "--dataframe", type=str, help="Datatframe")
    @argument("-w", "--widget-name", type=str, help="widget variable name")
    def pglite_df_insert(self, line, local_ns=None):
        """Call as: %pglite -d df -t tableName"""
        from pandas import DataFrame
        args = parse_argstring(self.pglite_df_insert, line)
        if args.dataframe not in local_ns:
            raise ValueError(f"DataFrame '{args.dataframe}' not found in the local namespace")

        # Get the DataFrame
        df = local_ns[args.dataframe]

        # Validate the DataFrame
        if not isinstance(df, DataFrame):
            raise TypeError(f"'{args.dataframe}' is not a pandas DataFrame")

        # Generate the SQL statement
        columns = ', '.join(df.columns)
        values = ',\n    '.join(
            [f"({', '.join(repr(value) for value in row)})" for row in df.itertuples(index=False, name=None)]
        )
        sql = f"INSERT INTO {args.table} ({columns})\nVALUES\n{values};"
        return self._run_query(args, sql)

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

1 participant