For mapping Pandas tables to SQL tables. Uses fact that table is reflected by SQLAlchemy to do better type conversions. Also holds various flags needed to avoid having to pass them between functions all the time.
| 922 | |
| 923 | |
| 924 | class SQLTable(PandasObject): |
| 925 | """ |
| 926 | For mapping Pandas tables to SQL tables. |
| 927 | Uses fact that table is reflected by SQLAlchemy to |
| 928 | do better type conversions. |
| 929 | Also holds various flags needed to avoid having to |
| 930 | pass them between functions all the time. |
| 931 | """ |
| 932 | |
| 933 | # TODO: support for multiIndex |
| 934 | |
| 935 | def __init__( |
| 936 | self, |
| 937 | name: str, |
| 938 | pandas_sql_engine, |
| 939 | frame=None, |
| 940 | index: bool | str | list[str] | None = True, |
| 941 | if_exists: Literal["fail", "replace", "append", "delete_rows"] = "fail", |
| 942 | prefix: str = "pandas", |
| 943 | index_label=None, |
| 944 | schema=None, |
| 945 | keys=None, |
| 946 | dtype: DtypeArg | None = None, |
| 947 | ) -> None: |
| 948 | self.name = name |
| 949 | self.pd_sql = pandas_sql_engine |
| 950 | self.prefix = prefix |
| 951 | self.frame = frame |
| 952 | self.index = self._index_name(index, index_label) |
| 953 | self.schema = schema |
| 954 | self.if_exists = if_exists |
| 955 | self.keys = keys |
| 956 | self.dtype = dtype |
| 957 | |
| 958 | if frame is not None: |
| 959 | # We want to initialize based on a dataframe |
| 960 | self.table = self._create_table_setup() |
| 961 | else: |
| 962 | # no data provided, read-only mode |
| 963 | self.table = self.pd_sql.get_table(self.name, self.schema) |
| 964 | |
| 965 | if self.table is None: |
| 966 | raise ValueError(f"Could not init table '{name}'") |
| 967 | |
| 968 | if not len(self.name): |
| 969 | raise ValueError("Empty table name specified") |
| 970 | |
| 971 | def exists(self): |
| 972 | return self.pd_sql.has_table(self.name, self.schema) |
| 973 | |
| 974 | def sql_schema(self) -> str: |
| 975 | from sqlalchemy.schema import CreateTable |
| 976 | |
| 977 | return str(CreateTable(self.table).compile(self.pd_sql.con)) |
| 978 | |
| 979 | def _execute_create(self) -> None: |
| 980 | # Inserting table into database, add to MetaData object |
| 981 | self.table = self.table.to_metadata(self.pd_sql.meta) |
no outgoing calls
no test coverage detected