meerschaum.connectors.sql

Subpackage for SQLConnector subclass.

The PEP 249 exceptions are what SQLConnector.read(), exec(), value() and exec_queries() raise for database errors (raw SQL runs through the Rust connector, see _native); when SQLAlchemy is imported, they are also instances of SQLAlchemy's classes of the same name.

 1#! /usr/bin/env python
 2# -*- coding: utf-8 -*-
 3# vim:fenc=utf-8
 4
 5"""
 6Subpackage for SQLConnector subclass.
 7
 8The PEP 249 exceptions are what `SQLConnector.read()`, `exec()`, `value()` and `exec_queries()`
 9raise for database errors (raw SQL runs through the Rust connector, see `_native`); when
10SQLAlchemy is imported, they are also instances of SQLAlchemy's classes of the same name.
11"""
12
13from meerschaum.connectors.sql._SQLConnector import SQLConnector
14from meerschaum.connectors.sql._native import (
15    DatabaseError,
16    InterfaceError,
17    OperationalError,
18    ProgrammingError,
19    IntegrityError,
20    DataError,
21    InternalError,
22    NotSupportedError,
23    ResourceClosedError,
24    NATIVE_SQL_FLAVORS,
25)
26
27__all__ = (
28    'SQLConnector',
29    'DatabaseError',
30    'InterfaceError',
31    'OperationalError',
32    'ProgrammingError',
33    'IntegrityError',
34    'DataError',
35    'InternalError',
36    'NotSupportedError',
37    'ResourceClosedError',
38    'NATIVE_SQL_FLAVORS',
39)
class SQLConnector(meerschaum.connectors.instance._InstanceConnector.InstanceConnector):
 94class SQLConnector(InstanceConnector):
 95    """
 96    Connect to SQL databases through the Rust connector's connection pool.
 97
 98    Raw SQL and pipe operations need no SQLAlchemy. The optional `.engine` property
 99    provides a SQLAlchemy engine for code that explicitly uses that interface.
100    
101    SQLConnectors may be used as Meerschaum instance connectors.
102    Read more about connectors and instances at
103    https://meerschaum.io/reference/connectors/
104
105    """
106
107    from ._create_engine import flavor_configs, create_engine
108    from ._sql import (
109        read,
110        value,
111        exec,
112        execute,
113        to_sql,
114        exec_queries,
115        get_connection,
116        _cleanup_connections,
117    )
118    from meerschaum.utils.sql import test_connection
119    from ._fetch import fetch, get_pipe_metadef
120    from ._cli import cli, _cli_exit
121    from ._compress import (
122        get_pipe_size,
123        compress_pipe,
124        decompress_pipe,
125        apply_compression_policy,
126        set_integer_now_func,
127    )
128    from ._maintenance import (
129        vacuum_pipe,
130        analyze_pipe,
131    )
132    from ._partition import (
133        get_partition_info,
134        partition_pipe,
135    )
136    from ._pipes import (
137        fetch_pipes_keys,
138        create_indices,
139        drop_indices,
140        get_create_index_queries,
141        get_drop_index_queries,
142        delete_pipe,
143        rename_pipe,
144        get_pipe_data,
145        get_pipe_docs,
146        get_pipe_data_query,
147        register_pipe,
148        edit_pipe,
149        get_pipe_id,
150        get_pipe_attributes,
151        sync_pipe,
152        sync_pipe_inplace,
153        get_sync_time,
154        pipe_exists,
155        get_pipe_rowcount,
156        drop_pipe,
157        clear_pipe,
158        deduplicate_pipe,
159        get_pipe_table,
160        get_pipe_columns_types,
161        get_pipe_schema,
162        get_pipe_columns_indices,
163        get_temporary_target,
164        create_pipe_indices,
165        drop_pipe_indices,
166        get_pipe_index_names,
167    )
168    from ._plugins import (
169        get_plugins_pipe,
170        register_plugin,
171        delete_plugin,
172        get_plugin_id,
173        get_plugin_version,
174        get_plugins,
175        get_plugin_user_id,
176        get_plugin_username,
177        get_plugin_attributes,
178    )
179    from ._users import (
180        get_users_pipe,
181        register_user,
182        get_user_id,
183        get_users,
184        edit_user,
185        delete_user,
186        get_user_password_hash,
187        get_user_type,
188        get_user_attributes,
189    )
190    from ._uri import from_uri, parse_uri
191
192    def __init__(
193        self,
194        label: Optional[str] = None,
195        flavor: Optional[str] = None,
196        wait: bool = False,
197        connect: bool = False,
198        debug: bool = False,
199        **kw: Any
200    ):
201        """
202        Parameters
203        ----------
204        label: str, default 'main'
205            The identifying label for the connector.
206            E.g. for `sql:main`, 'main' is the label.
207            Defaults to 'main'.
208
209        flavor: Optional[str], default None
210            The database flavor, e.g.
211            `'sqlite'`, `'postgresql'`, `'cockroachdb'`, etc.
212            To see supported flavors, run the `bootstrap connectors` command.
213
214        wait: bool, default False
215            If `True`, block until a database connection has been made.
216            Defaults to `False`.
217
218        connect: bool, default False
219            If `True`, immediately attempt to connect the database and raise
220            a warning if the connection fails.
221            Defaults to `False`.
222
223        debug: bool, default False
224            Verbosity toggle.
225            Defaults to `False`.
226
227        kw: Any
228            All other arguments will be passed to the connector's attributes.
229            Therefore, a connector may be made without being registered,
230            as long enough parameters are supplied to the constructor.
231        """
232        if 'uri' in kw:
233            uri = kw['uri']
234            if uri.startswith('postgres') and not uri.startswith('postgresql'):
235                uri = uri.replace('postgres', 'postgresql', 1)
236            if uri.startswith('postgresql') and not uri.startswith('postgresql+'):
237                uri = uri.replace('postgresql://', 'postgresql+psycopg://', 1)
238            if uri.startswith('timescaledb://'):
239                uri = uri.replace('timescaledb://', 'postgresql+psycopg://', 1)
240                flavor = 'timescaledb'
241            if uri.startswith('timescaledb-ha://'):
242                uri = uri.replace('timescaledb-ha://', 'postgresql+psycopg://', 1)
243                flavor = 'timescaledb-ha'
244            if uri.startswith('postgis://'):
245                uri = uri.replace('postgis://', 'postgresql+psycopg://', 1)
246                flavor = 'postgis'
247            kw['uri'] = uri
248            from_uri_params = self.from_uri(kw['uri'], as_dict=True)
249            label = label or from_uri_params.get('label', None)
250            _ = from_uri_params.pop('label', None)
251
252            ### Sometimes the flavor may be provided with a URI.
253            kw.update(from_uri_params)
254            if flavor:
255                kw['flavor'] = flavor
256            ### `?protected=true` marks the connector (`Connector.protected`); the driver must
257            ### not see it.
258            if 'protected' in from_uri_params:
259                kw['uri'] = _strip_uri_param(kw['uri'], 'protected')
260
261        ### set __dict__ in base class
262        super().__init__(
263            'sql',
264            label = label or self.__dict__.get('label', None),
265            **kw
266        )
267
268        if self.__dict__.get('flavor', None) in ('sqlite', 'geopackage'):
269            self._reset_attributes()
270            self._set_attributes(
271                'sql',
272                label = label,
273                inherit_default = False,
274                **kw
275            )
276            ### For backwards compatability reasons, set the path for sql:local if its missing.
277            if (
278                self.label == 'local'
279                and self.__dict__.get('database', None) in (None, '{SQLITE_DB_PATH}')
280            ):
281                import meerschaum.config.paths as paths
282                self.database = paths.SQLITE_DB_PATH.as_posix()
283
284        ### A `uri` decides where the connection goes (v4's engine is built from it alone), so
285        ### its scheme must also decide the dialect when it names another driver family than the
286        ### label's configured flavor (`MRSM_SQL_MAIN=sqlite:///x.db` on a `timescaledb-ha`
287        ### default config). v4 kept the configured flavor and generated SQL for the wrong
288        ### dialect; a flavor of the same family (`postgresql://` for `timescaledb-ha`) is kept.
289        if self.__dict__.get('uri') and self.__dict__.get('flavor'):
290            try:
291                uri_flavor = self.parse_uri(self.__dict__['uri']).get('flavor', None)
292            except Exception:
293                uri_flavor = None
294            if (
295                uri_flavor in _FLAVOR_FAMILIES or uri_flavor in _RUST_FLAVORS
296            ) and _flavor_family(uri_flavor) != _flavor_family(self.__dict__['flavor']):
297                self.__dict__['flavor'] = uri_flavor
298
299        ### ensure flavor and label are set accordingly
300        if 'flavor' not in self.__dict__:
301            if flavor is None and 'uri' not in self.__dict__:
302                raise ValueError(
303                    f"    Missing flavor. Provide flavor as a key for '{self}'."
304                )
305            self.flavor = flavor or self.parse_uri(self.__dict__['uri']).get('flavor', None)
306
307        if self.flavor == 'postgres':
308            self.flavor = 'postgresql'
309
310        self._debug = debug
311        ### Store the PID and thread at initialization
312        ### so we can dispose of the Pool in child processes or threads.
313        import os
314        import threading
315        self._pid = os.getpid()
316        self._thread_ident = threading.current_thread().ident
317        self._sessions = {}
318        self._locks = {'_sessions': threading.RLock(), }
319
320        ### verify the flavor's requirements are met
321        if self.flavor not in self.flavor_configs:
322            error(f"Flavor '{self.flavor}' is not supported by Meerschaum SQLConnector")
323        if not self.__dict__.get('uri'):
324            self.verify_attributes(
325                self.flavor_configs[self.flavor].get('requirements', set()),
326                debug=debug,
327            )
328
329        if wait:
330            from meerschaum.connectors.poll import retry_connect
331            retry_connect(connector=self, debug=debug)
332
333        if connect:
334            if not self.test_connection(debug=debug):
335                warn(f"Failed to connect with connector '{self}'!", stack=False)
336
337    @property
338    def Session(self):
339        if '_Session' not in self.__dict__:
340            if self.engine is None:
341                return None
342
343            from meerschaum.utils.packages import attempt_import
344            sqlalchemy_orm = attempt_import('sqlalchemy.orm', lazy=False)
345            session_factory = sqlalchemy_orm.sessionmaker(self.engine)
346            self._Session = sqlalchemy_orm.scoped_session(session_factory)
347
348        return self._Session
349
350    @property
351    def engine(self):
352        """
353        Return the SQLAlchemy engine connected to the configured database (the `sql` extra).
354
355        `read()`, `exec()`, `value()`, `exec_queries()` and `to_sql()` do not use it: they run on the
356        connector's Rust connection pool (see `meerschaum.connectors.sql._native`). The engine
357        opens the database through Python's own driver. On SQLite that is Python's `sqlite3`
358        library, a second copy of SQLite in the process: do not write the connector's file through
359        the engine while the process also reads or writes it through `Pipe` methods or `read()` /
360        `exec()` (two SQLite libraries keep separate lock bookkeeping for one file, which can
361        corrupt it; sqlite.org/howtocorrupt.html, 2.2.1).
362        """
363        import os
364        import threading
365        if self.flavor == 'duckdb':
366            from ._duckdb_transport import guard_sdk
367            guard_sdk()
368        if '_engine' not in self.__dict__:
369            try:
370                self._engine, self._engine_str = self.create_engine(include_uri=True)
371            except ImportError as e:
372                ### A property must raise `AttributeError` for `hasattr(conn, 'engine')` to be
373                ### `False`; Python cannot make one exception both an `ImportError` and an
374                ### `AttributeError`, so the message names the `sql` extra instead.
375                raise AttributeError(str(e)) from e
376
377        same_process = os.getpid() == self._pid
378        same_thread = threading.current_thread().ident == self._thread_ident
379
380        ### handle child processes
381        if not same_process:
382            self._pid = os.getpid()
383            self._thread = threading.current_thread()
384            warn("Different PID detected. Disposing of connections...")
385            self._engine.dispose()
386
387        ### handle different threads
388        if not same_thread:
389            if self.flavor == 'duckdb':
390                warn("Different thread detected.")
391                self._engine.dispose()
392
393        return self._engine
394
395    @property
396    def DATABASE_URL(self) -> str:
397        """
398        Return the URI connection string (alias for `SQLConnector.URI`).
399        """
400        return self.URI
401
402    @property
403    def URI(self) -> str:
404        """
405        Return the URI connection string, built from the connector's attributes
406        (no SQLAlchemy needed).
407        """
408        if '_engine_str' not in self.__dict__:
409            from ._create_engine import get_engine_str
410            self._engine_str = get_engine_str(self)
411        return str(self._engine_str)
412
413    @property
414    def IS_THREAD_SAFE(self) -> str:
415        """
416        Return whether this connector may be multithreaded.
417        """
418        if self.flavor in ('duckdb', 'oracle'):
419            return False
420        if self.flavor in ('sqlite', 'geopackage'):
421            return (
422                ':memory:' not in self.URI
423                and self.__dict__.get('_memory_path', None) is None
424            )
425        return True
426
427    @property
428    def metadata(self):
429        """
430        Return the metadata bound to this configured schema.
431        """
432        from ._create_engine import import_sqlalchemy
433        sqlalchemy = import_sqlalchemy()
434        if '_metadata' not in self.__dict__:
435            self._metadata = sqlalchemy.MetaData(schema=self.schema)
436        return self._metadata
437
438    @property
439    def instance_schema(self):
440        """
441        Return the schema name for Meerschaum tables. 
442        """
443        return self.schema
444
445    @property
446    def internal_schema(self):
447        """
448        Return the schema name for internal tables. 
449        """
450        from meerschaum._internal.static import STATIC_CONFIG
451        from meerschaum.utils.sql import NO_SCHEMA_FLAVORS
452        schema_name = self.__dict__.get('internal_schema', None) or (
453            STATIC_CONFIG['sql']['internal_schema']
454            if self.flavor not in NO_SCHEMA_FLAVORS
455            else self.schema
456        )
457
458        if '_internal_schema' not in self.__dict__:
459            self._internal_schema = schema_name
460        return self._internal_schema
461
462    @property
463    def db(self) -> Optional[databases.Database]:
464        from meerschaum.utils.packages import attempt_import
465        databases = attempt_import('databases', lazy=False, install=True)
466        url = self.DATABASE_URL
467        if 'mysql' in url:
468            url = url.replace('+pymysql', '')
469        if '_db' not in self.__dict__:
470            try:
471                self._db = databases.Database(url)
472            except KeyError:
473                ### Likely encountered an unsupported flavor.
474                self._db = None
475        return self._db
476
477    @property
478    def db_version(self) -> Union[str, None]:
479        """
480        Return the database version.
481        """
482        _db_version = self.__dict__.get('_db_version', None)
483        if _db_version is not None:
484            return _db_version
485
486        from meerschaum.utils.sql import get_db_version
487        self._db_version = get_db_version(self)
488        return self._db_version
489
490    @property
491    def schema(self) -> Union[str, None]:
492        """
493        Return the default schema to use.
494        A value of `None` will not prepend a schema.
495        """
496        if 'schema' in self.__dict__:
497            return self.__dict__['schema']
498
499        from meerschaum.utils.sql import NO_SCHEMA_FLAVORS
500        if self.flavor in NO_SCHEMA_FLAVORS:
501            self.__dict__['schema'] = None
502            return None
503
504        ### Ask the database (`SELECT current_schema()` on the PostgreSQL family, `SELECT
505        ### SCHEMA_NAME()` on MSSQL), natively and once: a role's `search_path` or a login's
506        ### default schema is what v4's `sqlalchemy.inspect(engine).default_schema_name`
507        ### reports, and the base wheel has no SQLAlchemy. Raises when the database is unreachable.
508        _schema = self._core_connector().discover_schema()
509        self.__dict__['schema'] = _schema
510        self.__dict__['_schema_pending'] = False
511        return _schema
512
513    def get_metadata_cache_path(self, kind: str = 'json') -> pathlib.Path:
514        """
515        Return the path to the file to which to write metadata cache.
516        """
517        import meerschaum.config.paths as paths
518        filename = (
519            f'{self.label}-metadata.pkl'
520            if kind == 'pkl'
521            else f'{self.label}.json'
522        )
523        return paths.SQL_CONN_CACHE_RESOURCES_PATH / filename
524
525    def __getstate__(self):
526        if '_rust_connector' not in self.__dict__:
527            return self.__dict__
528        return {
529            k: v
530            for k, v in self.__dict__.items()
531            if k not in ('_rust_connector', '_rust_connector_pid')
532        }
533
534    def _shared_memory_database(self) -> Optional[str]:
535        """
536        For an in-memory SQLite connector (`database=':memory:'`), the path of the one database
537        file that SQLAlchemy and the Rust pool both open, so `Pipe` methods and `read()` /
538        `exec()` / `.engine` see the same tables. `None` for any other connector.
539
540        The Python `sqlite3` module and the extension each carry their own SQLite library, which
541        cannot share a `cache=shared` memory database, so the "memory" database is a file in a
542        private temporary directory (a RAM disk where the system has one) that is removed when
543        the connector is collected or the process exits.
544        """
545        if self.__dict__.get('flavor', None) != 'sqlite' or self.__dict__.get('uri', None):
546            return None
547        if self.__dict__.get('database', None) != ':memory:':
548            return None
549        path = self.__dict__.get('_memory_path', None)
550        if path is None:
551            import os
552            import tempfile
553            import weakref
554            shm = '/dev/shm'
555            ### 5.1: an isolated team's sandbox lets it use `/dev/shm` without listing it, so
556            ### its private directories go to the team's own temporary directory instead.
557            sandboxed = bool(os.environ.get('MRSM_TEAM_SANDBOX'))
558            base = (
559                shm
560                if not sandboxed and os.path.isdir(shm) and os.access(shm, os.W_OK)
561                else None
562            )
563            directory = tempfile.mkdtemp(prefix='mrsm_mem_', dir=base)
564            path = os.path.join(directory, 'memory.db')
565            self.__dict__['_memory_path'] = path
566            weakref.finalize(self, _remove_memory_directory, directory, os.getpid())
567        return path
568
569    def _core_connector(self, discover_schema: bool = True):
570        """
571        Return the `meerschaum._core.SqlConnector` behind this connector (built once per process,
572        see `crates/meerschaum-connector-sql`), which implements every pipe, user and plugin method.
573
574        Every flavor has a Rust driver (`mssql` and `oracle` are compiled into the wheels;
575        `duckdb` uses its public Python driver transport when installed, sharing a database
576        anchor with SQLAlchemy while keeping Pipe algorithms in Rust. Standalone / base
577        installs use DuckDB's C API. Explicit `MRSM_DUCKDB_LIB` pins native mode and refuses
578        mixed SQLAlchemy access; unset it and restart to use both). An in-memory SQLite database (`sql:memory`) is one database file that the Rust
579        pool and SQLAlchemy both open (`_shared_memory_database`), so `Pipe` methods and
580        `read()` / `exec()` / `.engine` see the same tables.
581        `read`, `exec`, `exec_queries`, `value` and `to_sql` run on this connector too (raw SQL,
582        `_native.NATIVE_SQL_FLAVORS`); only `.engine` (and the calls that hand out or take
583        SQLAlchemy objects) stays SQLAlchemy.
584
585        The Rust connector (and its pool) is built once per process: a forked child (a job
586        daemon) builds its own, like SQLAlchemy engines must.
587
588        Parameters
589        ----------
590        discover_schema: bool, default True
591            Ask the database for its default schema now (when none is configured) so `self.schema`
592            is the one the Rust methods use. `False` returns the connector without touching the
593            database (`meerschaum._internal.entry.adhoc_context`): its methods still ask for the
594            schema before they run.
595
596        Raises
597        ------
598        `RuntimeError` naming the cause when no driver can be built (the Oracle client library,
599        `libclntsh`, is not installed; an unknown flavor; a failed pool setup).
600        """
601        import os
602        rust = self.__dict__.get('_rust_connector', None)
603        if rust is False:
604            raise RuntimeError(self._rust_unavailable())
605        if rust is not None and self.__dict__.get('_rust_connector_pid', None) != os.getpid():
606            rust = None
607        if rust is None:
608            from meerschaum import _core
609            if self.flavor not in _RUST_FLAVORS:
610                self.__dict__['_rust_connector'] = False
611                self.__dict__['_rust_error'] = f"the flavor '{self.flavor}' has no Rust driver"
612                raise RuntimeError(self._rust_unavailable())
613            if self.flavor == 'oracle' and not _oracle_client_available():
614                self.__dict__['_rust_connector'] = False
615                self.__dict__['_rust_error'] = (
616                    "the Oracle client library (libclntsh, e.g. Oracle Instant Client) "
617                    "is not installed; install it and make it loadable "
618                    "(`LD_LIBRARY_PATH` / `ldconfig`) to use `oracle` instances"
619                )
620                raise RuntimeError(self._rust_unavailable())
621            attributes = {key: value for key, value in self.meta.items()
622                          if key not in ('type', 'label')}
623            ### The core reads `protected` as text (`True` / `'true'` both mark it).
624            if attributes.get('protected') is not None:
625                attributes['protected'] = str(attributes['protected'])
626            if self.flavor == 'duckdb':
627                from ._duckdb_transport import prepare_connector
628                attributes['_duckdb_memory_id'] = prepare_connector(self)
629                attributes['_duckdb_database'] = self.__dict__.get('_duckdb_database')
630            if (shared := self._shared_memory_database()) is not None:
631                attributes['database'] = shared
632            ### Only a configured schema: the Rust connector discovers the default itself.
633            attributes['schema'] = self.__dict__.get('schema', None)
634            try:
635                rust = _core.SqlConnector(self.label, attributes)
636            except Exception as e:
637                self.__dict__['_rust_connector'] = False
638                self.__dict__['_rust_error'] = str(e)
639                raise RuntimeError(self._rust_unavailable()) from e
640            self.__dict__['_rust_connector'] = rust
641            self.__dict__['_rust_connector_pid'] = os.getpid()
642            from meerschaum.utils.sql import NO_SCHEMA_FLAVORS
643            self.__dict__['_schema_pending'] = (
644                not attributes['schema'] and self.flavor not in NO_SCHEMA_FLAVORS
645            )
646        if discover_schema and self.__dict__.get('_schema_pending', False):
647            ### The default schema is asked of the database before the first query runs, so the
648            ### Rust methods see the same schema as `self.schema`. While the database cannot be
649            ### asked, nothing runs: the flavor default (`public` / `dbo`) is the wrong schema
650            ### for a role with another `search_path`, and a write would create duplicates.
651            try:
652                self.__dict__['schema'] = rust.discover_schema()
653            except Exception as e:
654                raise RuntimeError(
655                    f"Could not determine the default schema of '{self}': {e}"
656                ) from e
657            self.__dict__['_schema_pending'] = False
658        return rust
659
660    def _rust_unavailable(self) -> str:
661        """The error text of a connector that has no usable Rust driver."""
662        cause = self.__dict__.get('_rust_error', None)
663        return (
664            f"Cannot use the SQL connector '{self}': no usable Rust driver"
665            + (f" ({cause})." if cause else ".")
666        )
667
668    def _rust_method(self, name: str):
669        """
670        Return the `meerschaum._core.SqlConnector` method `name`. Raises `AttributeError` naming
671        the method when the extension does not define it (raw SQL goes through `_native`, which
672        calls the `sql_*` bindings) and `RuntimeError` when the connector has no usable Rust
673        driver (see `_core_connector`).
674        """
675        rust = self._core_connector()
676        try:
677            method = getattr(rust, name)
678        except AttributeError:
679            raise AttributeError(f"`_core.SqlConnector` has no method '{name}'.") from None
680        ### A façade method called with `debug=True` shows the Rust core's debug output for
681        ### the binding it calls, whether or not it passes `debug` on.
682        try:
683            import sys
684            debug = sys._getframe(1).f_locals.get('debug', False) is True
685        except Exception:
686            debug = False
687        if not debug:
688            return _with_instance_hint(self, method)
689
690        def _debug_call(*args, **kwargs):
691            from meerschaum._core import debugging
692            with debugging():
693                return method(*args, **kwargs)
694
695        return _with_instance_hint(self, _debug_call)
696
697    def __setstate__(self, d):
698        self.__dict__.update(d)
699
700    def __call__(self):
701        return self

Connect to SQL databases through the Rust connector's connection pool.

Raw SQL and pipe operations need no SQLAlchemy. The optional .engine property provides a SQLAlchemy engine for code that explicitly uses that interface.

SQLConnectors may be used as Meerschaum instance connectors. Read more about connectors and instances at https://meerschaum.io/reference/connectors/

SQLConnector( label: str | None = None, flavor: str | None = None, wait: bool = False, connect: bool = False, debug: bool = False, **kw: Any)
192    def __init__(
193        self,
194        label: Optional[str] = None,
195        flavor: Optional[str] = None,
196        wait: bool = False,
197        connect: bool = False,
198        debug: bool = False,
199        **kw: Any
200    ):
201        """
202        Parameters
203        ----------
204        label: str, default 'main'
205            The identifying label for the connector.
206            E.g. for `sql:main`, 'main' is the label.
207            Defaults to 'main'.
208
209        flavor: Optional[str], default None
210            The database flavor, e.g.
211            `'sqlite'`, `'postgresql'`, `'cockroachdb'`, etc.
212            To see supported flavors, run the `bootstrap connectors` command.
213
214        wait: bool, default False
215            If `True`, block until a database connection has been made.
216            Defaults to `False`.
217
218        connect: bool, default False
219            If `True`, immediately attempt to connect the database and raise
220            a warning if the connection fails.
221            Defaults to `False`.
222
223        debug: bool, default False
224            Verbosity toggle.
225            Defaults to `False`.
226
227        kw: Any
228            All other arguments will be passed to the connector's attributes.
229            Therefore, a connector may be made without being registered,
230            as long enough parameters are supplied to the constructor.
231        """
232        if 'uri' in kw:
233            uri = kw['uri']
234            if uri.startswith('postgres') and not uri.startswith('postgresql'):
235                uri = uri.replace('postgres', 'postgresql', 1)
236            if uri.startswith('postgresql') and not uri.startswith('postgresql+'):
237                uri = uri.replace('postgresql://', 'postgresql+psycopg://', 1)
238            if uri.startswith('timescaledb://'):
239                uri = uri.replace('timescaledb://', 'postgresql+psycopg://', 1)
240                flavor = 'timescaledb'
241            if uri.startswith('timescaledb-ha://'):
242                uri = uri.replace('timescaledb-ha://', 'postgresql+psycopg://', 1)
243                flavor = 'timescaledb-ha'
244            if uri.startswith('postgis://'):
245                uri = uri.replace('postgis://', 'postgresql+psycopg://', 1)
246                flavor = 'postgis'
247            kw['uri'] = uri
248            from_uri_params = self.from_uri(kw['uri'], as_dict=True)
249            label = label or from_uri_params.get('label', None)
250            _ = from_uri_params.pop('label', None)
251
252            ### Sometimes the flavor may be provided with a URI.
253            kw.update(from_uri_params)
254            if flavor:
255                kw['flavor'] = flavor
256            ### `?protected=true` marks the connector (`Connector.protected`); the driver must
257            ### not see it.
258            if 'protected' in from_uri_params:
259                kw['uri'] = _strip_uri_param(kw['uri'], 'protected')
260
261        ### set __dict__ in base class
262        super().__init__(
263            'sql',
264            label = label or self.__dict__.get('label', None),
265            **kw
266        )
267
268        if self.__dict__.get('flavor', None) in ('sqlite', 'geopackage'):
269            self._reset_attributes()
270            self._set_attributes(
271                'sql',
272                label = label,
273                inherit_default = False,
274                **kw
275            )
276            ### For backwards compatability reasons, set the path for sql:local if its missing.
277            if (
278                self.label == 'local'
279                and self.__dict__.get('database', None) in (None, '{SQLITE_DB_PATH}')
280            ):
281                import meerschaum.config.paths as paths
282                self.database = paths.SQLITE_DB_PATH.as_posix()
283
284        ### A `uri` decides where the connection goes (v4's engine is built from it alone), so
285        ### its scheme must also decide the dialect when it names another driver family than the
286        ### label's configured flavor (`MRSM_SQL_MAIN=sqlite:///x.db` on a `timescaledb-ha`
287        ### default config). v4 kept the configured flavor and generated SQL for the wrong
288        ### dialect; a flavor of the same family (`postgresql://` for `timescaledb-ha`) is kept.
289        if self.__dict__.get('uri') and self.__dict__.get('flavor'):
290            try:
291                uri_flavor = self.parse_uri(self.__dict__['uri']).get('flavor', None)
292            except Exception:
293                uri_flavor = None
294            if (
295                uri_flavor in _FLAVOR_FAMILIES or uri_flavor in _RUST_FLAVORS
296            ) and _flavor_family(uri_flavor) != _flavor_family(self.__dict__['flavor']):
297                self.__dict__['flavor'] = uri_flavor
298
299        ### ensure flavor and label are set accordingly
300        if 'flavor' not in self.__dict__:
301            if flavor is None and 'uri' not in self.__dict__:
302                raise ValueError(
303                    f"    Missing flavor. Provide flavor as a key for '{self}'."
304                )
305            self.flavor = flavor or self.parse_uri(self.__dict__['uri']).get('flavor', None)
306
307        if self.flavor == 'postgres':
308            self.flavor = 'postgresql'
309
310        self._debug = debug
311        ### Store the PID and thread at initialization
312        ### so we can dispose of the Pool in child processes or threads.
313        import os
314        import threading
315        self._pid = os.getpid()
316        self._thread_ident = threading.current_thread().ident
317        self._sessions = {}
318        self._locks = {'_sessions': threading.RLock(), }
319
320        ### verify the flavor's requirements are met
321        if self.flavor not in self.flavor_configs:
322            error(f"Flavor '{self.flavor}' is not supported by Meerschaum SQLConnector")
323        if not self.__dict__.get('uri'):
324            self.verify_attributes(
325                self.flavor_configs[self.flavor].get('requirements', set()),
326                debug=debug,
327            )
328
329        if wait:
330            from meerschaum.connectors.poll import retry_connect
331            retry_connect(connector=self, debug=debug)
332
333        if connect:
334            if not self.test_connection(debug=debug):
335                warn(f"Failed to connect with connector '{self}'!", stack=False)
Parameters
  • label (str, default 'main'): The identifying label for the connector. E.g. for sql:main, 'main' is the label. Defaults to 'main'.
  • flavor (Optional[str], default None): The database flavor, e.g. 'sqlite', 'postgresql', 'cockroachdb', etc. To see supported flavors, run the bootstrap connectors command.
  • wait (bool, default False): If True, block until a database connection has been made. Defaults to False.
  • connect (bool, default False): If True, immediately attempt to connect the database and raise a warning if the connection fails. Defaults to False.
  • debug (bool, default False): Verbosity toggle. Defaults to False.
  • kw (Any): All other arguments will be passed to the connector's attributes. Therefore, a connector may be made without being registered, as long enough parameters are supplied to the constructor.
Session
337    @property
338    def Session(self):
339        if '_Session' not in self.__dict__:
340            if self.engine is None:
341                return None
342
343            from meerschaum.utils.packages import attempt_import
344            sqlalchemy_orm = attempt_import('sqlalchemy.orm', lazy=False)
345            session_factory = sqlalchemy_orm.sessionmaker(self.engine)
346            self._Session = sqlalchemy_orm.scoped_session(session_factory)
347
348        return self._Session
engine
350    @property
351    def engine(self):
352        """
353        Return the SQLAlchemy engine connected to the configured database (the `sql` extra).
354
355        `read()`, `exec()`, `value()`, `exec_queries()` and `to_sql()` do not use it: they run on the
356        connector's Rust connection pool (see `meerschaum.connectors.sql._native`). The engine
357        opens the database through Python's own driver. On SQLite that is Python's `sqlite3`
358        library, a second copy of SQLite in the process: do not write the connector's file through
359        the engine while the process also reads or writes it through `Pipe` methods or `read()` /
360        `exec()` (two SQLite libraries keep separate lock bookkeeping for one file, which can
361        corrupt it; sqlite.org/howtocorrupt.html, 2.2.1).
362        """
363        import os
364        import threading
365        if self.flavor == 'duckdb':
366            from ._duckdb_transport import guard_sdk
367            guard_sdk()
368        if '_engine' not in self.__dict__:
369            try:
370                self._engine, self._engine_str = self.create_engine(include_uri=True)
371            except ImportError as e:
372                ### A property must raise `AttributeError` for `hasattr(conn, 'engine')` to be
373                ### `False`; Python cannot make one exception both an `ImportError` and an
374                ### `AttributeError`, so the message names the `sql` extra instead.
375                raise AttributeError(str(e)) from e
376
377        same_process = os.getpid() == self._pid
378        same_thread = threading.current_thread().ident == self._thread_ident
379
380        ### handle child processes
381        if not same_process:
382            self._pid = os.getpid()
383            self._thread = threading.current_thread()
384            warn("Different PID detected. Disposing of connections...")
385            self._engine.dispose()
386
387        ### handle different threads
388        if not same_thread:
389            if self.flavor == 'duckdb':
390                warn("Different thread detected.")
391                self._engine.dispose()
392
393        return self._engine

Return the SQLAlchemy engine connected to the configured database (the sql extra).

read(), exec(), value(), exec_queries() and to_sql() do not use it: they run on the connector's Rust connection pool (see meerschaum.connectors.sql._native). The engine opens the database through Python's own driver. On SQLite that is Python's sqlite3 library, a second copy of SQLite in the process: do not write the connector's file through the engine while the process also reads or writes it through Pipe methods or read() / exec() (two SQLite libraries keep separate lock bookkeeping for one file, which can corrupt it; sqlite.org/howtocorrupt.html, 2.2.1).

DATABASE_URL: str
395    @property
396    def DATABASE_URL(self) -> str:
397        """
398        Return the URI connection string (alias for `SQLConnector.URI`).
399        """
400        return self.URI

Return the URI connection string (alias for SQLConnector.URI).

URI: str
402    @property
403    def URI(self) -> str:
404        """
405        Return the URI connection string, built from the connector's attributes
406        (no SQLAlchemy needed).
407        """
408        if '_engine_str' not in self.__dict__:
409            from ._create_engine import get_engine_str
410            self._engine_str = get_engine_str(self)
411        return str(self._engine_str)

Return the URI connection string, built from the connector's attributes (no SQLAlchemy needed).

IS_THREAD_SAFE: str
413    @property
414    def IS_THREAD_SAFE(self) -> str:
415        """
416        Return whether this connector may be multithreaded.
417        """
418        if self.flavor in ('duckdb', 'oracle'):
419            return False
420        if self.flavor in ('sqlite', 'geopackage'):
421            return (
422                ':memory:' not in self.URI
423                and self.__dict__.get('_memory_path', None) is None
424            )
425        return True

Return whether this connector may be multithreaded.

metadata
427    @property
428    def metadata(self):
429        """
430        Return the metadata bound to this configured schema.
431        """
432        from ._create_engine import import_sqlalchemy
433        sqlalchemy = import_sqlalchemy()
434        if '_metadata' not in self.__dict__:
435            self._metadata = sqlalchemy.MetaData(schema=self.schema)
436        return self._metadata

Return the metadata bound to this configured schema.

instance_schema
438    @property
439    def instance_schema(self):
440        """
441        Return the schema name for Meerschaum tables. 
442        """
443        return self.schema

Return the schema name for Meerschaum tables.

internal_schema
445    @property
446    def internal_schema(self):
447        """
448        Return the schema name for internal tables. 
449        """
450        from meerschaum._internal.static import STATIC_CONFIG
451        from meerschaum.utils.sql import NO_SCHEMA_FLAVORS
452        schema_name = self.__dict__.get('internal_schema', None) or (
453            STATIC_CONFIG['sql']['internal_schema']
454            if self.flavor not in NO_SCHEMA_FLAVORS
455            else self.schema
456        )
457
458        if '_internal_schema' not in self.__dict__:
459            self._internal_schema = schema_name
460        return self._internal_schema

Return the schema name for internal tables.

db: 'Optional[databases.Database]'
462    @property
463    def db(self) -> Optional[databases.Database]:
464        from meerschaum.utils.packages import attempt_import
465        databases = attempt_import('databases', lazy=False, install=True)
466        url = self.DATABASE_URL
467        if 'mysql' in url:
468            url = url.replace('+pymysql', '')
469        if '_db' not in self.__dict__:
470            try:
471                self._db = databases.Database(url)
472            except KeyError:
473                ### Likely encountered an unsupported flavor.
474                self._db = None
475        return self._db
db_version: str | None
477    @property
478    def db_version(self) -> Union[str, None]:
479        """
480        Return the database version.
481        """
482        _db_version = self.__dict__.get('_db_version', None)
483        if _db_version is not None:
484            return _db_version
485
486        from meerschaum.utils.sql import get_db_version
487        self._db_version = get_db_version(self)
488        return self._db_version

Return the database version.

schema: str | None
490    @property
491    def schema(self) -> Union[str, None]:
492        """
493        Return the default schema to use.
494        A value of `None` will not prepend a schema.
495        """
496        if 'schema' in self.__dict__:
497            return self.__dict__['schema']
498
499        from meerschaum.utils.sql import NO_SCHEMA_FLAVORS
500        if self.flavor in NO_SCHEMA_FLAVORS:
501            self.__dict__['schema'] = None
502            return None
503
504        ### Ask the database (`SELECT current_schema()` on the PostgreSQL family, `SELECT
505        ### SCHEMA_NAME()` on MSSQL), natively and once: a role's `search_path` or a login's
506        ### default schema is what v4's `sqlalchemy.inspect(engine).default_schema_name`
507        ### reports, and the base wheel has no SQLAlchemy. Raises when the database is unreachable.
508        _schema = self._core_connector().discover_schema()
509        self.__dict__['schema'] = _schema
510        self.__dict__['_schema_pending'] = False
511        return _schema

Return the default schema to use. A value of None will not prepend a schema.

def get_metadata_cache_path(self, kind: str = 'json') -> pathlib.Path:
513    def get_metadata_cache_path(self, kind: str = 'json') -> pathlib.Path:
514        """
515        Return the path to the file to which to write metadata cache.
516        """
517        import meerschaum.config.paths as paths
518        filename = (
519            f'{self.label}-metadata.pkl'
520            if kind == 'pkl'
521            else f'{self.label}.json'
522        )
523        return paths.SQL_CONN_CACHE_RESOURCES_PATH / filename

Return the path to the file to which to write metadata cache.

flavor_configs = {'timescaledb': {'engine': 'postgresql+psycopg', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 5432}}, 'timescaledb-ha': {'engine': 'postgresql+psycopg', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 5432}}, 'postgresql': {'engine': 'postgresql+psycopg', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 5432}}, 'postgis': {'engine': 'postgresql+psycopg', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 5432}}, 'citus': {'engine': 'postgresql+psycopg', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 5432}}, 'mssql': {'engine': 'mssql+pyodbc', 'create_engine': {'fast_executemany': True, 'use_insertmanyvalues': False, 'isolation_level': 'AUTOCOMMIT', 'use_setinputsizes': False, 'pool_pre_ping': True, 'ignore_no_transaction_on_rollback': True}, 'omit_create_engine': {'method'}, 'to_sql': {'method': None}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 1433, 'options': 'driver=ODBC Driver 18 for SQL Server&UseFMTONLY=Yes&TrustServerCertificate=yes&Encrypt=no&MARS_Connection=yes'}}, 'mysql': {'engine': 'mysql+pymysql', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {'method': 'multi'}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 3306}}, 'mariadb': {'engine': 'mysql+pymysql', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {'method': 'multi'}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 3306}}, 'oracle': {'engine': 'oracle+oracledb', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {'method': None}, 'requirements': {'host', 'database', 'password', 'username'}, 'defaults': {'port': 1521}}, 'sqlite': {'engine': 'sqlite', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {'method': 'multi'}, 'requirements': {'database'}, 'defaults': {}}, 'geopackage': {'engine': 'sqlite', 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'omit_create_engine': {'method'}, 'to_sql': {'method': 'multi'}, 'requirements': {'database'}, 'defaults': {}}, 'duckdb': {'engine': 'duckdb', 'create_engine': {}, 'omit_create_engine': {'ALL'}, 'to_sql': {'method': 'multi'}, 'requirements': '', 'defaults': {}}, 'cockroachdb': {'engine': 'cockroachdb', 'omit_create_engine': {'method'}, 'create_engine': {'pool_size': 2, 'max_overflow': 2, 'pool_recycle': 3600, 'connect_args': {}}, 'to_sql': {'method': 'multi'}, 'requirements': {'host'}, 'defaults': {'port': 26257, 'database': 'defaultdb', 'username': 'root', 'password': 'admin'}}}
def create_engine( self, include_uri: bool = False, debug: bool = False, **kw) -> 'sqlalchemy.engine.Engine':
136def create_engine(
137    self,
138    include_uri: bool = False,
139    debug: bool = False,
140    **kw
141) -> 'sqlalchemy.engine.Engine':
142    """Create a sqlalchemy engine by building the engine string."""
143    from meerschaum.utils.packages import attempt_import
144    from meerschaum.utils.warnings import error, warn
145    if self.flavor == 'duckdb':
146        from ._duckdb_transport import guard_sdk, validate_connector_uri
147        guard_sdk()
148        validate_connector_uri(self)
149        for source in (kw, self._sys_config.get('create_engine', {})):
150            if any(source.get(key) is not None for key in ('creator', 'module')):
151                raise RuntimeError('DuckDB custom creator/module overrides cannot share the native driver safely.')
152    sqlalchemy = import_sqlalchemy()
153    import urllib
154    import copy
155    ### Install and patch required drivers.
156    if self.flavor in install_flavor_drivers:
157        _ = attempt_import(
158            *install_flavor_drivers[self.flavor],
159            debug=debug,
160            lazy=False,
161            warn=False,
162        )
163        if self.flavor == 'mssql':
164            _init_mssql_sqlalchemy()
165
166    engine_str = get_engine_str(self)
167    _password = self.__dict__.get('password', None)
168
169    ### Handle registering specific dialects (due to installing in virtual environments).
170    if self.flavor in flavor_dialects:
171        sqlalchemy.dialects.registry.register(*flavor_dialects[self.flavor])
172
173    if self.flavor in ("sqlite", "geopackage"):
174        if 'create_engine' not in self._sys_config:
175            self._sys_config['create_engine'] = {}
176        if 'connect_args' not in self._sys_config['create_engine']:
177            self._sys_config['create_engine']['connect_args'] = {}
178        self._sys_config['create_engine']['connect_args'].update({"check_same_thread": False})
179
180    if debug:
181        dprint(
182            (
183                (engine_str.replace(':' + _password, ':' + ('*' * len(_password))))
184                    if _password is not None else engine_str
185            ) + '\n' + f"{self._sys_config.get('create_engine', {}).get('connect_args', {})}"
186        )
187
188    _kw_copy = copy.deepcopy(kw)
189
190    ### NOTE: Order of inheritance:
191    ###       1. Defaults
192    ###       2. System configuration
193    ###       3. Connector configuration
194    ###       4. Keyword arguments
195    # Flavor defaults may share nested dictionaries across SQL dialects. Per-connector
196    # overrides must not mutate STATIC_CONFIG or affect engines created afterwards.
197    _create_engine_args = copy.deepcopy(
198        flavor_configs.get(self.flavor, {}).get('create_engine', {})
199    )
200    def _apply_create_engine_args(update):
201        if self.flavor == 'duckdb' or 'ALL' not in flavor_configs[self.flavor].get('omit_create_engine', {}):
202            _create_engine_args.update(
203                { k: v for k, v in update.items()
204                    if 'omit_create_engine' not in flavor_configs[self.flavor]
205                        or k not in flavor_configs[self.flavor].get('omit_create_engine')
206                }
207            )
208    _apply_create_engine_args(self._sys_config.get('create_engine', {}))
209    _apply_create_engine_args(self.__dict__.get('create_engine', {}))
210    _apply_create_engine_args(_kw_copy)
211
212    if self.flavor == 'duckdb':
213        # Historical system config includes pandas.to_sql's method, not an engine option.
214        _create_engine_args.pop('method', None)
215
216    duckdb_creator = None
217    if self.flavor == 'duckdb':
218        if any(_create_engine_args.get(key) is not None for key in ('creator', 'module')):
219            raise RuntimeError('DuckDB custom creator/module overrides cannot share the native driver safely.')
220        duckdb_creator = []
221        # SQLAlchemy constructs engines lazily; bind the shared creator before first checkout.
222        _create_engine_args['creator'] = lambda: duckdb_creator[0]()
223
224    try:
225        engine = sqlalchemy.create_engine(
226            engine_str,
227            ### I know this looks confusing, and maybe it's bad code,
228            ### but it's simple. It dynamically parses the config string
229            ### and splits it to separate the class name (QueuePool)
230            ### from the module name (sqlalchemy.pool).
231            poolclass    = getattr(
232                attempt_import(
233                    ".".join(self._sys_config['poolclass'].split('.')[:-1])
234                ),
235                self._sys_config['poolclass'].split('.')[-1]
236            ),
237            echo         = debug,
238            **_create_engine_args
239        )
240    except Exception:
241        warn(f"Failed to create connector '{self}':\n{traceback.format_exc()}", stack=False)
242        engine = None
243
244    if engine is not None and duckdb_creator is not None:
245        from ._duckdb_transport import engine_creator
246        args = dict(_create_engine_args)
247        args.pop('creator', None)
248        try:
249            duckdb_creator.append(engine_creator(self, engine, args))
250        except BaseException:
251            engine.dispose()
252            raise
253
254    if include_uri:
255        return engine, engine_str
256    return engine

Create a sqlalchemy engine by building the engine string.

def read( self, query_or_table: 'Union[str, sqlalchemy.Query]', params: Dict[str, Any] | List[str] | None = None, dtype: Dict[str, Any] | None = None, coerce_float: bool = True, chunksize: int | None = -1, workers: int | None = None, chunk_hook: Callable[[pandas.DataFrame], Any] | None = None, as_hook_results: bool = False, chunks: int | None = None, schema: str | None = None, as_chunks: bool = False, as_iterator: bool = False, as_dask: bool = False, index_col: str | None = None, silent: bool = False, debug: bool = False, as_polars: bool | None = None, as_pandas: bool | None = None, **kw: Any) -> 'Union[pandas.DataFrame, dask.DataFrame, List[pandas.DataFrame], List[Any], None]':
147def read(
148    self,
149    query_or_table: Union[str, sqlalchemy.Query],
150    params: Union[Dict[str, Any], List[str], None] = None,
151    dtype: Optional[Dict[str, Any]] = None,
152    coerce_float: bool = True,
153    chunksize: Optional[int] = -1,
154    workers: Optional[int] = None,
155    chunk_hook: Optional[Callable[[pandas.DataFrame], Any]] = None,
156    as_hook_results: bool = False,
157    chunks: Optional[int] = None,
158    schema: Optional[str] = None,
159    as_chunks: bool = False,
160    as_iterator: bool = False,
161    as_dask: bool = False,
162    index_col: Optional[str] = None,
163    silent: bool = False,
164    debug: bool = False,
165    as_polars: Optional[bool] = None,
166    as_pandas: Optional[bool] = None,
167    **kw: Any
168) -> Union[
169    pandas.DataFrame,
170    dask.DataFrame,
171    List[pandas.DataFrame],
172    List[Any],
173    None,
174]:
175    """
176    Read a SQL query or table into a DataFrame (Polars or pandas, see `as_polars`).
177
178    The query runs on the connector's Rust connection pool (the one `Pipe` methods use) for every
179    flavor in `meerschaum.connectors.sql._native.NATIVE_SQL_FLAVORS`, so no SQLAlchemy is needed;
180    the frame is the one Meerschaum 4 built with `pd.read_sql_query()` (same columns, dtypes and
181    values) when the result is pandas.
182
183    Parameters
184    ----------
185    query_or_table: Union[str, sqlalchemy.Query]
186        The SQL query (text, or a SQLAlchemy construct such as `text()` or `select()`) or the name
187        of the table from which to select.
188
189    params: Union[Dict[str, Any], List[Any], None], default None
190        The query's parameters: a dictionary for `:name` placeholders (SQLAlchemy's style, also
191        `%(name)s`), or a list / tuple of values for `?` (or `%s`) placeholders, in order.
192
193    dtype: Optional[Dict[str, Any]], default None
194        A dictionary of pandas data types to cast columns to (`DataFrame.astype()`).
195        For Polars results, declared `json` and `geometry` columns.
196
197    chunksize: Optional[int], default -1
198        How many chunks to read at a time. `None` will read everything in one large chunk.
199        Defaults to system configuration.
200
201        **NOTE:** DuckDB does not allow for chunking.
202
203    workers: Optional[int], default None
204        How many threads to use when consuming the generator.
205        Only applies if `chunk_hook` is provided.
206
207    chunk_hook: Optional[Callable[[pandas.DataFrame], Any]], default None
208        Hook function to execute once per chunk, e.g. writing and reading chunks intermittently.
209        See `--sync-chunks` for an example.
210        **NOTE:** `as_iterator` MUST be False (default).
211
212    as_hook_results: bool, default False
213        If `True`, return a `List` of the outputs of the hook function.
214        Only applicable if `chunk_hook` is not None.
215
216        **NOTE:** `as_iterator` MUST be `False` (default).
217
218    chunks: Optional[int], default None
219        Limit the number of chunks to read into memory, i.e. how many chunks to retrieve and
220        return into a single dataframe.
221        For example, to limit the returned dataframe to 100,000 rows,
222        you could specify a `chunksize` of `1000` and `chunks` of `100`.
223
224    schema: Optional[str], default None
225        If just a table name is provided, optionally specify the table schema.
226        Defaults to `SQLConnector.schema`.
227
228    as_chunks: bool, default False
229        If `True`, return a list of DataFrames.
230        Otherwise return a single DataFrame.
231
232    as_iterator: bool, default False
233        If `True`, return the pandas DataFrame iterator.
234        `chunksize` must not be `None` (falls back to 1000 if so),
235        and hooks are not called in this case.
236
237    index_col: Optional[str], default None
238        Make this column the index of a pandas result (with Dask, the index column).
239
240    silent: bool, default False
241        If `True`, return `None` instead of raising when the query fails, without a warning
242        (Meerschaum 4's behavior). By default, database errors raise.
243
244    as_polars: Optional[bool], default None
245        `True` returns Polars frames, `False` pandas; `None` follows the `dataframe` setting
246        (`meerschaum.utils.dataframe.get_dataframe_library()`).
247
248    as_pandas: Optional[bool], default None
249        `True` returns pandas frames, `False` Polars; `None` follows the setting.
250
251    Returns
252    -------
253    A DataFrame (default case), or an iterator, or a list of dataframes / iterators.
254    Raises the database error if the query fails (`None` with `silent=True`): a PEP 249 exception
255    (`meerschaum.connectors.sql.OperationalError`, `ProgrammingError`, `IntegrityError`, ...;
256    also an instance of SQLAlchemy's class of the same name when SQLAlchemy is imported).
257    On a protected connector (`protected: true`) without the allowance (`--allow-protected`,
258    `MRSM_ALLOW_PROTECTED=1`, `meerschaum.connectors.allow_protected()`), the query must be one
259    read statement (else `PermissionError`), and it runs in a transaction that is rolled back
260    (read-only on PostgreSQL and MySQL / MariaDB).
261
262    """
263    from meerschaum.connectors.sql import _native
264    if _native.uses_native(self):
265        from meerschaum.utils.packages import pandas_name
266        if 'dask' not in pandas_name():
267            return _native.read(
268                self,
269                query_or_table,
270                params=params,
271                dtype=dtype,
272                coerce_float=coerce_float,
273                chunksize=chunksize,
274                workers=workers,
275                chunk_hook=chunk_hook,
276                as_hook_results=as_hook_results,
277                chunks=chunks,
278                schema=schema,
279                as_chunks=as_chunks,
280                as_iterator=as_iterator,
281                index_col=index_col,
282                silent=silent,
283                debug=debug,
284                as_polars=as_polars,
285                as_pandas=as_pandas,
286                **kw
287            )
288        _native.fallback(self, 'read', 'the configured pandas implementation is Dask', debug)
289    result = _sqlalchemy_read(
290        self,
291        query_or_table,
292        params=params,
293        dtype=dtype,
294        coerce_float=coerce_float,
295        chunksize=chunksize,
296        workers=workers,
297        chunk_hook=chunk_hook,
298        as_hook_results=as_hook_results,
299        chunks=chunks,
300        schema=schema,
301        as_chunks=as_chunks,
302        as_iterator=as_iterator,
303        as_dask=as_dask,
304        index_col=index_col,
305        silent=silent,
306        debug=debug,
307        **kw
308    )
309    return _as_library(result, as_polars, as_pandas)

Read a SQL query or table into a DataFrame (Polars or pandas, see as_polars).

The query runs on the connector's Rust connection pool (the one Pipe methods use) for every flavor in meerschaum.connectors.sql._native.NATIVE_SQL_FLAVORS, so no SQLAlchemy is needed; the frame is the one Meerschaum 4 built with pd.read_sql_query() (same columns, dtypes and values) when the result is pandas.

Parameters
  • query_or_table (Union[str, sqlalchemy.Query]): The SQL query (text, or a SQLAlchemy construct such as text() or select()) or the name of the table from which to select.
  • params (Union[Dict[str, Any], List[Any], None], default None): The query's parameters: a dictionary for :name placeholders (SQLAlchemy's style, also %(name)s), or a list / tuple of values for ? (or %s) placeholders, in order.
  • dtype (Optional[Dict[str, Any]], default None): A dictionary of pandas data types to cast columns to (DataFrame.astype()). For Polars results, declared json and geometry columns.
  • chunksize (Optional[int], default -1): How many chunks to read at a time. None will read everything in one large chunk. Defaults to system configuration.

    NOTE: DuckDB does not allow for chunking.

  • workers (Optional[int], default None): How many threads to use when consuming the generator. Only applies if chunk_hook is provided.
  • chunk_hook (Optional[Callable[[pandas.DataFrame], Any]], default None): Hook function to execute once per chunk, e.g. writing and reading chunks intermittently. See --sync-chunks for an example. NOTE: as_iterator MUST be False (default).
  • as_hook_results (bool, default False): If True, return a List of the outputs of the hook function. Only applicable if chunk_hook is not None.

    NOTE: as_iterator MUST be False (default).

  • chunks (Optional[int], default None): Limit the number of chunks to read into memory, i.e. how many chunks to retrieve and return into a single dataframe. For example, to limit the returned dataframe to 100,000 rows, you could specify a chunksize of 1000 and chunks of 100.
  • schema (Optional[str], default None): If just a table name is provided, optionally specify the table schema. Defaults to SQLConnector.schema.
  • as_chunks (bool, default False): If True, return a list of DataFrames. Otherwise return a single DataFrame.
  • as_iterator (bool, default False): If True, return the pandas DataFrame iterator. chunksize must not be None (falls back to 1000 if so), and hooks are not called in this case.
  • index_col (Optional[str], default None): Make this column the index of a pandas result (with Dask, the index column).
  • silent (bool, default False): If True, return None instead of raising when the query fails, without a warning (Meerschaum 4's behavior). By default, database errors raise.
  • as_polars (Optional[bool], default None): True returns Polars frames, False pandas; None follows the dataframe setting (meerschaum.utils.dataframe.get_dataframe_library()).
  • as_pandas (Optional[bool], default None): True returns pandas frames, False Polars; None follows the setting.
Returns
  • A DataFrame (default case), or an iterator, or a list of dataframes / iterators.
  • Raises the database error if the query fails (None with silent=True) (a PEP 249 exception):

  • (meerschaum.connectors.sql.OperationalError, ProgrammingError, IntegrityError, ...;

  • also an instance of SQLAlchemy's class of the same name when SQLAlchemy is imported).
  • **On a protected connector (protected** (true) without the allowance (--allow-protected,):

  • MRSM_ALLOW_PROTECTED=1, meerschaum.connectors.allow_protected()), the query must be one

  • read statement (else PermissionError), and it runs in a transaction that is rolled back
  • (read-only on PostgreSQL and MySQL / MariaDB).
def value(self, query: str, *args: Any, use_pandas: bool = False, **kw: Any) -> Any:
672def value(
673    self,
674    query: str,
675    *args: Any,
676    use_pandas: bool = False,
677    **kw: Any
678) -> Any:
679    """
680    Execute the provided query and return the first value.
681
682    Parameters
683    ----------
684    query: str
685        The SQL query to execute.
686        
687    *args: Any
688        The arguments passed to `meerschaum.connectors.sql.SQLConnector.exec`
689        if `use_pandas` is `False` (default) or to `meerschaum.connectors.sql.SQLConnector.read`.
690        
691    use_pandas: bool, default False
692        If `True`, use `meerschaum.connectors.SQLConnector.read`, otherwise use
693        `meerschaum.connectors.sql.SQLConnector.exec` (default).
694        **NOTE:** This is always `True` for DuckDB.
695
696    **kw: Any
697        See `args`. `silent=True` returns `None` instead of raising when the query fails.
698
699    Returns
700    -------
701    Any value returned from the query (`None` when it returns no rows), as the flavor's Python
702    driver returns it (`int`, `float`, `Decimal`, `str`, `datetime`, ...; a NumPy scalar on DuckDB,
703    as in Meerschaum 4, which read it through pandas).
704    Raises the database error if the query fails (`None` with `silent=True`).
705    On a protected connector without the allowance, the query must be one read statement
706    (else `PermissionError`), and it runs read-only, as in `read()`.
707
708    """
709    from meerschaum.connectors.sql import _native
710    if _native.uses_native(self):
711        return _native.value(self, query, *args, use_pandas=use_pandas, **kw)
712    ### A missing `sql` extra is an `ImportError`, not a swallowed failure.
713    import_sqlalchemy()
714    silent = kw.get('silent', False)
715    if self.flavor == 'duckdb':
716        use_pandas = True
717    if use_pandas:
718        import_pandas_for_sql()
719        df = self.read(query, *args, **kw)
720        if df is None:
721            return None
722        try:
723            return df.iloc[0, 0]
724        except IndexError:
725            return None
726
727    _close = kw.pop('close', True)
728    _commit = kw.pop('commit', (self.flavor != 'mssql'))
729
730    ### A protected connector (without `--allow-protected`) reads one read statement, read-only.
731    read_only, refusal = _read_guard(self, query)
732    if refusal is not None:
733        if silent:
734            return None
735        raise PermissionError(refusal)
736    if read_only:
737        try:
738            with _read_only_connection(self) as connection:
739                result = self.exec(
740                    query,
741                    *args,
742                    close=False,
743                    commit=False,
744                    _connection=connection,
745                    _skip_protected=True,
746                    **kw
747                )
748                first = result.first() if result is not None else None
749                return first[0] if first is not None else None
750        except Exception:
751            if not silent:
752                raise
753            return None
754
755    ### Database errors raise; `silent=True` returns `None` without a warning (v4's result).
756    result, connection = self.exec(
757        query,
758        *args,
759        with_connection=True,
760        close=False,
761        commit=_commit,
762        _skip_protected=True,
763        **kw
764    )
765    try:
766        first = result.first() if result is not None else None
767        _val = first[0] if first is not None else None
768    except Exception:
769        if not silent:
770            raise
771        _val = None
772    finally:
773        if _close and connection is not None:
774            try:
775                connection.close()
776            except Exception as e:
777                warn("Failed to close connection with exception:\n" + str(e))
778    return _val

Execute the provided query and return the first value.

Parameters
Returns
  • Any value returned from the query (None when it returns no rows), as the flavor's Python
  • driver returns it (int, float, Decimal, str, datetime, ...; a NumPy scalar on DuckDB,
  • as in Meerschaum 4, which read it through pandas).
  • Raises the database error if the query fails (None with silent=True).
  • On a protected connector without the allowance, the query must be one read statement
  • (else PermissionError), and it runs read-only, as in read().
def exec( self, query: str, *args: Any, silent: bool = False, debug: bool = False, commit: bool | None = None, close: bool | None = None, with_connection: bool = False, _connection=None, _transaction=None, **kw: Any) -> 'Union[sqlalchemy.engine.result.resultProxy, sqlalchemy.engine.cursor.LegacyCursorResult, Tuple[sqlalchemy.engine.result.resultProxy, sqlalchemy.engine.base.Connection], Tuple[sqlalchemy.engine.cursor.LegacyCursorResult, sqlalchemy.engine.base.Connection], None]':
792def exec(
793    self,
794    query: str,
795    *args: Any,
796    silent: bool = False,
797    debug: bool = False,
798    commit: Optional[bool] = None,
799    close: Optional[bool] = None,
800    with_connection: bool = False,
801    _connection=None,
802    _transaction=None,
803    **kw: Any
804) -> Union[
805        sqlalchemy.engine.result.resultProxy,
806        sqlalchemy.engine.cursor.LegacyCursorResult,
807        Tuple[sqlalchemy.engine.result.resultProxy, sqlalchemy.engine.base.Connection],
808        Tuple[sqlalchemy.engine.cursor.LegacyCursorResult, sqlalchemy.engine.base.Connection],
809        None
810]:
811    """
812    Execute SQL code and return the result, e.g. when calling stored procedures.
813
814    The statement runs on the connector's Rust connection pool for every flavor in
815    `meerschaum.connectors.sql._native.NATIVE_SQL_FLAVORS` (no SQLAlchemy needed), and the result
816    has the parts of SQLAlchemy's `CursorResult` that code written for Meerschaum 4 uses
817    (`fetchall()`, `first()`, `scalar()`, `mappings()`, `keys()`, `rowcount`, iteration, ...).
818    `with_connection=True` (which returns a SQLAlchemy connection) uses SQLAlchemy.
819
820    If inserting data, please use bind variables to avoid SQL injection!
821
822    Parameters
823    ----------
824    query: Union[str, List[str], Tuple[str]]
825        The query to execute (text, or a SQLAlchemy construct).
826        If `query` is a list or tuple, call `self.exec_queries()` instead.
827
828    args: Any
829        The statement's parameters: a dictionary for `:name` placeholders, a list / tuple of
830        values for `?` (or `%s`) placeholders, or a list of dictionaries to run the statement
831        once per dictionary (`executemany`). `parameters=` is accepted too.
832
833    silent: bool, default False
834        If `True`, return `None` instead of raising when the query fails, without a warning
835        (Meerschaum 4's behavior). By default, database errors raise.
836
837    commit: Optional[bool], default None
838        If `True`, commit the changes after execution.
839        Causes issues with flavors like `'mssql'`.
840        This does not apply if `query` is a list of strings.
841
842    close: Optional[bool], default None
843        If `True`, close the connection after execution.
844        Causes issues with flavors like `'mssql'`.
845        This does not apply if `query` is a list of strings.
846
847    with_connection: bool, default False
848        If `True`, return a tuple including the connection object.
849        This does not apply if `query` is a list of strings.
850
851    Returns
852    -------
853    The `sqlalchemy` result object, or a tuple with the connection if `with_connection` is provided.
854    Raises the database error if the query fails (`None` with `silent=True`), and
855    `PermissionError` on a protected connector unless writes are allowed
856    (`--allow-protected`, `MRSM_ALLOW_PROTECTED=1`, `meerschaum.connectors.allow_protected()`).
857
858    """
859    if isinstance(query, (list, tuple)):
860        return self.exec_queries(
861            list(query),
862            *args,
863            silent=silent,
864            debug=debug,
865            **kw
866        )
867
868    ### A protected connector refuses raw SQL unless writes are allowed
869    ### (`--allow-protected`, `MRSM_ALLOW_PROTECTED=1`, `allow_protected()`).
870    if not kw.pop('_skip_protected', False):
871        from meerschaum.connectors import protected_refusal
872        refusal = protected_refusal(self, 'execute SQL')
873        if refusal is not None:
874            if silent:
875                return (None, None) if with_connection else None
876            raise PermissionError(refusal)
877
878    from meerschaum.connectors.sql import _native
879    if _native.uses_native(self):
880        reason = (
881            '`with_connection=True` returns a SQLAlchemy connection'
882            if with_connection
883            else (
884                'it was given a SQLAlchemy connection or transaction'
885                if (_connection is not None or _transaction is not None)
886                else None
887            )
888        )
889        if reason is None:
890            return _native.exec(
891                self, query, *args,
892                silent=silent, debug=debug, commit=commit, close=close, **kw
893            )
894        _native.fallback(self, 'exec', reason, debug)
895
896    from meerschaum.utils.packages import attempt_import
897    sqlalchemy = import_sqlalchemy()
898    if debug:
899        dprint(f"[{self}] Executing query:\n{query}")
900
901    _close = close if close is not None else (self.flavor != 'mssql')
902    _commit = commit if commit is not None else (
903        (self.flavor != 'mssql' or 'select' not in str(query).lower())
904    )
905
906    ### Select and Insert objects need to be compiled (SQLAlchemy 2.0.0+).
907    if not hasattr(query, 'compile'):
908        query = sqlalchemy.text(query)
909
910    connection = _connection if _connection is not None else self.get_connection()
911
912    try:
913        transaction = (
914            _transaction
915            if _transaction is not None else (
916                connection.begin()
917                if _commit
918                else None
919            )
920        )
921    except sqlalchemy.exc.InvalidRequestError as e:
922        if _connection is not None or _transaction is not None:
923            raise e
924        connection = self.get_connection(rebuild=True)
925        transaction = connection.begin()
926
927    if transaction is not None and not transaction.is_active and _transaction is not None:
928        connection = self.get_connection(rebuild=True)
929        transaction = connection.begin() if _commit else None
930
931    result = None
932    try:
933        result = connection.execute(query, *args, **kw)
934        if _commit:
935            transaction.commit()
936    except Exception as e:
937        if debug:
938            dprint(f"[{self}] Failed to execute query:\n\n{query}\n\n{e}")
939        result = None
940        if _commit:
941            if debug:
942                dprint(f"[{self}] Rolling back failed transaction...")
943            transaction.rollback()
944            connection = self.get_connection(rebuild=True)
945        ### Database errors raise; `silent=True` returns `None` without a warning (v4's result).
946        if not silent:
947            if _connection is None and not _close:
948                try:
949                    connection.close()
950                except Exception:
951                    pass
952            raise
953    finally:
954        if _close:
955            connection.close()
956
957    if debug:
958        dprint(f"[{self}] Done executing.")
959
960    if with_connection:
961        return result, connection
962
963    return result

Execute SQL code and return the result, e.g. when calling stored procedures.

The statement runs on the connector's Rust connection pool for every flavor in meerschaum.connectors.sql._native.NATIVE_SQL_FLAVORS (no SQLAlchemy needed), and the result has the parts of SQLAlchemy's CursorResult that code written for Meerschaum 4 uses (fetchall(), first(), scalar(), mappings(), keys(), rowcount, iteration, ...). with_connection=True (which returns a SQLAlchemy connection) uses SQLAlchemy.

If inserting data, please use bind variables to avoid SQL injection!

Parameters
  • query (Union[str, List[str], Tuple[str]]): The query to execute (text, or a SQLAlchemy construct). If query is a list or tuple, call self.exec_queries() instead.
  • args (Any): The statement's parameters: a dictionary for :name placeholders, a list / tuple of values for ? (or %s) placeholders, or a list of dictionaries to run the statement once per dictionary (executemany). parameters= is accepted too.
  • silent (bool, default False): If True, return None instead of raising when the query fails, without a warning (Meerschaum 4's behavior). By default, database errors raise.
  • commit (Optional[bool], default None): If True, commit the changes after execution. Causes issues with flavors like 'mssql'. This does not apply if query is a list of strings.
  • close (Optional[bool], default None): If True, close the connection after execution. Causes issues with flavors like 'mssql'. This does not apply if query is a list of strings.
  • with_connection (bool, default False): If True, return a tuple including the connection object. This does not apply if query is a list of strings.
Returns
  • The sqlalchemy result object, or a tuple with the connection if with_connection is provided.
  • Raises the database error if the query fails (None with silent=True), and
  • PermissionError on a protected connector unless writes are allowed
  • (--allow-protected, MRSM_ALLOW_PROTECTED=1, meerschaum.connectors.allow_protected()).
def execute( self, *args: Any, **kw: Any) -> 'Optional[sqlalchemy.engine.result.resultProxy]':
781def execute(
782    self,
783    *args : Any,
784    **kw : Any
785) -> Optional[sqlalchemy.engine.result.resultProxy]:
786    """
787    An alias for `meerschaum.connectors.sql.SQLConnector.exec`.
788    """
789    return self.exec(*args, **kw)
def to_sql( self, df: pandas.DataFrame, name: str = None, index: bool = False, if_exists: str = 'replace', method: str = '', chunksize: int | None = -1, schema: str | None = None, safe_copy: bool = True, silent: bool = False, debug: bool = False, as_tuple: bool = False, as_dict: bool = False, _connection=None, _transaction=None, **kw) -> bool | Tuple[bool, str]:
1083def to_sql(
1084    self,
1085    df: pandas.DataFrame,
1086    name: str = None,
1087    index: bool = False,
1088    if_exists: str = 'replace',
1089    method: str = "",
1090    chunksize: Optional[int] = -1,
1091    schema: Optional[str] = None,
1092    safe_copy: bool = True,
1093    silent: bool = False,
1094    debug: bool = False,
1095    as_tuple: bool = False,
1096    as_dict: bool = False,
1097    _connection=None,
1098    _transaction=None,
1099    **kw
1100) -> Union[bool, SuccessTuple]:
1101    """
1102    Upload a DataFrame's contents to the SQL server.
1103
1104    The rows go through the connector's Rust connection pool (no SQLAlchemy) for every flavor in
1105    `meerschaum.connectors.sql._native.NATIVE_SQL_FLAVORS`; a new table gets the column types
1106    `pandas.DataFrame.to_sql()` would create (or `dtype`).
1107
1108    Parameters
1109    ----------
1110    df: Union[pd.DataFrame, pl.DataFrame, pyarrow.Table]
1111        The DataFrame to be inserted: pandas, Polars, or Arrow data (anything with
1112        `__arrow_c_stream__`).
1113
1114    name: str
1115        The name of the table to be created.
1116
1117    index: bool, default False
1118        If True, creates the DataFrame's indices as columns.
1119
1120    if_exists: str, default 'replace'
1121        Drop and create the table ('replace') or append if it exists
1122        ('append') or raise Exception ('fail').
1123        Options are ['replace', 'append', 'fail'].
1124
1125    method: str, default ''
1126        None or multi. Details on pandas.to_sql.
1127
1128    chunksize: Optional[int], default -1
1129        How many rows to insert at a time.
1130
1131    schema: Optional[str], default None
1132        Optionally override the schema for the table.
1133        Defaults to `SQLConnector.schema`.
1134
1135    safe_copy: bool, defaul True
1136        If `True`, copy the dataframe before making any changes.
1137
1138    as_tuple: bool, default False
1139        If `True`, return a (success_bool, message) tuple instead of a `bool`.
1140        Defaults to `False`.
1141
1142    as_dict: bool, default False
1143        If `True`, return a dictionary of transaction information.
1144        The keys are `success`, `msg`, `start`, `end`, `duration`, `num_rows`, `chunksize`,
1145        `method`, and `target`.
1146
1147    kw: Any
1148        Additional arguments will be passed to the DataFrame's `to_sql` function
1149
1150    Returns
1151    -------
1152    Either a `bool` or a `SuccessTuple` (depends on `as_tuple`).
1153    """
1154    import time
1155    import json
1156    from datetime import timedelta
1157    from meerschaum.utils.warnings import error, warn
1158    import warnings
1159    import functools
1160    import traceback
1161
1162    if name is None:
1163        error(f"Name must not be `None` to insert data into {self}.")
1164
1165    from meerschaum.connectors import protected_refusal
1166    refusal = protected_refusal(self, f"write to table '{name}'")
1167    if refusal is not None:
1168        if not silent:
1169            warn(refusal, stack=False)
1170        if as_dict:
1171            return {'success': False, 'msg': refusal, 'target': name}
1172        return (False, refusal) if as_tuple else False
1173
1174    ### We're requiring `name` to be positional, and sometimes it's passed in from background jobs.
1175    kw.pop('name', None)
1176
1177    ### Arrow data (a pyarrow table, any `__arrow_c_stream__` producer) becomes the configured
1178    ### library's frame first.
1179    module_name = str(getattr(type(df), '__module__', ''))
1180    if (
1181        df is not None
1182        and not module_name.startswith(('pandas', 'polars', 'geopandas', 'dask'))
1183        and (hasattr(df, '__arrow_c_stream__') or hasattr(df, '__arrow_c_array__'))
1184    ):
1185        from meerschaum.utils.dataframe import frame_from_arrow
1186        df = frame_from_arrow(df)
1187
1188    ### The rows go through the Rust connector unless the call needs SQLAlchemy.
1189    from meerschaum.connectors.sql import _native
1190    is_dask = 'dask' in str(getattr(type(df), '__module__', ''))
1191    is_polars = str(getattr(type(df), '__module__', '')).startswith('polars')
1192    native = _native.uses_native(self)
1193    if native:
1194        reason = (
1195            'Dask frames write through `DataFrame.to_sql()`'
1196            if is_dask
1197            else (
1198                'a custom `method` writes through SQLAlchemy'
1199                if callable(method)
1200                else (
1201                    'it was given a SQLAlchemy connection or transaction'
1202                    if (_connection is not None or _transaction is not None)
1203                    else None
1204                )
1205            )
1206        )
1207        if reason is not None:
1208            native = False
1209            _native.fallback(self, 'to_sql', reason, debug)
1210    if is_polars and not native:
1211        df = df.to_pandas()
1212        is_polars = False
1213
1214    schema = schema or self.schema
1215
1216    from meerschaum.utils.sql import (
1217        sql_item_name,
1218        table_exists,
1219        json_flavors,
1220        truncate_item_name,
1221        DROP_IF_EXISTS_FLAVORS,
1222    )
1223    from meerschaum.utils.dataframe import (
1224        get_json_cols,
1225        get_numeric_cols,
1226        get_uuid_cols,
1227        get_bytes_cols,
1228        get_geometry_cols,
1229    )
1230    from meerschaum.utils.dtypes import (
1231        are_dtypes_equal,
1232        coerce_timezone,
1233        encode_bytes_for_bytea,
1234        serialize_bytes,
1235        serialize_decimal,
1236        serialize_geometry,
1237        json_serialize_value,
1238        get_geometry_type_srid,
1239    )
1240    from meerschaum.utils.dtypes.sql import (
1241        PD_TO_SQLALCHEMY_DTYPES_FLAVORS,
1242        TIMEZONE_NAIVE_FLAVORS,
1243        get_db_type_from_pd_type,
1244        get_pd_type_from_db_type,
1245        get_numeric_precision_scale,
1246    )
1247    from meerschaum.utils.misc import interval_str
1248    from meerschaum.connectors.sql._create_engine import flavor_configs
1249    from meerschaum.utils.packages import attempt_import, import_pandas
1250    sqlalchemy = import_sqlalchemy() if not native else None
1251    if native and is_polars:
1252        return _native.to_sql_polars(
1253            self, df, name,
1254            if_exists=if_exists,
1255            chunksize=chunksize,
1256            schema=schema,
1257            silent=silent,
1258            debug=debug,
1259            as_tuple=as_tuple,
1260            as_dict=as_dict,
1261            dtype=kw.get('dtype', None),
1262        )
1263    pd = import_pandas_for_sql()
1264
1265    bytes_cols = get_bytes_cols(df)
1266    numeric_cols = get_numeric_cols(df)
1267    geometry_cols = get_geometry_cols(df)
1268    ### NOTE: This excludes non-numeric serialized Decimals (e.g. SQLite).
1269    numeric_cols_dtypes = {
1270        col: typ
1271        for col, typ in kw.get('dtype', {}).items()
1272        if (
1273            col in df.columns
1274            and 'numeric' in str(typ).lower()
1275        )
1276    }
1277    numeric_cols.extend([col for col in numeric_cols_dtypes if col not in numeric_cols])
1278    numeric_cols_precisions_scales = {
1279        col: (
1280            (typ.precision, typ.scale)
1281            if hasattr(typ, 'precision')
1282            else get_numeric_precision_scale(self.flavor)
1283        )
1284        for col, typ in numeric_cols_dtypes.items()
1285    }
1286    geometry_cols_dtypes = {
1287        col: typ
1288        for col, typ in kw.get('dtype', {}).items()
1289        if (
1290            col in df.columns
1291            and ('geometry' in str(typ).lower() or 'geography' in str(typ).lower())
1292        )
1293    }
1294    geometry_cols.extend([col for col in geometry_cols_dtypes if col not in geometry_cols])
1295    geometry_cols_types_srids = {
1296        col: (typ.geometry_type, typ.srid)
1297        if hasattr(typ, 'srid')
1298        else get_geometry_type_srid()
1299        for col, typ in geometry_cols_dtypes.items()
1300    }
1301
1302    if self.flavor in TIMEZONE_NAIVE_FLAVORS:
1303        for col, typ in df.dtypes.items():
1304            if are_dtypes_equal(str(typ), 'datetime'):
1305                df[col] = coerce_timezone(df[col], strip_utc=True)
1306
1307    cols_pd_types = {
1308        col: get_pd_type_from_db_type(str(typ))
1309        for col, typ in kw.get('dtype', {}).items()
1310    }
1311    cols_pd_types.update({
1312        col: f'numeric[{precision},{scale}]'
1313        for col, (precision, scale) in numeric_cols_precisions_scales.items()
1314        if precision and scale
1315    })
1316    cols_db_types = {
1317        col: get_db_type_from_pd_type(typ, flavor=self.flavor)
1318        for col, typ in cols_pd_types.items()
1319    }
1320
1321    enable_bulk_insert = mrsm.get_config(
1322        'system', 'connectors', 'sql', 'bulk_insert', self.flavor,
1323        warn=False,
1324    ) or False
1325    stats = {'target': name}
1326    ### resort to defaults if None
1327    copied = False
1328    use_bulk_insert = False
1329    if method == "":
1330        if enable_bulk_insert:
1331            method = (
1332                functools.partial(mssql_insert_json, cols_types=cols_db_types, debug=debug)
1333                if self.flavor == 'mssql'
1334                else functools.partial(psql_insert_copy, debug=debug)
1335            )
1336            use_bulk_insert = True
1337        else:
1338            ### Should resolve to 'multi' or `None`.
1339            method = flavor_configs.get(self.flavor, {}).get('to_sql', {}).get('method', 'multi')
1340    ### The Rust connector bulk-inserts itself (`COPY` / `OPENJSON`) when the flag is on.
1341    method_name = (
1342        (method.func.__name__ if isinstance(method, functools.partial) else method.__name__)
1343        if callable(method)
1344        else str(method)
1345    )
1346
1347    if bytes_cols and (use_bulk_insert or self.flavor == 'oracle'):
1348        if safe_copy and not copied:
1349            df = df.copy()
1350            copied = True
1351        bytes_serializer = (
1352            functools.partial(encode_bytes_for_bytea, with_prefix=(self.flavor != 'oracle'))
1353            if self.flavor != 'mssql'
1354            else serialize_bytes
1355        )
1356        for col in bytes_cols:
1357            df[col] = df[col].apply(bytes_serializer)
1358
1359    ### Check for numeric columns.
1360    for col in numeric_cols:
1361        precision, scale = numeric_cols_precisions_scales.get(
1362            col,
1363            get_numeric_precision_scale(self.flavor)
1364        )
1365        df[col] = df[col].apply(
1366            functools.partial(
1367                serialize_decimal,
1368                quantize=True,
1369                precision=precision,
1370                scale=scale,
1371            )
1372        )
1373
1374    geometry_format = 'wkt' if self.flavor == 'mssql' else (
1375        'gpkg_wkb'
1376        if self.flavor == 'geopackage'
1377        else 'wkb_hex'
1378    )
1379    for col in geometry_cols:
1380        geometry_type, srid = geometry_cols_types_srids.get(col, get_geometry_type_srid())
1381        with warnings.catch_warnings():
1382            warnings.simplefilter("ignore")
1383            df[col] = df[col].apply(
1384                functools.partial(
1385                    serialize_geometry,
1386                    geometry_format=geometry_format,
1387                )
1388            )
1389
1390    stats['method'] = method_name
1391
1392    default_chunksize = self._sys_config.get('chunksize', None)
1393    chunksize = chunksize if chunksize != -1 else default_chunksize
1394    if chunksize is not None and self.flavor in _max_chunks_flavors:
1395        if chunksize > _max_chunks_flavors[self.flavor]:
1396            if chunksize != default_chunksize:
1397                warn(
1398                    f"The specified chunksize of {chunksize} exceeds the maximum of "
1399                    + f"{_max_chunks_flavors[self.flavor]} for flavor '{self.flavor}'.\n"
1400                    + f"    Falling back to a chunksize of {_max_chunks_flavors[self.flavor]}.",
1401                    stacklevel = 3,
1402                )
1403            chunksize = _max_chunks_flavors[self.flavor]
1404    stats['chunksize'] = chunksize
1405
1406    success, msg = False, "Default to_sql message"
1407    start = time.perf_counter()
1408    if debug:
1409        msg = f"[{self}] Inserting {len(df)} rows with chunksize: {chunksize}..."
1410        print(msg, end="", flush=True)
1411    stats['num_rows'] = len(df)
1412
1413    ### Check if the name is too long.
1414    truncated_name = truncate_item_name(name, self.flavor)
1415    if name != truncated_name:
1416        if self.flavor not in ('oracle', 'mysql', 'mariadb'):
1417            warn(
1418                f"Table '{name}' is too long for '{self.flavor}',"
1419                f" will instead create the table '{truncated_name}'."
1420            )
1421
1422    ### filter out non-pandas args
1423    import inspect
1424    to_sql_params = inspect.signature(df.to_sql).parameters
1425    to_sql_kw = {}
1426    for k, v in kw.items():
1427        if k in to_sql_params:
1428            to_sql_kw[k] = v
1429
1430    to_sql_kw.update({
1431        'name': truncated_name,
1432        'schema': schema,
1433        'index': index,
1434        'if_exists': if_exists,
1435        'method': method,
1436        'chunksize': chunksize,
1437    })
1438    if not native:
1439        to_sql_kw[('con' if not is_dask else 'uri')] = (
1440            self.engine if not is_dask else self.URI
1441        )
1442    if is_dask:
1443        to_sql_kw.update({
1444            'parallel': True,
1445        })
1446    elif _connection is not None:
1447        to_sql_kw['con'] = _connection
1448
1449    if_exists_str = "IF EXISTS" if self.flavor in DROP_IF_EXISTS_FLAVORS else ""
1450    if self.flavor == 'oracle' and not native:
1451        ### For some reason 'replace' doesn't work properly in pandas,
1452        ### so try dropping first.
1453        if if_exists == 'replace' and table_exists(name, self, schema=schema, debug=debug):
1454            success = self.exec(
1455                f"DROP TABLE {if_exists_str}" + sql_item_name(name, 'oracle', schema)
1456            ) is not None
1457            if not success:
1458                warn(f"Unable to drop {name}")
1459
1460        ### Enforce NVARCHAR(2000) as text instead of CLOB.
1461        dtype = to_sql_kw.get('dtype', {})
1462        for col, typ in df.dtypes.items():
1463            if are_dtypes_equal(str(typ), 'object'):
1464                dtype[col] = sqlalchemy.types.NVARCHAR(2000)
1465            elif are_dtypes_equal(str(typ), 'int'):
1466                dtype[col] = sqlalchemy.types.INTEGER
1467        to_sql_kw['dtype'] = dtype
1468    elif self.flavor == 'duckdb':
1469        dtype = to_sql_kw.get('dtype', {})
1470        dt_cols = [col for col, typ in df.dtypes.items() if are_dtypes_equal(str(typ), 'datetime')]
1471        for col in dt_cols:
1472            df[col] = coerce_timezone(df[col], strip_utc=False)
1473    elif self.flavor == 'mssql' and not native:
1474        dtype = to_sql_kw.get('dtype', {})
1475        dt_cols = [col for col, typ in df.dtypes.items() if are_dtypes_equal(str(typ), 'datetime')]
1476        new_dtype = {}
1477        for col in dt_cols:
1478            if col in dtype:
1479                continue
1480            dt_typ = get_db_type_from_pd_type(str(df.dtypes[col]), self.flavor, as_sqlalchemy=True)
1481            if col not in dtype:
1482                new_dtype[col] = dt_typ
1483
1484        dtype.update(new_dtype)
1485        to_sql_kw['dtype'] = dtype
1486
1487    ### Check for JSON columns.
1488    if self.flavor not in json_flavors:
1489        json_cols = get_json_cols(df)
1490        for col in json_cols:
1491            df[col] = df[col].apply(
1492                (
1493                    lambda x: json.dumps(x, default=json_serialize_value, sort_keys=True)
1494                    if not isinstance(x, Hashable)
1495                    else x
1496                )
1497            )
1498
1499    if PD_TO_SQLALCHEMY_DTYPES_FLAVORS['uuid'].get(self.flavor, None) != 'Uuid':
1500        uuid_cols = get_uuid_cols(df)
1501        for col in uuid_cols:
1502            df[col] = df[col].astype(str)
1503
1504    if native:
1505        try:
1506            success, error_msg = _native.to_sql_write(
1507                self,
1508                df,
1509                truncated_name,
1510                schema,
1511                if_exists,
1512                index,
1513                chunksize,
1514                dtype=kw.get('dtype', None),
1515            )
1516        except Exception:
1517            success, error_msg = False, traceback.format_exc()
1518        if not success:
1519            if not silent:
1520                warn(error_msg)
1521            msg = error_msg
1522    else:
1523        try:
1524            with warnings.catch_warnings():
1525                warnings.filterwarnings('ignore')
1526                df.to_sql(**to_sql_kw)
1527            success = True
1528        except Exception:
1529            if not silent:
1530                warn(traceback.format_exc())
1531            success, msg = False, traceback.format_exc()
1532
1533    end = time.perf_counter()
1534    if success:
1535        num_rows = len(df)
1536        msg = (
1537            f"It took {interval_str(timedelta(seconds=(end - start)))} "
1538            + f"to sync {num_rows:,} row"
1539            + ('s' if num_rows != 1 else '')
1540            + f" to {name}."
1541        )
1542    stats['start'] = start
1543    stats['end'] = end
1544    stats['duration'] = end - start
1545
1546    if debug:
1547        print(" done.", flush=True)
1548        dprint(msg)
1549
1550    stats['success'] = success
1551    stats['msg'] = msg
1552    if as_tuple:
1553        return success, msg
1554    if as_dict:
1555        return stats
1556    return success

Upload a DataFrame's contents to the SQL server.

The rows go through the connector's Rust connection pool (no SQLAlchemy) for every flavor in meerschaum.connectors.sql._native.NATIVE_SQL_FLAVORS; a new table gets the column types pandas.DataFrame.to_sql() would create (or dtype).

Parameters
  • df (Union[pd.DataFrame, pl.DataFrame, pyarrow.Table]): The DataFrame to be inserted: pandas, Polars, or Arrow data (anything with __arrow_c_stream__).
  • name (str): The name of the table to be created.
  • index (bool, default False): If True, creates the DataFrame's indices as columns.
  • if_exists (str, default 'replace'): Drop and create the table ('replace') or append if it exists ('append') or raise Exception ('fail'). Options are ['replace', 'append', 'fail'].
  • method (str, default ''): None or multi. Details on pandas.to_sql.
  • chunksize (Optional[int], default -1): How many rows to insert at a time.
  • schema (Optional[str], default None): Optionally override the schema for the table. Defaults to SQLConnector.schema.
  • safe_copy (bool, defaul True): If True, copy the dataframe before making any changes.
  • as_tuple (bool, default False): If True, return a (success_bool, message) tuple instead of a bool. Defaults to False.
  • as_dict (bool, default False): If True, return a dictionary of transaction information. The keys are success, msg, start, end, duration, num_rows, chunksize, method, and target.
  • kw (Any): Additional arguments will be passed to the DataFrame's to_sql function
Returns
  • Either a bool or a SuccessTuple (depends on as_tuple).
def exec_queries( self, queries: "List[Union[str, Tuple[str, Callable[['sqlalchemy.orm.session.Session'], List[str]]]]]", break_on_error: bool = False, rollback: bool = True, silent: bool = False, debug: bool = False) -> 'List[Union[sqlalchemy.engine.cursor.CursorResult, None]]':
 966def exec_queries(
 967    self,
 968    queries: List[
 969        Union[
 970            str,
 971            Tuple[str, Callable[['sqlalchemy.orm.session.Session'], List[str]]]
 972        ]
 973    ],
 974    break_on_error: bool = False,
 975    rollback: bool = True,
 976    silent: bool = False,
 977    debug: bool = False,
 978) -> List[Union[sqlalchemy.engine.cursor.CursorResult, None]]:
 979    """
 980    Execute a list of queries in a single transaction.
 981
 982    Parameters
 983    ----------
 984    queries: List[
 985        Union[
 986            str,
 987            Tuple[str, Callable[[], List[str]]]
 988        ]
 989    ]
 990        The queries in the transaction to be executed.
 991        If a query is a tuple, the second item of the tuple
 992        will be considered a callable hook that returns a list of queries to be executed
 993        before the next item in the list.
 994
 995    break_on_error: bool, default False
 996        If `True`, stop executing when a query fails.
 997
 998    rollback: bool, default True
 999        If `break_on_error` is `True`, rollback the transaction if a query fails.
1000
1001    silent: bool, default False
1002        If `True`, suppress warnings.
1003
1004    Returns
1005    -------
1006    A list of SQLAlchemy results.
1007    """
1008    from meerschaum.utils.warnings import warn
1009    from meerschaum.utils.debug import dprint
1010    from meerschaum.utils.packages import attempt_import
1011    from meerschaum.connectors import protected_refusal
1012    refusal = protected_refusal(self, 'execute SQL')
1013    if refusal is not None:
1014        if silent:
1015            return []
1016        raise PermissionError(refusal)
1017    from meerschaum.connectors.sql import _native
1018    if _native.uses_native(self):
1019        return _native.exec_queries(
1020            self,
1021            queries,
1022            break_on_error=break_on_error,
1023            rollback=rollback,
1024            silent=silent,
1025            debug=debug,
1026        )
1027    sqlalchemy, sqlalchemy_orm = import_sqlalchemy('sqlalchemy', 'sqlalchemy.orm')
1028    session = sqlalchemy_orm.Session(self.engine)
1029
1030    result = None
1031    results = []
1032    with session.begin():
1033        for query in queries:
1034            hook = None
1035            result = None
1036
1037            if isinstance(query, tuple):
1038                query, hook = query
1039            if isinstance(query, str):
1040                query = sqlalchemy.text(query)
1041
1042            if debug:
1043                dprint(f"[{self}]\n" + str(query))
1044
1045            try:
1046                result = session.execute(query)
1047                session.flush()
1048            except Exception as e:
1049                msg = (f"Encountered error while executing:\n{e}")
1050                if not silent:
1051                    warn(msg)
1052                elif debug:
1053                    dprint(f"[{self}]\n" + str(msg))
1054                result = None
1055
1056            if debug:
1057                dprint(f"[{self}] Finished executing.")
1058
1059            if result is None and break_on_error:
1060                if rollback:
1061                    if debug:
1062                        dprint(f"[{self}] Rolling back...")
1063                    session.rollback()
1064                results.append(result)
1065                break
1066            elif result is not None and hook is not None:
1067                hook_queries = hook(session)
1068                if hook_queries:
1069                    hook_results = self.exec_queries(
1070                        hook_queries,
1071                        break_on_error = break_on_error,
1072                        rollback=rollback,
1073                        silent=silent,
1074                        debug=debug,
1075                    )
1076                    result = (result, hook_results)
1077
1078            results.append(result)
1079
1080    return results

Execute a list of queries in a single transaction.

Parameters
  • queries (List[): Union[ str, Tuple[str, Callable[[], List[str]]] ]
  • ]: The queries in the transaction to be executed. If a query is a tuple, the second item of the tuple will be considered a callable hook that returns a list of queries to be executed before the next item in the list.
  • break_on_error (bool, default False): If True, stop executing when a query fails.
  • rollback (bool, default True): If break_on_error is True, rollback the transaction if a query fails.
  • silent (bool, default False): If True, suppress warnings.
Returns
  • A list of SQLAlchemy results.
def get_connection(self, rebuild: bool = False) -> "'sqlalchemy.engine.base.Connection'":
1754def get_connection(self, rebuild: bool = False) -> 'sqlalchemy.engine.base.Connection':
1755    """
1756    Return the current alive connection.
1757
1758    Parameters
1759    ----------
1760    rebuild: bool, default False
1761        If `True`, close the previous connection and open a new one.
1762
1763    Returns
1764    -------
1765    A `sqlalchemy.engine.base.Connection` object.
1766    """
1767    import threading
1768    if '_thread_connections' not in self.__dict__:
1769        self.__dict__['_thread_connections'] = {}
1770
1771    self._cleanup_connections()
1772
1773    thread_id = threading.get_ident()
1774
1775    thread_connections = self.__dict__.get('_thread_connections', {})
1776    connection = thread_connections.get(thread_id, None)
1777
1778    if rebuild and connection is not None:
1779        try:
1780            connection.close()
1781        except Exception:
1782            pass
1783
1784        _ = thread_connections.pop(thread_id, None)
1785        connection = None
1786
1787    if connection is None or connection.closed:
1788        connection = self.engine.connect()
1789        thread_connections[thread_id] = connection
1790
1791    return connection

Return the current alive connection.

Parameters
  • rebuild (bool, default False): If True, close the previous connection and open a new one.
Returns
  • A sqlalchemy.engine.base.Connection object.
def test_connection(self, **kw: Any) -> bool | None:
650def test_connection(
651    self,
652    **kw: Any
653) -> Union[bool, None]:
654    """
655    Test if a successful connection to the database may be made.
656
657    Parameters
658    ----------
659    **kw:
660        The keyword arguments are passed to `meerschaum.connectors.poll.retry_connect`:
661        `max_retries` (default `1`), `retry_wait` seconds between attempts (default `0`)
662        and `warn` (say why an attempt failed, default `False`).
663
664    Returns
665    -------
666    `True` if a connection is made, otherwise `False` or `None` in case of failure.
667
668    """
669    import warnings
670    from meerschaum.connectors.poll import retry_connect, _native_target
671    from meerschaum.utils.misc import filter_keywords
672    _default_kw = {'max_retries': 1, 'retry_wait': 0, 'warn': False, 'connector': self}
673    _default_kw.update(kw)
674    ### `SELECT 1` through the Rust connector (no SQLAlchemy engine), in this process: a failed
675    ### attempt prints the cause the driver gave (`cannot connect to localhost:5432 (connection
676    ### refused)`, `authentication failed for user ...`) as v4's `retry_connect()` did.
677    if _native_target(self) is None:
678        ### No usable Rust driver here: say why rather than retry in a child process which
679        ### could not connect either.
680        if _default_kw.get('warn', False):
681            from meerschaum.utils.warnings import warn as _warn
682            try:
683                self._core_connector(discover_schema=False)
684            except Exception as e:
685                _warn(f"Connection to '{self}' failed: {e}", stack=False)
686        return False
687    with warnings.catch_warnings():
688        warnings.filterwarnings('ignore', 'Could not')
689        try:
690            return retry_connect(**filter_keywords(retry_connect, **_default_kw))
691        except Exception:
692            return False

Test if a successful connection to the database may be made.

Parameters
  • **kw:: The keyword arguments are passed to meerschaum.connectors.poll.retry_connect: max_retries (default 1), retry_wait seconds between attempts (default 0) and warn (say why an attempt failed, default False).
Returns
  • True if a connection is made, otherwise False or None in case of failure.
def fetch( self, pipe: meerschaum.Pipe, begin: datetime.datetime | int | str | None = '', end: datetime.datetime | int | str | None = None, check_existing: bool = True, chunksize: int | None = -1, workers: int | None = None, debug: bool = False, **kw: Any) -> pandas.DataFrame | List[Any] | None:
 68def fetch(
 69    self,
 70    pipe: mrsm.Pipe,
 71    begin: Union[datetime, int, str, None] = '',
 72    end: Union[datetime, int, str, None] = None,
 73    check_existing: bool = True,
 74    chunksize: Optional[int] = -1,
 75    workers: Optional[int] = None,
 76    debug: bool = False,
 77    **kw: Any
 78) -> Union['pd.DataFrame', List[Any], None]:
 79    """Execute the SQL definition and return a Pandas DataFrame.
 80
 81    Parameters
 82    ----------
 83    pipe: mrsm.Pipe
 84        The pipe object which contains the `fetch` metadata.
 85
 86        - pipe.columns['datetime']: str
 87            - Name of the datetime column for the remote table.
 88        - pipe.parameters['fetch']: Dict[str, Any]
 89            - Parameters necessary to execute a query.
 90        - pipe.parameters['fetch']['definition']: str
 91            - Raw SQL query to execute to generate the pandas DataFrame.
 92        - pipe.parameters['fetch']['backtrack_minutes']: Union[int, float]
 93            - How many minutes before `begin` to search for data (*optional*).
 94
 95    begin: Union[datetime, int, str, None], default None
 96        Most recent datatime to search for data.
 97        If `backtrack_minutes` is provided, subtract `backtrack_minutes`.
 98
 99    end: Union[datetime, int, str, None], default None
100        The latest datetime to search for data.
101        If `end` is `None`, do not bound 
102
103    check_existing: bool, defult True
104        If `False`, use a backtrack interval of 0 minutes.
105
106    chunksize: Optional[int], default -1
107        How many rows to load into memory at once.
108        Otherwise the entire result set is loaded into memory.
109
110    workers: Optional[int], default None
111        How many threads to use when consuming the generator.
112        Defaults to the number of cores.
113
114    debug: bool, default False
115        Verbosity toggle.
116
117    Returns
118    -------
119    A pandas DataFrame generator.
120    """
121    meta_def = self.get_pipe_metadef(
122        pipe,
123        begin=begin,
124        end=end,
125        check_existing=check_existing,
126        debug=debug,
127        **kw
128    )
129    chunks = self.read(
130        meta_def,
131        chunksize=chunksize,
132        workers=workers,
133        as_iterator=True,
134        debug=debug,
135    )
136    return chunks

Execute the SQL definition and return a Pandas DataFrame.

Parameters
  • pipe (mrsm.Pipe): The pipe object which contains the fetch metadata.

    • pipe.columns['datetime']: str
      • Name of the datetime column for the remote table.
    • pipe.parameters['fetch']: Dict[str, Any]
      • Parameters necessary to execute a query.
    • pipe.parameters['fetch']['definition']: str
      • Raw SQL query to execute to generate the pandas DataFrame.
    • pipe.parameters['fetch']['backtrack_minutes']: Union[int, float]
      • How many minutes before begin to search for data (optional).
  • begin (Union[datetime, int, str, None], default None): Most recent datatime to search for data. If backtrack_minutes is provided, subtract backtrack_minutes.
  • end (Union[datetime, int, str, None], default None): The latest datetime to search for data. If end is None, do not bound
  • check_existing (bool, defult True): If False, use a backtrack interval of 0 minutes.
  • chunksize (Optional[int], default -1): How many rows to load into memory at once. Otherwise the entire result set is loaded into memory.
  • workers (Optional[int], default None): How many threads to use when consuming the generator. Defaults to the number of cores.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A pandas DataFrame generator.
def get_pipe_metadef( self, pipe: meerschaum.Pipe, params: Dict[str, Any] | None = None, begin: datetime.datetime | int | str | None = '', end: datetime.datetime | int | str | None = None, check_existing: bool = True, debug: bool = False, **kw: Any) -> str | None:
139def get_pipe_metadef(
140    self,
141    pipe: mrsm.Pipe,
142    params: Optional[Dict[str, Any]] = None,
143    begin: Union[datetime, int, str, None] = '',
144    end: Union[datetime, int, str, None] = None,
145    check_existing: bool = True,
146    debug: bool = False,
147    **kw: Any
148) -> Union[str, None]:
149    """
150    Return a pipe's meta definition fetch query.
151
152    params: Optional[Dict[str, Any]], default None
153        Optional params dictionary to build the `WHERE` clause.
154        See `meerschaum.utils.sql.build_where`.
155
156    begin: Union[datetime, int, str, None], default None
157        Most recent datatime to search for data.
158        If `backtrack_minutes` is provided, subtract `backtrack_minutes`.
159
160    end: Union[datetime, int, str, None], default None
161        The latest datetime to search for data.
162        If `end` is `None`, do not bound 
163
164    check_existing: bool, default True
165        If `True`, apply the backtrack interval.
166
167    debug: bool, default False
168        Verbosity toggle.
169
170    Returns
171    -------
172    A pipe's meta definition fetch query string.
173    """
174    from meerschaum import _core
175    from meerschaum.config import get_config
176    if (pipe.columns or {}).get('id', None) and get_config('system', 'experimental', 'join_fetch'):
177        _warn_join_fetch_ignored()
178
179    parent = pipe.parent
180    parent_spec = None
181    if parent is not None:
182        parent_dt_col = parent.columns.get('datetime', None)
183        parent_instance = parent.instance_connector
184        parent_spec = {
185            'target': parent.target,
186            'schema': (
187                parent_instance.get_pipe_schema(parent)
188                if parent_instance.type == 'sql'
189                else None
190            ),
191            'dt_col': parent_dt_col,
192            'dt_typ': (
193                parent.dtypes.get(parent_dt_col, 'datetime')
194                if parent_dt_col
195                else None
196            ),
197            'precision_unit': (parent.precision or {}).get('unit', 'second'),
198        }
199    sync_time = pipe.get_sync_time(debug=debug) if begin == '' else None
200    _check_bounds_are_comparable(pipe, parent, begin, end, sync_time)
201    meta_def = _core.get_pipe_metadef(
202        self._core_connector(),
203        pipe,
204        params,
205        begin,
206        end,
207        check_existing,
208        sync_time,
209        parent_spec,
210    )
211    if meta_def is None:
212        raise ValueError(f"No SQL definition could be found for {pipe}.")
213    return meta_def

Return a pipe's meta definition fetch query.

params: Optional[Dict[str, Any]], default None Optional params dictionary to build the WHERE clause. See meerschaum.utils.sql.build_where.

begin: Union[datetime, int, str, None], default None Most recent datatime to search for data. If backtrack_minutes is provided, subtract backtrack_minutes.

end: Union[datetime, int, str, None], default None The latest datetime to search for data. If end is None, do not bound

check_existing: bool, default True If True, apply the backtrack interval.

debug: bool, default False Verbosity toggle.

Returns
  • A pipe's meta definition fetch query string.
def cli(self, debug: bool = False, nopretty: bool = False) -> Tuple[bool, str]:
36def cli(
37    self,
38    debug: bool = False,
39    nopretty: bool = False,
40) -> SuccessTuple:
41    """Open the native SQL client launcher using this connector's exact attributes.
42
43    Rainfrog, configured preferences, fallback clients, credentials, and exit status use
44    the same implementation as ``mrsm sql LABEL``. ``nopretty`` forces the plain client.
45    No SQLAlchemy engine or database connection is needed to launch an external client.
46    """
47    from meerschaum import _core
48    from meerschaum._internal.entry import _plain_value
49
50    attributes = dict(self.meta)
51    attributes.pop('type', None)
52    attributes.pop('label', None)
53    context = {'attributes': {str(self): {
54        key: value for key, value in attributes.items() if _plain_value(value)
55    }}}
56    arguments = ['sql', self.label]
57    if debug:
58        arguments.append('--debug')
59    if nopretty:
60        arguments.append('--nopretty')
61    return _core.entry(arguments, None, context)

Open the native SQL client launcher using this connector's exact attributes.

Rainfrog, configured preferences, fallback clients, credentials, and exit status use the same implementation as mrsm sql LABEL. nopretty forces the plain client. No SQLAlchemy engine or database connection is needed to launch an external client.

def get_pipe_size( self, pipe: meerschaum.Pipe, debug: bool = False, **kwargs: Any) -> int | None:
17def get_pipe_size(
18    self,
19    pipe: mrsm.Pipe,
20    debug: bool = False,
21    **kwargs: Any
22) -> Union[int, None]:
23    """
24    Return the on-disk size of a pipe's target table in bytes.
25
26    For TimescaleDB hypertables, the total hypertable size (including chunks and indexes)
27    is returned. Other flavors use their native size functions where available.
28
29    Parameters
30    ----------
31    pipe: mrsm.Pipe
32        The pipe whose target table size to measure.
33
34    debug: bool, default False
35        Verbosity toggle.
36
37    Returns
38    -------
39    An `int` of the number of bytes occupied by the target table,
40    or `None` if the size could not be determined.
41    """
42    return self._rust_method('get_pipe_size')(pipe)

Return the on-disk size of a pipe's target table in bytes.

For TimescaleDB hypertables, the total hypertable size (including chunks and indexes) is returned. Other flavors use their native size functions where available.

Parameters
  • pipe (mrsm.Pipe): The pipe whose target table size to measure.
  • debug (bool, default False): Verbosity toggle.
Returns
  • An int of the number of bytes occupied by the target table,
  • or None if the size could not be determined.
def compress_pipe( self, pipe: meerschaum.Pipe, no_policy: bool = False, debug: bool = False, **kwargs: Any) -> Tuple[bool, str]:
 82def compress_pipe(
 83    self,
 84    pipe: mrsm.Pipe,
 85    no_policy: bool = False,
 86    debug: bool = False,
 87    **kwargs: Any
 88) -> SuccessTuple:
 89    """
 90    Compress a pipe's target table to reduce disk usage.
 91
 92    For TimescaleDB, enables the Hypercore columnstore, installs a columnstore (compression)
 93    policy (so future synced chunks are converted automatically), and converts any existing
 94    uncompressed chunks now. For MySQL/MariaDB and MSSQL, applies the flavor's native table
 95    compression. Other flavors are unsupported.
 96
 97    Parameters
 98    ----------
 99    pipe: mrsm.Pipe
100        The pipe whose target table to compress.
101
102    no_policy: bool, default False
103        If `True` (TimescaleDB only), compress existing chunks now without installing an ongoing
104        columnstore (compression) policy. Any pre-existing policy is left untouched.
105
106    debug: bool, default False
107        Verbosity toggle.
108
109    Returns
110    -------
111    A `SuccessTuple` indicating success, including the amount of disk reclaimed.
112    """
113    return self._rust_method('compress_pipe')(pipe, no_policy=no_policy)

Compress a pipe's target table to reduce disk usage.

For TimescaleDB, enables the Hypercore columnstore, installs a columnstore (compression) policy (so future synced chunks are converted automatically), and converts any existing uncompressed chunks now. For MySQL/MariaDB and MSSQL, applies the flavor's native table compression. Other flavors are unsupported.

Parameters
  • pipe (mrsm.Pipe): The pipe whose target table to compress.
  • no_policy (bool, default False): If True (TimescaleDB only), compress existing chunks now without installing an ongoing columnstore (compression) policy. Any pre-existing policy is left untouched.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A SuccessTuple indicating success, including the amount of disk reclaimed.
def decompress_pipe( self, pipe: meerschaum.Pipe, no_policy: bool = False, debug: bool = False, **kwargs: Any) -> Tuple[bool, str]:
116def decompress_pipe(
117    self,
118    pipe: mrsm.Pipe,
119    no_policy: bool = False,
120    debug: bool = False,
121    **kwargs: Any
122) -> SuccessTuple:
123    """
124    Decompress a pipe's target table, the inverse of `compress_pipe()`.
125
126    For TimescaleDB, removes the columnstore (compression) policy, converts every compressed
127    chunk back to row-store, and disables the columnstore so future synced chunks stay
128    uncompressed. For MySQL/MariaDB and MSSQL, reverts the flavor's native table compression.
129    Other flavors are unsupported.
130
131    Parameters
132    ----------
133    pipe: mrsm.Pipe
134        The pipe whose target table to decompress.
135
136    no_policy: bool, default False
137        If `True` (TimescaleDB only), decompress existing chunks now but leave the columnstore
138        (compression) policy in place — chunks will be recompressed on the policy's schedule.
139        Useful to temporarily decompress for a bulk backfill without disabling compression.
140
141    debug: bool, default False
142        Verbosity toggle.
143
144    Returns
145    -------
146    A `SuccessTuple` indicating success, including the change in disk size.
147    """
148    return self._rust_method('decompress_pipe')(pipe, no_policy=no_policy)

Decompress a pipe's target table, the inverse of compress_pipe().

For TimescaleDB, removes the columnstore (compression) policy, converts every compressed chunk back to row-store, and disables the columnstore so future synced chunks stay uncompressed. For MySQL/MariaDB and MSSQL, reverts the flavor's native table compression. Other flavors are unsupported.

Parameters
  • pipe (mrsm.Pipe): The pipe whose target table to decompress.
  • no_policy (bool, default False): If True (TimescaleDB only), decompress existing chunks now but leave the columnstore (compression) policy in place, chunks will be recompressed on the policy's schedule. Useful to temporarily decompress for a bulk backfill without disabling compression.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A SuccessTuple indicating success, including the change in disk size.
def apply_compression_policy( self, pipe: meerschaum.Pipe, debug: bool = False, **kwargs: Any) -> Tuple[bool, str]:
57def apply_compression_policy(
58    self,
59    pipe: mrsm.Pipe,
60    debug: bool = False,
61    **kwargs: Any
62) -> SuccessTuple:
63    """
64    Idempotently enable compression and install a compression policy for a pipe.
65
66    Intended to be called automatically (e.g. after a sync) when `pipe.compress` is set.
67    Only TimescaleDB hypertables are affected; all other flavors are a no-op success.
68    Failures are non-fatal and never raise.
69
70    Parameters
71    ----------
72    pipe: mrsm.Pipe
73        The pipe whose target table should have a compression policy.
74
75    Returns
76    -------
77    A `SuccessTuple` indicating success.
78    """
79    return self._rust_method('apply_compression_policy')(pipe)

Idempotently enable compression and install a compression policy for a pipe.

Intended to be called automatically (e.g. after a sync) when pipe.compress is set. Only TimescaleDB hypertables are affected; all other flavors are a no-op success. Failures are non-fatal and never raise.

Parameters
  • pipe (mrsm.Pipe): The pipe whose target table should have a compression policy.
Returns
  • A SuccessTuple indicating success.
def set_integer_now_func(self, pipe: meerschaum.Pipe, debug: bool = False) -> bool:
45def set_integer_now_func(
46    self,
47    pipe: mrsm.Pipe,
48    debug: bool = False,
49) -> bool:
50    """
51    Register an `integer_now` function if the pipe's datetime axis is an integer.
52    Returns `True` when nothing needed doing or the function was registered.
53    """
54    return self._rust_method('set_integer_now_func')(pipe)

Register an integer_now function if the pipe's datetime axis is an integer. Returns True when nothing needed doing or the function was registered.

def vacuum_pipe( self, pipe: meerschaum.Pipe, full: bool = False, debug: bool = False, **kwargs: Any) -> Tuple[bool, str]:
18def vacuum_pipe(
19    self,
20    pipe: mrsm.Pipe,
21    full: bool = False,
22    debug: bool = False,
23    **kwargs: Any
24) -> SuccessTuple:
25    """
26    Reclaim dead-tuple disk space from a pipe's target table.
27
28    PostgreSQL-family tables run `VACUUM` (optionally `VACUUM FULL`); TimescaleDB hypertables
29    recurse into their chunks; MySQL/MariaDB run `OPTIMIZE TABLE`; MSSQL rebuilds the table;
30    SQLite vacuums the whole database file.
31
32    Parameters
33    ----------
34    pipe: mrsm.Pipe
35        The pipe whose target table to vacuum.
36
37    full: bool, default False
38        If `True` (PostgreSQL family only), run `VACUUM FULL`, which rewrites the table and
39        returns freed space to the operating system at the cost of an exclusive lock.
40
41    debug: bool, default False
42        Verbosity toggle.
43
44    Returns
45    -------
46    A `SuccessTuple` indicating success, including the amount of disk reclaimed.
47    """
48    return self._rust_method('vacuum_pipe')(pipe, full=full)

Reclaim dead-tuple disk space from a pipe's target table.

PostgreSQL-family tables run VACUUM (optionally VACUUM FULL); TimescaleDB hypertables recurse into their chunks; MySQL/MariaDB run OPTIMIZE TABLE; MSSQL rebuilds the table; SQLite vacuums the whole database file.

Parameters
  • pipe (mrsm.Pipe): The pipe whose target table to vacuum.
  • full (bool, default False): If True (PostgreSQL family only), run VACUUM FULL, which rewrites the table and returns freed space to the operating system at the cost of an exclusive lock.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A SuccessTuple indicating success, including the amount of disk reclaimed.
def analyze_pipe( self, pipe: meerschaum.Pipe, debug: bool = False, **kwargs: Any) -> Tuple[bool, str]:
51def analyze_pipe(
52    self,
53    pipe: mrsm.Pipe,
54    debug: bool = False,
55    **kwargs: Any
56) -> SuccessTuple:
57    """
58    Refresh the database planner's statistics for a pipe's target table.
59
60    This does not reclaim disk space; it helps the query planner choose better plans after
61    large syncs. PostgreSQL/SQLite run `ANALYZE`, MySQL/MariaDB run `ANALYZE TABLE`, and MSSQL
62    runs `UPDATE STATISTICS`.
63
64    Parameters
65    ----------
66    pipe: mrsm.Pipe
67        The pipe whose target table to analyze.
68
69    debug: bool, default False
70        Verbosity toggle.
71
72    Returns
73    -------
74    A `SuccessTuple` indicating success.
75    """
76    return self._rust_method('analyze_pipe')(pipe)

Refresh the database planner's statistics for a pipe's target table.

This does not reclaim disk space; it helps the query planner choose better plans after large syncs. PostgreSQL/SQLite run ANALYZE, MySQL/MariaDB run ANALYZE TABLE, and MSSQL runs UPDATE STATISTICS.

Parameters
  • pipe (mrsm.Pipe): The pipe whose target table to analyze.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A SuccessTuple indicating success.
def get_partition_info(self, pipe: meerschaum.Pipe, debug: bool = False) -> dict:
25def get_partition_info(self, pipe: mrsm.Pipe, debug: bool = False) -> dict:
26    """
27    Return a summary of a pipe's target table partitioning for `show partitions`.
28
29    Keys:
30    - `flavor`: the connector flavor.
31    - `partitioned`: whether the table is range-partitioned (native) or a TimescaleDB hypertable.
32    - `count`: the number of partitions / chunks (`None` if unknown).
33    - `interval`: the physical partition width (`timedelta`, epoch-`int`, or `None`).
34    """
35    return self._rust_method('get_partition_info')(pipe)

Return a summary of a pipe's target table partitioning for show partitions.

Keys:

  • flavor: the connector flavor.
  • partitioned: whether the table is range-partitioned (native) or a TimescaleDB hypertable.
  • count: the number of partitions / chunks (None if unknown).
  • interval: the physical partition width (timedelta, epoch-int, or None).
def partition_pipe( self, pipe: meerschaum.Pipe, chunk_minutes: int | None = None, debug: bool = False, **kwargs: Any) -> Tuple[bool, str]:
38def partition_pipe(
39    self,
40    pipe: mrsm.Pipe,
41    chunk_minutes: Optional[int] = None,
42    debug: bool = False,
43    **kwargs: Any
44) -> SuccessTuple:
45    """
46    Rebuild a pipe's target table to a new partition (chunk) width.
47
48    The width is taken from `chunk_minutes` if provided, else the pipe's configured
49    `verify.chunk_minutes`. The new width is persisted to `verify.chunk_minutes`, which is the
50    authoritative partition width (see `Pipe.get_chunk_interval`).
51
52    Strategy by flavor:
53
54    - **TimescaleDB**: call `set_chunk_time_interval()`. This changes the width of FUTURE chunks
55      only; existing chunks are not rewritten.
56    - **PostgreSQL / PostGIS, MySQL / MariaDB, MSSQL**: rebuild the table by reading its data,
57      dropping it, and re-syncing at the new width. This reuses the tested `create_pipe_table_from_df`
58      and `_create_missing_partitions` paths, and (for MSSQL) frees the partition function/scheme
59      names so they can be recreated. The whole table is read into memory; for very large tables
60      consider a manual chunked rebuild.
61
62    Parameters
63    ----------
64    pipe: mrsm.Pipe
65        The partitioned pipe whose target table to repartition.
66
67    chunk_minutes: Optional[int], default None
68        The new partition width in minutes. Defaults to the pipe's `verify.chunk_minutes`.
69
70    debug: bool, default False
71        Verbosity toggle.
72
73    Returns
74    -------
75    A `SuccessTuple` indicating success.
76    """
77    result = self._rust_method('partition_pipe')(pipe, chunk_minutes=chunk_minutes)
78    if result[0] and not pipe.temporary:
79        ### v4 sets `verify.chunk_minutes` on the Python pipe (`update_parameters`);
80        ### Rust persisted it, so mirror the registered value in memory.
81        verify = (
82            (self.get_pipe_attributes(pipe, debug=debug) or {})
83            .get('parameters', {})
84            .get('verify', None)
85        )
86        if isinstance(verify, dict) and 'chunk_minutes' in verify:
87            pipe.update_parameters(
88                {'verify': {'chunk_minutes': verify['chunk_minutes']}},
89                persist=False,
90                debug=debug,
91            )
92    return result

Rebuild a pipe's target table to a new partition (chunk) width.

The width is taken from chunk_minutes if provided, else the pipe's configured verify.chunk_minutes. The new width is persisted to verify.chunk_minutes, which is the authoritative partition width (see Pipe.get_chunk_interval).

Strategy by flavor:

  • TimescaleDB: call set_chunk_time_interval(). This changes the width of FUTURE chunks only; existing chunks are not rewritten.
  • PostgreSQL / PostGIS, MySQL / MariaDB, MSSQL: rebuild the table by reading its data, dropping it, and re-syncing at the new width. This reuses the tested create_pipe_table_from_df and _create_missing_partitions paths, and (for MSSQL) frees the partition function/scheme names so they can be recreated. The whole table is read into memory; for very large tables consider a manual chunked rebuild.
Parameters
  • pipe (mrsm.Pipe): The partitioned pipe whose target table to repartition.
  • chunk_minutes (Optional[int], default None): The new partition width in minutes. Defaults to the pipe's verify.chunk_minutes.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A SuccessTuple indicating success.
def fetch_pipes_keys( self, connector_keys: List[str] | None = None, metric_keys: List[str] | None = None, location_keys: List[str] | None = None, tags: List[str] | None = None, params: Dict[str, Any] | None = None, debug: bool = False) -> Dict[int, Tuple[str, str, str | None, Dict[str, Any]]]:
 58def fetch_pipes_keys(
 59    self,
 60    connector_keys: Optional[List[str]] = None,
 61    metric_keys: Optional[List[str]] = None,
 62    location_keys: Optional[List[str]] = None,
 63    tags: Optional[List[str]] = None,
 64    params: Optional[Dict[str, Any]] = None,
 65    debug: bool = False,
 66) -> Dict[
 67        int, Tuple[str, str, Union[str, None], Dict[str, Any]]
 68    ]:
 69    """
 70    Return a dictionary mapping pipe IDs to key tuples corresponding to the parameters provided.
 71
 72    Parameters
 73    ----------
 74    connector_keys: Optional[List[str]], default None
 75        List of connector_keys to search by.
 76
 77    metric_keys: Optional[List[str]], default None
 78        List of metric_keys to search by.
 79
 80    location_keys: Optional[List[str]], default None
 81        List of location_keys to search by.
 82
 83    tags: Optional[List[str]], default None
 84        List of pipes to search by.
 85
 86    params: Optional[Dict[str, Any]], default None
 87        Dictionary of additional parameters to search by.
 88        E.g. `--params pipe_id:1`
 89
 90    debug: bool, default False
 91        Verbosity toggle.
 92
 93    Returns
 94    -------
 95    A list of tuples of pipes' keys and parameters (connector_keys, metric_key, location_key, parameters).
 96    """
 97    return self._rust_method('fetch_pipes_keys')(
 98        connector_keys=connector_keys,
 99        metric_keys=metric_keys,
100        location_keys=location_keys,
101        tags=tags,
102        params=params,
103    )

Return a dictionary mapping pipe IDs to key tuples corresponding to the parameters provided.

Parameters
  • connector_keys (Optional[List[str]], default None): List of connector_keys to search by.
  • metric_keys (Optional[List[str]], default None): List of metric_keys to search by.
  • location_keys (Optional[List[str]], default None): List of location_keys to search by.
  • tags (Optional[List[str]], default None): List of pipes to search by.
  • params (Optional[Dict[str, Any]], default None): Dictionary of additional parameters to search by. E.g. --params pipe_id:1
  • debug (bool, default False): Verbosity toggle.
Returns
  • A list of tuples of pipes' keys and parameters (connector_keys, metric_key, location_key, parameters).
def create_indices( self, pipe: meerschaum.Pipe, columns: List[str] | None = None, indices: List[str] | None = None, debug: bool = False) -> bool:
118def create_indices(
119    self,
120    pipe: mrsm.Pipe,
121    columns: Optional[List[str]] = None,
122    indices: Optional[List[str]] = None,
123    debug: bool = False
124) -> bool:
125    """
126    Create a pipe's indices.
127    """
128    if pipe.__dict__.get('_skip_check_indices', False):
129        return True
130    return self._rust_method('create_indices')(pipe, columns=columns, indices=indices)

Create a pipe's indices.

def drop_indices( self, pipe: meerschaum.Pipe, columns: List[str] | None = None, indices: List[str] | None = None, debug: bool = False) -> bool:
145def drop_indices(
146    self,
147    pipe: mrsm.Pipe,
148    columns: Optional[List[str]] = None,
149    indices: Optional[List[str]] = None,
150    debug: bool = False
151) -> bool:
152    """
153    Drop a pipe's indices.
154    """
155    return self._rust_method('drop_indices')(pipe, columns=columns, indices=indices)

Drop a pipe's indices.

def get_create_index_queries( self, pipe: meerschaum.Pipe, debug: bool = False) -> Dict[str, List[str]]:
168def get_create_index_queries(
169    self,
170    pipe: mrsm.Pipe,
171    debug: bool = False,
172) -> Dict[str, List[str]]:
173    """
174    Return a dictionary mapping columns to a `CREATE INDEX` or equivalent query.
175
176    Parameters
177    ----------
178    pipe: mrsm.Pipe
179        The pipe to which the queries will correspond.
180
181    Returns
182    -------
183    A dictionary of index names mapping to lists of queries.
184    """
185    return self._rust_method('get_create_index_queries')(pipe)

Return a dictionary mapping columns to a CREATE INDEX or equivalent query.

Parameters
  • pipe (mrsm.Pipe): The pipe to which the queries will correspond.
Returns
  • A dictionary of index names mapping to lists of queries.
def get_drop_index_queries( self, pipe: meerschaum.Pipe, debug: bool = False) -> Dict[str, List[str]]:
188def get_drop_index_queries(
189    self,
190    pipe: mrsm.Pipe,
191    debug: bool = False,
192) -> Dict[str, List[str]]:
193    """
194    Return a dictionary mapping columns to a `DROP INDEX` or equivalent query.
195
196    Parameters
197    ----------
198    pipe: mrsm.Pipe
199        The pipe to which the queries will correspond.
200
201    Returns
202    -------
203    A dictionary of column names mapping to lists of queries.
204    """
205    return self._rust_method('get_drop_index_queries')(pipe)

Return a dictionary mapping columns to a DROP INDEX or equivalent query.

Parameters
  • pipe (mrsm.Pipe): The pipe to which the queries will correspond.
Returns
  • A dictionary of column names mapping to lists of queries.
def delete_pipe( self, pipe: meerschaum.Pipe, debug: bool = False) -> Tuple[bool, str]:
208def delete_pipe(
209    self,
210    pipe: mrsm.Pipe,
211    debug: bool = False,
212) -> SuccessTuple:
213    """
214    Delete a Pipe's registration.
215    """
216    return self._rust_method('delete_pipe')(pipe)

Delete a Pipe's registration.

def rename_pipe( self, pipe: meerschaum.Pipe, connector_keys: str | None = None, metric_key: str | None = None, location_key: str | None = None, clear_location: bool = False, target: str | None = None, dry_run: bool = False, debug: bool = False) -> Dict[str, Any]:
219def rename_pipe(
220    self,
221    pipe: mrsm.Pipe,
222    connector_keys: Optional[str] = None,
223    metric_key: Optional[str] = None,
224    location_key: Optional[str] = None,
225    clear_location: bool = False,
226    target: Optional[str] = None,
227    dry_run: bool = False,
228    debug: bool = False,
229) -> Dict[str, Any]:
230    """
231    Atomically rename a registered Pipe's keys and optionally its physical target table
232    on this SQL instance, returning the structured `RenamePipeReport` dictionary.
233    """
234    return self._rust_method('rename_pipe')(
235        pipe,
236        connector_keys=connector_keys,
237        metric_key=metric_key,
238        location_key=location_key,
239        clear_location=clear_location,
240        target=target,
241        dry_run=dry_run,
242    )

Atomically rename a registered Pipe's keys and optionally its physical target table on this SQL instance, returning the structured RenamePipeReport dictionary.

def get_pipe_data( self, pipe: meerschaum.Pipe, select_columns: List[str] | None = None, omit_columns: List[str] | None = None, begin: datetime.datetime | str | None = None, end: datetime.datetime | str | None = None, params: Dict[str, Any] | None = None, order: str = 'asc', limit: int | None = None, begin_add_minutes: int = 0, end_add_minutes: int = 0, chunksize: int | None = -1, as_iterator: bool = False, as_polars: bool | None = None, as_pandas: bool | None = None, debug: bool = False, **kw: Any) -> pandas.DataFrame | None:
245def get_pipe_data(
246    self,
247    pipe: mrsm.Pipe,
248    select_columns: Optional[List[str]] = None,
249    omit_columns: Optional[List[str]] = None,
250    begin: Union[datetime, str, None] = None,
251    end: Union[datetime, str, None] = None,
252    params: Optional[Dict[str, Any]] = None,
253    order: str = 'asc',
254    limit: Optional[int] = None,
255    begin_add_minutes: int = 0,
256    end_add_minutes: int = 0,
257    chunksize: Optional[int] = -1,
258    as_iterator: bool = False,
259    as_polars: Optional[bool] = None,
260    as_pandas: Optional[bool] = None,
261    debug: bool = False,
262    **kw: Any
263) -> Union[pd.DataFrame, None]:
264    """
265    Access a pipe's data from the SQL instance.
266
267    Parameters
268    ----------
269    pipe: mrsm.Pipe:
270        The pipe to get data from.
271
272    select_columns: Optional[List[str]], default None
273        If provided, only select these given columns.
274        Otherwise select all available columns (i.e. `SELECT *`).
275
276    omit_columns: Optional[List[str]], default None
277        If provided, remove these columns from the selection.
278
279    begin: Union[datetime, str, None], default None
280        If provided, get rows newer than or equal to this value.
281
282    end: Union[datetime, str, None], default None
283        If provided, get rows older than or equal to this value.
284
285    params: Optional[Dict[str, Any]], default None
286        Additional parameters to filter by.
287        See `meerschaum.connectors.sql.build_where`.
288
289    order: Optional[str], default 'asc'
290        The selection order for all of the indices in the query.
291        If `None`, omit the `ORDER BY` clause.
292
293    limit: Optional[int], default None
294        If specified, limit the number of rows retrieved to this value.
295
296    begin_add_minutes: int, default 0
297        The number of minutes to add to the `begin` datetime (i.e. `DATEADD`).
298
299    end_add_minutes: int, default 0
300        The number of minutes to add to the `end` datetime (i.e. `DATEADD`).
301
302    chunksize: Optional[int], default -1
303        The size of dataframe chunks to load into memory.
304
305    as_iterator: bool, default False
306        If `True`, return the chunks iterator directly.
307
308    as_polars: Optional[bool], default None
309        `True` returns Polars, `False` pandas; `None` follows the `dataframe` setting
310        (`meerschaum.utils.dataframe.get_dataframe_library()`).
311
312    as_pandas: Optional[bool], default None
313        `True` returns pandas, `False` Polars; `None` follows the setting.
314
315    debug: bool, default False
316        Verbosity toggle.
317
318    Returns
319    -------
320    A DataFrame of the requested library (an iterator of them with `as_iterator`), or `None`
321    when the table does not exist.
322
323    """
324    from meerschaum.utils.dataframe import wants_polars
325    polars = wants_polars(as_polars=as_polars, as_pandas=as_pandas)
326    result = self._rust_method('get_pipe_data')(
327        pipe,
328        select_columns=select_columns,
329        omit_columns=omit_columns,
330        begin=begin,
331        end=end,
332        params=params,
333        order=order,
334        limit=limit,
335        begin_add_minutes=begin_add_minutes,
336        end_add_minutes=end_add_minutes,
337        chunksize=chunksize,
338        as_iterator=as_iterator,
339        as_polars=polars,
340        **kw
341    )
342    if polars and as_iterator and result is not None:
343        ### The binding's chunks are pandas frames: the helper converts each to Polars.
344        from meerschaum.utils.dataframe import frame_from_arrow
345        return (frame_from_arrow(chunk, as_polars=True) for chunk in result)
346    return result

Access a pipe's data from the SQL instance.

Parameters
  • pipe (mrsm.Pipe:): The pipe to get data from.
  • select_columns (Optional[List[str]], default None): If provided, only select these given columns. Otherwise select all available columns (i.e. SELECT *).
  • omit_columns (Optional[List[str]], default None): If provided, remove these columns from the selection.
  • begin (Union[datetime, str, None], default None): If provided, get rows newer than or equal to this value.
  • end (Union[datetime, str, None], default None): If provided, get rows older than or equal to this value.
  • params (Optional[Dict[str, Any]], default None): Additional parameters to filter by. See meerschaum.connectors.sql.build_where.
  • order (Optional[str], default 'asc'): The selection order for all of the indices in the query. If None, omit the ORDER BY clause.
  • limit (Optional[int], default None): If specified, limit the number of rows retrieved to this value.
  • begin_add_minutes (int, default 0): The number of minutes to add to the begin datetime (i.e. DATEADD).
  • end_add_minutes (int, default 0): The number of minutes to add to the end datetime (i.e. DATEADD).
  • chunksize (Optional[int], default -1): The size of dataframe chunks to load into memory.
  • as_iterator (bool, default False): If True, return the chunks iterator directly.
  • as_polars (Optional[bool], default None): True returns Polars, False pandas; None follows the dataframe setting (meerschaum.utils.dataframe.get_dataframe_library()).
  • as_pandas (Optional[bool], default None): True returns pandas, False Polars; None follows the setting.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A DataFrame of the requested library (an iterator of them with as_iterator), or None
  • when the table does not exist.
def get_pipe_docs( self, pipe: meerschaum.Pipe, select_columns: List[str] | None = None, omit_columns: List[str] | None = None, begin: datetime.datetime | str | None = None, end: datetime.datetime | str | None = None, params: Dict[str, Any] | None = None, order: str = 'asc', limit: int | None = None, debug: bool = False, **kw: Any) -> List[Dict[str, Any]]:
349def get_pipe_docs(
350    self,
351    pipe: mrsm.Pipe,
352    select_columns: Optional[List[str]] = None,
353    omit_columns: Optional[List[str]] = None,
354    begin: Union[datetime, str, None] = None,
355    end: Union[datetime, str, None] = None,
356    params: Optional[Dict[str, Any]] = None,
357    order: str = 'asc',
358    limit: Optional[int] = None,
359    debug: bool = False,
360    **kw: Any
361) -> List[Dict[str, Any]]:
362    """
363    Return a pipe's data as a list of dictionaries, bypassing pandas overhead.
364    """
365    return self._rust_method('get_pipe_docs')(
366        pipe,
367        select_columns=select_columns,
368        omit_columns=omit_columns,
369        begin=begin,
370        end=end,
371        params=params,
372        order=order,
373        limit=limit,
374    )

Return a pipe's data as a list of dictionaries, bypassing pandas overhead.

def get_pipe_data_query( self, pipe: meerschaum.Pipe, select_columns: List[str] | None = None, omit_columns: List[str] | None = None, begin: datetime.datetime | int | str | None = None, end: datetime.datetime | int | str | None = None, params: Dict[str, Any] | None = None, order: str | None = 'asc', sort_datetimes: bool = False, limit: int | None = None, begin_add_minutes: int = 0, end_add_minutes: int = 0, replace_nulls: str | None = None, skip_existing_cols_check: bool = False, debug: bool = False, **kw: Any) -> str | None:
377def get_pipe_data_query(
378    self,
379    pipe: mrsm.Pipe,
380    select_columns: Optional[List[str]] = None,
381    omit_columns: Optional[List[str]] = None,
382    begin: Union[datetime, int, str, None] = None,
383    end: Union[datetime, int, str, None] = None,
384    params: Optional[Dict[str, Any]] = None,
385    order: Optional[str] = 'asc',
386    sort_datetimes: bool = False,
387    limit: Optional[int] = None,
388    begin_add_minutes: int = 0,
389    end_add_minutes: int = 0,
390    replace_nulls: Optional[str] = None,
391    skip_existing_cols_check: bool = False,
392    debug: bool = False,
393    **kw: Any
394) -> Union[str, None]:
395    """
396    Return the `SELECT` query for retrieving a pipe's data from its instance.
397
398    Parameters
399    ----------
400    pipe: mrsm.Pipe:
401        The pipe to get data from.
402
403    select_columns: Optional[List[str]], default None
404        If provided, only select these given columns.
405        Otherwise select all available columns (i.e. `SELECT *`).
406
407    omit_columns: Optional[List[str]], default None
408        If provided, remove these columns from the selection.
409
410    begin: Union[datetime, int, str, None], default None
411        If provided, get rows newer than or equal to this value.
412
413    end: Union[datetime, str, None], default None
414        If provided, get rows older than or equal to this value.
415
416    params: Optional[Dict[str, Any]], default None
417        Additional parameters to filter by.
418        See `meerschaum.connectors.sql.build_where`.
419
420    order: Optional[str], default None
421        The selection order for all of the indices in the query.
422        If `None`, omit the `ORDER BY` clause.
423
424    sort_datetimes: bool, default False
425        Alias for `order='desc'`.
426
427    limit: Optional[int], default None
428        If specified, limit the number of rows retrieved to this value.
429
430    begin_add_minutes: int, default 0
431        The number of minutes to add to the `begin` datetime (i.e. `DATEADD`).
432
433    end_add_minutes: int, default 0
434        The number of minutes to add to the `end` datetime (i.e. `DATEADD`).
435
436    chunksize: Optional[int], default -1
437        The size of dataframe chunks to load into memory.
438
439    replace_nulls: Optional[str], default None
440        If provided, replace null values with this value.
441
442    skip_existing_cols_check: bool, default False
443        If `True`, do not verify that querying columns are actually on the table.
444
445    debug: bool, default False
446        Verbosity toggle.
447
448    Returns
449    -------
450    A `SELECT` query to retrieve a pipe's data.
451    """
452    return self._rust_method('get_pipe_data_query')(
453        pipe,
454        select_columns=select_columns,
455        omit_columns=omit_columns,
456        begin=begin,
457        end=end,
458        params=params,
459        order=order,
460        sort_datetimes=sort_datetimes,
461        limit=limit,
462        begin_add_minutes=begin_add_minutes,
463        end_add_minutes=end_add_minutes,
464        replace_nulls=replace_nulls,
465        skip_existing_cols_check=skip_existing_cols_check,
466    )

Return the SELECT query for retrieving a pipe's data from its instance.

Parameters
  • pipe (mrsm.Pipe:): The pipe to get data from.
  • select_columns (Optional[List[str]], default None): If provided, only select these given columns. Otherwise select all available columns (i.e. SELECT *).
  • omit_columns (Optional[List[str]], default None): If provided, remove these columns from the selection.
  • begin (Union[datetime, int, str, None], default None): If provided, get rows newer than or equal to this value.
  • end (Union[datetime, str, None], default None): If provided, get rows older than or equal to this value.
  • params (Optional[Dict[str, Any]], default None): Additional parameters to filter by. See meerschaum.connectors.sql.build_where.
  • order (Optional[str], default None): The selection order for all of the indices in the query. If None, omit the ORDER BY clause.
  • sort_datetimes (bool, default False): Alias for order='desc'.
  • limit (Optional[int], default None): If specified, limit the number of rows retrieved to this value.
  • begin_add_minutes (int, default 0): The number of minutes to add to the begin datetime (i.e. DATEADD).
  • end_add_minutes (int, default 0): The number of minutes to add to the end datetime (i.e. DATEADD).
  • chunksize (Optional[int], default -1): The size of dataframe chunks to load into memory.
  • replace_nulls (Optional[str], default None): If provided, replace null values with this value.
  • skip_existing_cols_check (bool, default False): If True, do not verify that querying columns are actually on the table.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A SELECT query to retrieve a pipe's data.
def register_pipe( self, pipe: meerschaum.Pipe, debug: bool = False) -> Tuple[bool, str]:
23def register_pipe(
24    self,
25    pipe: mrsm.Pipe,
26    debug: bool = False,
27) -> SuccessTuple:
28    """
29    Register a new pipe.
30    A pipe's attributes must be set before registering.
31    """
32    return self._rust_method('register_pipe')(pipe)

Register a new pipe. A pipe's attributes must be set before registering.

def edit_pipe( self, pipe: meerschaum.Pipe, patch: bool = False, debug: bool = False, **kw: Any) -> Tuple[bool, str]:
35def edit_pipe(
36    self,
37    pipe: mrsm.Pipe,
38    patch: bool = False,
39    debug: bool = False,
40    **kw : Any
41) -> SuccessTuple:
42    """
43    Persist a Pipe's parameters to its database.
44
45    Parameters
46    ----------
47    pipe: mrsm.Pipe, default None
48        The pipe to be edited.
49    patch: bool, default False
50        If patch is `True`, update the existing parameters by cascading.
51        Otherwise overwrite the parameters (default).
52    debug: bool, default False
53        Verbosity toggle.
54    """
55    return self._rust_method('edit_pipe')(pipe, patch=patch)

Persist a Pipe's parameters to its database.

Parameters
  • pipe (mrsm.Pipe, default None): The pipe to be edited.
  • patch (bool, default False): If patch is True, update the existing parameters by cascading. Otherwise overwrite the parameters (default).
  • debug (bool, default False): Verbosity toggle.
def get_pipe_id(self, pipe: meerschaum.Pipe, debug: bool = False) -> Any:
469def get_pipe_id(
470    self,
471    pipe: mrsm.Pipe,
472    debug: bool = False,
473) -> Any:
474    """
475    Get a Pipe's ID from the pipes table.
476    """
477    return self._rust_method('get_pipe_id')(pipe)

Get a Pipe's ID from the pipes table.

def get_pipe_attributes( self, pipe: meerschaum.Pipe, debug: bool = False) -> Dict[str, Any]:
480def get_pipe_attributes(
481    self,
482    pipe: mrsm.Pipe,
483    debug: bool = False,
484) -> Dict[str, Any]:
485    """
486    Get a Pipe's attributes dictionary.
487    """
488    return self._rust_method('get_pipe_attributes')(pipe)

Get a Pipe's attributes dictionary.

def sync_pipe( self, pipe: meerschaum.Pipe, df: pandas.DataFrame | str | Dict[Any, Any] | None = None, begin: datetime.datetime | int | None = None, end: datetime.datetime | int | None = None, chunksize: int | None = -1, check_existing: bool = True, blocking: bool = True, debug: bool = False, _check_temporary_tables: bool = True, **kw: Any) -> Tuple[bool, str]:
491def sync_pipe(
492    self,
493    pipe: mrsm.Pipe,
494    df: Union[pd.DataFrame, str, Dict[Any, Any], None] = None,
495    begin: Union[datetime, int, None] = None,
496    end: Union[datetime, int, None] = None,
497    chunksize: Optional[int] = -1,
498    check_existing: bool = True,
499    blocking: bool = True,
500    debug: bool = False,
501    _check_temporary_tables: bool = True,
502    **kw: Any
503) -> SuccessTuple:
504    """
505    Sync a pipe using a database connection.
506
507    Parameters
508    ----------
509    pipe: mrsm.Pipe
510        The Meerschaum Pipe instance into which to sync the data.
511
512    df: Union[pandas.DataFrame, str, Dict[Any, Any], List[Dict[str, Any]]]
513        An optional DataFrame or equivalent to sync into the pipe.
514        Defaults to `None`.
515
516    begin: Union[datetime, int, None], default None
517        Optionally specify the earliest datetime to search for data.
518        Defaults to `None`.
519
520    end: Union[datetime, int, None], default None
521        Optionally specify the latest datetime to search for data.
522        Defaults to `None`.
523
524    chunksize: Optional[int], default -1
525        Specify the number of rows to sync per chunk.
526        If `-1`, resort to system configuration (default is `900`).
527        A `chunksize` of `None` will sync all rows in one transaction.
528        Defaults to `-1`.
529
530    check_existing: bool, default True
531        If `True`, pull and diff with existing data from the pipe. Defaults to `True`.
532
533    blocking: bool, default True
534        If `True`, wait for sync to finish and return its result, otherwise asyncronously sync.
535        Defaults to `True`.
536
537    debug: bool, default False
538        Verbosity toggle. Defaults to False.
539
540    kw: Any
541        Catch-all for keyword arguments. `replace=True` replaces the pipe's rows of
542        `[begin, end)` (matching `params`) with the rows of `df` in one transaction; a bound
543        that is not given is the rows' own datetime range (`begin` = the earliest, `end` = just
544        after the latest), as for `pipe.sync(df, replace=True)`.
545
546    Returns
547    -------
548    A `SuccessTuple` of success (`bool`) and message (`str`).
549    """
550    if df is not None and type(df).__module__.split('.', maxsplit=1)[0] != 'pandas':
551        df = pipe.enforce_dtypes(
552            df,
553            chunksize=chunksize,
554            safe_copy=kw.get('safe_copy', False),
555            dtypes=pipe.get_dtypes(debug=debug),
556            debug=debug,
557        )
558    replace_kw = (
559        {'replace': True, 'params': kw.get('params', None)}
560        if kw.get('replace', False)
561        else {}
562    )
563    result = self._rust_method('sync_pipe')(
564        pipe,
565        df,
566        begin=begin,
567        end=end,
568        chunksize=chunksize,
569        check_existing=check_existing,
570        **replace_kw
571    )
572    if hasattr(pipe, '_clear_cache_key'):
573        for cache_key in (
574            '_exists', '_columns_types', '_columns_types_timestamp',
575            '_columns_indices', '_columns_indices_timestamp',
576        ):
577            pipe._clear_cache_key(cache_key, debug=debug)
578    return result

Sync a pipe using a database connection.

Parameters
  • pipe (mrsm.Pipe): The Meerschaum Pipe instance into which to sync the data.
  • df (Union[pandas.DataFrame, str, Dict[Any, Any], List[Dict[str, Any]]]): An optional DataFrame or equivalent to sync into the pipe. Defaults to None.
  • begin (Union[datetime, int, None], default None): Optionally specify the earliest datetime to search for data. Defaults to None.
  • end (Union[datetime, int, None], default None): Optionally specify the latest datetime to search for data. Defaults to None.
  • chunksize (Optional[int], default -1): Specify the number of rows to sync per chunk. If -1, resort to system configuration (default is 900). A chunksize of None will sync all rows in one transaction. Defaults to -1.
  • check_existing (bool, default True): If True, pull and diff with existing data from the pipe. Defaults to True.
  • blocking (bool, default True): If True, wait for sync to finish and return its result, otherwise asyncronously sync. Defaults to True.
  • debug (bool, default False): Verbosity toggle. Defaults to False.
  • kw (Any): Catch-all for keyword arguments. replace=True replaces the pipe's rows of [begin, end) (matching params) with the rows of df in one transaction; a bound that is not given is the rows' own datetime range (begin = the earliest, end = just after the latest), as for pipe.sync(df, replace=True).
Returns
  • A SuccessTuple of success (bool) and message (str).
def sync_pipe_inplace( self, pipe: meerschaum.Pipe, params: Dict[str, Any] | None = None, begin: datetime.datetime | int | None = None, end: datetime.datetime | int | None = None, chunksize: int | None = -1, check_existing: bool = True, debug: bool = False, **kw: Any) -> Tuple[bool, str]:
581def sync_pipe_inplace(
582    self,
583    pipe: 'mrsm.Pipe',
584    params: Optional[Dict[str, Any]] = None,
585    begin: Union[datetime, int, None] = None,
586    end: Union[datetime, int, None] = None,
587    chunksize: Optional[int] = -1,
588    check_existing: bool = True,
589    debug: bool = False,
590    **kw: Any
591) -> SuccessTuple:
592    """
593    If a pipe's connector is the same as its instance connector,
594    it's more efficient to sync the pipe in-place rather than reading data into Pandas.
595
596    Parameters
597    ----------
598    pipe: mrsm.Pipe
599        The pipe whose connector is the same as its instance.
600
601    params: Optional[Dict[str, Any]], default None
602        Optional params dictionary to build the `WHERE` clause.
603        See `meerschaum.utils.sql.build_where`.
604
605    begin: Union[datetime, int, None], default None
606        Optionally specify the earliest datetime to search for data.
607        Defaults to `None`.
608
609    end: Union[datetime, int, None], default None
610        Optionally specify the latest datetime to search for data.
611        Defaults to `None`.
612
613    chunksize: Optional[int], default -1
614        Specify the number of rows to sync per chunk.
615        If `-1`, resort to system configuration (default is `900`).
616        A `chunksize` of `None` will sync all rows in one transaction.
617        Defaults to `-1`.
618
619    check_existing: bool, default True
620        If `True`, pull and diff with existing data from the pipe.
621
622    debug: bool, default False
623        Verbosity toggle.
624
625    Returns
626    -------
627    A SuccessTuple.
628    """
629    if self.flavor == 'duckdb':
630        return pipe.sync(
631            params=params,
632            begin=begin,
633            end=end,
634            chunksize=chunksize,
635            check_existing=check_existing,
636            debug=debug,
637            _inplace=False,
638            **kw
639        )
640    from meerschaum import _core
641    result = _core.sync_pipe_inplace(
642        self._core_connector(),
643        pipe,
644        params,
645        begin,
646        end,
647        check_existing,
648    )
649    ### The in-place sync may have added or retyped columns behind the pipe's cache.
650    pipe._clear_cache_key('_columns_types', debug=debug)
651    pipe._clear_cache_key('_columns_indices', debug=debug)
652    return result

If a pipe's connector is the same as its instance connector, it's more efficient to sync the pipe in-place rather than reading data into Pandas.

Parameters
  • pipe (mrsm.Pipe): The pipe whose connector is the same as its instance.
  • params (Optional[Dict[str, Any]], default None): Optional params dictionary to build the WHERE clause. See meerschaum.utils.sql.build_where.
  • begin (Union[datetime, int, None], default None): Optionally specify the earliest datetime to search for data. Defaults to None.
  • end (Union[datetime, int, None], default None): Optionally specify the latest datetime to search for data. Defaults to None.
  • chunksize (Optional[int], default -1): Specify the number of rows to sync per chunk. If -1, resort to system configuration (default is 900). A chunksize of None will sync all rows in one transaction. Defaults to -1.
  • check_existing (bool, default True): If True, pull and diff with existing data from the pipe.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A SuccessTuple.
def get_sync_time( self, pipe: meerschaum.Pipe, params: Dict[str, Any] | None = None, newest: bool = True, remote: bool = False, debug: bool = False) -> datetime.datetime | int | None:
655def get_sync_time(
656    self,
657    pipe: 'mrsm.Pipe',
658    params: Optional[Dict[str, Any]] = None,
659    newest: bool = True,
660    remote: bool = False,
661    debug: bool = False,
662) -> Union[datetime, int, None]:
663    """Get a Pipe's most recent datetime value.
664
665    Parameters
666    ----------
667    pipe: mrsm.Pipe
668        The pipe to get the sync time for.
669
670    params: Optional[Dict[str, Any]], default None
671        Optional params dictionary to build the `WHERE` clause.
672        See `meerschaum.utils.sql.build_where`.
673
674    newest: bool, default True
675        If `True`, get the most recent datetime (honoring `params`).
676        If `False`, get the oldest datetime (ASC instead of DESC).
677
678    remote: bool, default False
679        If `True`, return the sync time for the remote fetch definition.
680
681    Returns
682    -------
683    A `datetime` object (or `int` if using an integer axis) if the pipe exists, otherwise `None`.
684    """
685    return self._rust_method('get_sync_time')(pipe, params=params, newest=newest, remote=remote)

Get a Pipe's most recent datetime value.

Parameters
  • pipe (mrsm.Pipe): The pipe to get the sync time for.
  • params (Optional[Dict[str, Any]], default None): Optional params dictionary to build the WHERE clause. See meerschaum.utils.sql.build_where.
  • newest (bool, default True): If True, get the most recent datetime (honoring params). If False, get the oldest datetime (ASC instead of DESC).
  • remote (bool, default False): If True, return the sync time for the remote fetch definition.
Returns
  • A datetime object (or int if using an integer axis) if the pipe exists, otherwise None.
def pipe_exists(self, pipe: meerschaum.Pipe, debug: bool = False) -> bool:
688def pipe_exists(
689    self,
690    pipe: mrsm.Pipe,
691    debug: bool = False
692) -> bool:
693    """
694    Check that a Pipe's table exists.
695
696    Parameters
697    ----------
698    pipe: mrsm.Pipe:
699        The pipe to check.
700
701    debug: bool, default False
702        Verbosity toggle.
703
704    Returns
705    -------
706    A `bool` corresponding to whether a pipe's table exists.
707
708    """
709    return self._rust_method('pipe_exists')(pipe)

Check that a Pipe's table exists.

Parameters
  • pipe (mrsm.Pipe:): The pipe to check.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A bool corresponding to whether a pipe's table exists.
def get_pipe_rowcount( self, pipe: meerschaum.Pipe, begin: datetime.datetime | int | None = None, end: datetime.datetime | int | None = None, params: Dict[str, Any] | None = None, remote: bool = False, debug: bool = False) -> int | None:
712def get_pipe_rowcount(
713    self,
714    pipe: mrsm.Pipe,
715    begin: Union[datetime, int, None] = None,
716    end: Union[datetime, int, None] = None,
717    params: Optional[Dict[str, Any]] = None,
718    remote: bool = False,
719    debug: bool = False
720) -> Union[int, None]:
721    """
722    Get the rowcount for a pipe in accordance with given parameters.
723
724    Parameters
725    ----------
726    pipe: mrsm.Pipe
727        The pipe to query with.
728
729    begin: Union[datetime, int, None], default None
730        The begin datetime value.
731
732    end: Union[datetime, int, None], default None
733        The end datetime value.
734
735    params: Optional[Dict[str, Any]], default None
736        See `meerschaum.utils.sql.build_where`.
737
738    remote: bool, default False
739        If `True`, get the rowcount for the remote table.
740
741    debug: bool, default False
742        Verbosity toggle.
743
744    Returns
745    -------
746    An `int` for the number of rows if the `pipe` exists, otherwise `None`.
747
748    """
749    return self._rust_method('get_pipe_rowcount')(pipe, begin=begin, end=end, params=params, remote=remote)

Get the rowcount for a pipe in accordance with given parameters.

Parameters
  • pipe (mrsm.Pipe): The pipe to query with.
  • begin (Union[datetime, int, None], default None): The begin datetime value.
  • end (Union[datetime, int, None], default None): The end datetime value.
  • params (Optional[Dict[str, Any]], default None): See meerschaum.utils.sql.build_where.
  • remote (bool, default False): If True, get the rowcount for the remote table.
  • debug (bool, default False): Verbosity toggle.
Returns
  • An int for the number of rows if the pipe exists, otherwise None.
def drop_pipe( self, pipe: meerschaum.Pipe, debug: bool = False, **kw) -> Tuple[bool, str]:
752def drop_pipe(
753    self,
754    pipe: mrsm.Pipe,
755    debug: bool = False,
756    **kw
757) -> SuccessTuple:
758    """
759    Drop a pipe's tables but maintain its registration.
760
761    Parameters
762    ----------
763    pipe: mrsm.Pipe
764        The pipe to drop.
765
766    Returns
767    -------
768    A `SuccessTuple` indicated success.
769    """
770    return self._rust_method('drop_pipe')(pipe)

Drop a pipe's tables but maintain its registration.

Parameters
  • pipe (mrsm.Pipe): The pipe to drop.
Returns
  • A SuccessTuple indicated success.
def clear_pipe( self, pipe: meerschaum.Pipe, begin: datetime.datetime | int | None = None, end: datetime.datetime | int | None = None, params: Dict[str, Any] | None = None, debug: bool = False, **kw) -> Tuple[bool, str]:
773def clear_pipe(
774    self,
775    pipe: mrsm.Pipe,
776    begin: Union[datetime, int, None] = None,
777    end: Union[datetime, int, None] = None,
778    params: Optional[Dict[str, Any]] = None,
779    debug: bool = False,
780    **kw
781) -> SuccessTuple:
782    """
783    Delete a pipe's data within a bounded or unbounded interval without dropping the table.
784
785    Parameters
786    ----------
787    pipe: mrsm.Pipe
788        The pipe to clear.
789        
790    begin: Union[datetime, int, None], default None
791        Beginning datetime. Inclusive.
792
793    end: Union[datetime, int, None], default None
794         Ending datetime. Exclusive.
795
796    params: Optional[Dict[str, Any]], default None
797         See `meerschaum.utils.sql.build_where`.
798
799    """
800    return self._rust_method('clear_pipe')(pipe, begin=begin, end=end, params=params)

Delete a pipe's data within a bounded or unbounded interval without dropping the table.

Parameters
  • pipe (mrsm.Pipe): The pipe to clear.
  • begin (Union[datetime, int, None], default None): Beginning datetime. Inclusive.
  • end (Union[datetime, int, None], default None): Ending datetime. Exclusive.
  • params (Optional[Dict[str, Any]], default None): See meerschaum.utils.sql.build_where.
def deduplicate_pipe( self, pipe: meerschaum.Pipe, begin: datetime.datetime | int | None = None, end: datetime.datetime | int | None = None, params: Dict[str, Any] | None = None, debug: bool = False, **kwargs: Any) -> Tuple[bool, str]:
887def deduplicate_pipe(
888    self,
889    pipe: mrsm.Pipe,
890    begin: Union[datetime, int, None] = None,
891    end: Union[datetime, int, None] = None,
892    params: Optional[Dict[str, Any]] = None,
893    debug: bool = False,
894    **kwargs: Any
895) -> SuccessTuple:
896    """
897    Delete duplicate values within a pipe's table.
898
899    Parameters
900    ----------
901    pipe: mrsm.Pipe
902        The pipe whose table to deduplicate.
903
904    begin: Union[datetime, int, None], default None
905        If provided, only deduplicate values greater than or equal to this value.
906
907    end: Union[datetime, int, None], default None
908        If provided, only deduplicate values less than this value.
909
910    params: Optional[Dict[str, Any]], default None
911        If provided, further limit deduplication to values which match this query dictionary.
912
913    debug: bool, default False
914        Verbosity toggle.
915
916    Returns
917    -------
918    A `SuccessTuple` indicating success.
919    """
920    return self._rust_method('deduplicate_pipe')(pipe, begin=begin, end=end, params=params)

Delete duplicate values within a pipe's table.

Parameters
  • pipe (mrsm.Pipe): The pipe whose table to deduplicate.
  • begin (Union[datetime, int, None], default None): If provided, only deduplicate values greater than or equal to this value.
  • end (Union[datetime, int, None], default None): If provided, only deduplicate values less than this value.
  • params (Optional[Dict[str, Any]], default None): If provided, further limit deduplication to values which match this query dictionary.
  • debug (bool, default False): Verbosity toggle.
Returns
  • A SuccessTuple indicating success.
def get_pipe_table( self, pipe: meerschaum.Pipe, debug: bool = False) -> "Union['sqlalchemy.Table', None]":
803def get_pipe_table(
804    self,
805    pipe: mrsm.Pipe,
806    debug: bool = False,
807) -> Union['sqlalchemy.Table', None]:
808    """
809    Return the `sqlalchemy.Table` object for a `mrsm.Pipe`.
810
811    Parameters
812    ----------
813    pipe: mrsm.Pipe:
814        The pipe in question.
815
816    Returns
817    -------
818    A `sqlalchemy.Table` object. 
819
820    """
821    from meerschaum.utils.sql import get_sqlalchemy_table
822    if not pipe.exists(debug=debug):
823        return None
824
825    return get_sqlalchemy_table(
826        pipe.target,
827        connector=self,
828        schema=self.get_pipe_schema(pipe),
829        debug=debug,
830        refresh=True,
831    )

Return the sqlalchemy.Table object for a mrsm.Pipe.

Parameters
  • pipe (mrsm.Pipe:): The pipe in question.
Returns
  • A sqlalchemy.Table object.
def get_pipe_columns_types( self, pipe: meerschaum.Pipe, debug: bool = False) -> Dict[str, str]:
834def get_pipe_columns_types(
835    self,
836    pipe: mrsm.Pipe,
837    debug: bool = False,
838) -> Dict[str, str]:
839    """
840    Get the pipe's columns and types.
841
842    Parameters
843    ----------
844    pipe: mrsm.Pipe:
845        The pipe to get the columns for.
846
847    Returns
848    -------
849    A dictionary of columns names (`str`) and types (`str`).
850
851    Examples
852    --------
853    >>> conn.get_pipe_columns_types(pipe)
854    {
855      'dt': 'TIMESTAMP WITHOUT TIMEZONE',
856      'id': 'BIGINT',
857      'val': 'DOUBLE PRECISION',
858    }
859    >>> 
860    """
861    return self._rust_method('get_pipe_columns_types')(pipe)

Get the pipe's columns and types.

Parameters
  • pipe (mrsm.Pipe:): The pipe to get the columns for.
Returns
  • A dictionary of columns names (str) and types (str).
Examples
>>> conn.get_pipe_columns_types(pipe)
{
  'dt': 'TIMESTAMP WITHOUT TIMEZONE',
  'id': 'BIGINT',
  'val': 'DOUBLE PRECISION',
}
>>>
def get_pipe_schema(self, pipe: meerschaum.Pipe) -> str | None:
923def get_pipe_schema(self, pipe: mrsm.Pipe) -> Union[str, None]:
924    """
925    Return the schema to use for this pipe.
926    First check `pipe.parameters['schema']`, then check `self.schema`.
927
928    Parameters
929    ----------
930    pipe: mrsm.Pipe
931        The pipe which may contain a configured schema.
932
933    Returns
934    -------
935    A schema string or `None` if nothing is configured.
936    """
937    if self.flavor in ('sqlite', 'geopackage'):
938        return self.schema
939    return pipe.parameters.get('schema', self.schema)

Return the schema to use for this pipe. First check pipe.parameters['schema'], then check self.schema.

Parameters
  • pipe (mrsm.Pipe): The pipe which may contain a configured schema.
Returns
  • A schema string or None if nothing is configured.
def get_pipe_columns_indices( self, pipe: meerschaum.Pipe, debug: bool = False) -> Dict[str, List[Dict[str, str]]]:
864def get_pipe_columns_indices(
865    self,
866    pipe: mrsm.Pipe,
867    debug: bool = False,
868) -> Dict[str, List[Dict[str, str]]]:
869    """
870    Return a dictionary mapping columns to the indices created on those columns.
871
872    Parameters
873    ----------
874    pipe: mrsm.Pipe
875        The pipe to be queried against.
876
877    Returns
878    -------
879    A dictionary mapping columns names to lists of dictionaries.
880    The dictionaries in the lists contain the name and type of the indices.
881    """
882    if pipe.__dict__.get('_skip_check_indices', False):
883        return {}
884    return self._rust_method('get_pipe_columns_indices')(pipe)

Return a dictionary mapping columns to the indices created on those columns.

Parameters
  • pipe (mrsm.Pipe): The pipe to be queried against.
Returns
  • A dictionary mapping columns names to lists of dictionaries.
  • The dictionaries in the lists contain the name and type of the indices.
@staticmethod
def get_temporary_target( target: str, transact_id: str | None = None, label: str | None = None, separator: str | None = None) -> str:
942@staticmethod
943def get_temporary_target(
944    target: str,
945    transact_id: Optional[str] = None,
946    label: Optional[str] = None,
947    separator: Optional[str] = None,
948) -> str:
949    """
950    Return a unique(ish) temporary target for a pipe.
951    """
952    from meerschaum.utils.misc import generate_password
953    temp_target_cf = (
954        mrsm.get_config('system', 'connectors', 'sql', 'instance', 'temporary_target') or {}
955    )
956    transaction_id_len = temp_target_cf.get('transaction_id_length', 3)
957    transact_id = transact_id or generate_password(transaction_id_len)
958    temp_prefix = temp_target_cf.get('prefix', '_')
959    separator = separator or temp_target_cf.get('separator', '_')
960    return (
961        temp_prefix
962        + target
963        + separator
964        + transact_id
965        + ((separator + label) if label else '')
966    )

Return a unique(ish) temporary target for a pipe.

def create_pipe_indices( self, pipe: meerschaum.Pipe, columns: List[str] | None = None, debug: bool = False) -> Tuple[bool, str]:
106def create_pipe_indices(
107    self,
108    pipe: mrsm.Pipe,
109    columns: Optional[List[str]] = None,
110    debug: bool = False,
111) -> SuccessTuple:
112    """
113    Create a pipe's indices.
114    """
115    return self._rust_method('create_pipe_indices')(pipe, columns=columns)

Create a pipe's indices.

def drop_pipe_indices( self, pipe: meerschaum.Pipe, columns: List[str] | None = None, debug: bool = False) -> Tuple[bool, str]:
133def drop_pipe_indices(
134    self,
135    pipe: mrsm.Pipe,
136    columns: Optional[List[str]] = None,
137    debug: bool = False,
138) -> SuccessTuple:
139    """
140    Drop a pipe's indices.
141    """
142    return self._rust_method('drop_pipe_indices')(pipe, columns=columns)

Drop a pipe's indices.

def get_pipe_index_names(self, pipe: meerschaum.Pipe) -> Dict[str, str]:
158def get_pipe_index_names(self, pipe: mrsm.Pipe) -> Dict[str, str]:
159    """
160    Return a dictionary mapping index keys to their names on the database.
161
162    Returns
163    -------
164    A dictionary of index keys to column names.
165    """
166    return self._rust_method('get_pipe_index_names')(pipe)

Return a dictionary mapping index keys to their names on the database.

Returns
  • A dictionary of index keys to column names.
def get_plugins_pipe(self) -> meerschaum.Pipe:
17def get_plugins_pipe(self) -> mrsm.Pipe:
18    """
19    Return the internal metadata plugins pipe.
20    """
21    users_pipe = self.get_users_pipe()
22    user_id_dtype = users_pipe.dtypes.get('user_id', 'int')
23    return mrsm.Pipe(
24        'mrsm', 'plugins',
25        instance=self,
26        temporary=True,
27        static=True,
28        null_indices=False,
29        columns={
30            'primary': 'plugin_id',
31            'user_id': 'user_id',    
32        },
33        dtypes={
34            'plugin_name': 'string',
35            'user_id': user_id_dtype,
36            'attributes': 'json',
37            'version': 'string',
38        },
39        indices={
40            'unique': 'plugin_name',
41        },
42    )

Return the internal metadata plugins pipe.

def register_plugin( self, plugin: meerschaum.Plugin, force: bool = False, debug: bool = False, **kw: Any) -> Tuple[bool, str]:
45def register_plugin(
46    self,
47    plugin: 'mrsm.core.Plugin',
48    force: bool = False,
49    debug: bool = False,
50    **kw: Any
51) -> SuccessTuple:
52    """Register a new plugin to the plugins table."""
53    return self._rust_method('register_plugin')(plugin, force=force)

Register a new plugin to the plugins table.

def delete_plugin( self, plugin: meerschaum.Plugin, debug: bool = False, **kw: Any) -> Tuple[bool, str]:
133def delete_plugin(
134    self,
135    plugin: 'mrsm.core.Plugin',
136    debug: bool = False,
137    **kw: Any
138) -> SuccessTuple:
139    """Delete a plugin from the plugins table."""
140    return self._rust_method('delete_plugin')(plugin)

Delete a plugin from the plugins table.

def get_plugin_id( self, plugin: meerschaum.Plugin, debug: bool = False) -> int | None:
55def get_plugin_id(
56    self,
57    plugin: 'mrsm.core.Plugin',
58    debug: bool = False
59) -> Optional[int]:
60    """
61    Return a plugin's ID.
62    """
63    return self._rust_method('get_plugin_id')(plugin)

Return a plugin's ID.

def get_plugin_version( self, plugin: meerschaum.Plugin, debug: bool = False) -> str | None:
66def get_plugin_version(
67    self,
68    plugin: 'mrsm.core.Plugin',
69    debug: bool = False
70) -> Optional[str]:
71    """
72    Return a plugin's version.
73    """
74    return self._rust_method('get_plugin_version')(plugin)

Return a plugin's version.

def get_plugins( self, user_id: int | None = None, search_term: str | None = None, debug: bool = False, **kw: Any) -> List[str]:
107def get_plugins(
108    self,
109    user_id: Optional[int] = None,
110    search_term: Optional[str] = None,
111    debug: bool = False,
112    **kw: Any
113) -> List[str]:
114    """
115    Return a list of all registered plugins.
116
117    Parameters
118    ----------
119    user_id: Optional[int], default None
120        If specified, filter plugins by a specific `user_id`.
121
122    search_term: Optional[str], default None
123        If specified, add a `WHERE plugin_name LIKE '{search_term}%'` clause to filter the plugins.
124
125
126    Returns
127    -------
128    A list of plugin names.
129    """
130    return self._rust_method('get_plugins')(user_id=user_id, search_term=search_term)

Return a list of all registered plugins.

Parameters
  • user_id (Optional[int], default None): If specified, filter plugins by a specific user_id.
  • search_term (Optional[str], default None): If specified, add a WHERE plugin_name LIKE '{search_term}%' clause to filter the plugins.
Returns
  • A list of plugin names.
def get_plugin_user_id( self, plugin: meerschaum.Plugin, debug: bool = False) -> int | None:
76def get_plugin_user_id(
77    self,
78    plugin: 'mrsm.core.Plugin',
79    debug: bool = False
80) -> Optional[int]:
81    """
82    Return a plugin's user ID.
83    """
84    return self._rust_method('get_plugin_user_id')(plugin)

Return a plugin's user ID.

def get_plugin_username( self, plugin: meerschaum.Plugin, debug: bool = False) -> str | None:
86def get_plugin_username(
87    self,
88    plugin: 'mrsm.core.Plugin',
89    debug: bool = False
90) -> Optional[str]:
91    """
92    Return the username of a plugin's owner.
93    """
94    return self._rust_method('get_plugin_username')(plugin)

Return the username of a plugin's owner.

def get_plugin_attributes( self, plugin: meerschaum.Plugin, debug: bool = False) -> Dict[str, Any]:
 97def get_plugin_attributes(
 98    self,
 99    plugin: 'mrsm.core.Plugin',
100    debug: bool = False
101) -> Dict[str, Any]:
102    """
103    Return the attributes of a plugin.
104    """
105    return self._rust_method('get_plugin_attributes')(plugin)

Return the attributes of a plugin.

def get_users_pipe(self) -> meerschaum.Pipe:
16def get_users_pipe(self) -> mrsm.Pipe:
17    """
18    Return the internal metadata pipe for users management.
19    """
20    if '_users_pipe' in self.__dict__:
21        return self._users_pipe
22
23    cache_connector = self.__dict__.get('_cache_connector', None)
24    self._users_pipe = mrsm.Pipe(
25        'mrsm', 'users',
26        ### FIX (intentional v4 change): v4 left out `instance=self`, so the users pipe
27        ### (and `get_username()`, which reads it) was on the default instance.
28        instance=self,
29        temporary=True,
30        cache=True,
31        cache_connector_keys=cache_connector,
32        static=True,
33        null_indices=False,
34        enforce=False,
35        autoincrement=True,
36        columns={
37            'primary': 'user_id',
38        },
39        dtypes={
40            'user_id': 'int',
41            'username': 'string',
42            'attributes': 'json',
43            'user_type': 'string',
44        },
45        indices={
46            'unique': 'username',
47        },
48    )
49    return self._users_pipe

Return the internal metadata pipe for users management.

def register_user( self, user: meerschaum.core.User._User.User, debug: bool = False, **kw: Any) -> Tuple[bool, str]:
52def register_user(
53    self,
54    user: mrsm.core.User,
55    debug: bool = False,
56    **kw: Any
57) -> SuccessTuple:
58    """Register a new user."""
59    return self._rust_method('register_user')(user)

Register a new user.

def get_user_id( self, user: meerschaum.core.User._User.User, debug: bool = False) -> int | None:
106def get_user_id(
107    self,
108    user: 'mrsm.core.User',
109    debug: bool = False
110) -> Optional[int]:
111    """If a user is registered, return the `user_id`."""
112    return self._rust_method('get_user_id')(user)

If a user is registered, return the user_id.

def get_users(self, debug: bool = False, **kw: Any) -> List[str]:
133def get_users(
134    self,
135    debug: bool = False,
136    **kw: Any
137) -> List[str]:
138    """
139    Get the registered usernames.
140    """
141    return self._rust_method('get_users')()

Get the registered usernames.

def edit_user( self, user: meerschaum.core.User._User.User, debug: bool = False, **kw: Any) -> Tuple[bool, str]:
 96def edit_user(
 97    self,
 98    user: 'mrsm.core.User',
 99    debug: bool = False,
100    **kw: Any
101) -> SuccessTuple:
102    """Update an existing user's metadata."""
103    return self._rust_method('edit_user')(user)

Update an existing user's metadata.

def delete_user( self, user: meerschaum.core.User._User.User, debug: bool = False) -> Tuple[bool, str]:
124def delete_user(
125    self,
126    user: 'mrsm.core.User',
127    debug: bool = False
128) -> SuccessTuple:
129    """Delete a user's record from the users table."""
130    return self._rust_method('delete_user')(user)

Delete a user's record from the users table.

def get_user_password_hash( self, user: meerschaum.core.User._User.User, debug: bool = False, **kw: Any) -> str | None:
144def get_user_password_hash(
145    self,
146    user: 'mrsm.core.User',
147    debug: bool = False,
148    **kw: Any
149) -> Optional[str]:
150    """
151    Return the password has for a user.
152    **NOTE**: This may be dangerous and is only allowed if the security settings explicity allow it.
153    """
154    return self._rust_method('get_user_password_hash')(user)

Return the password has for a user. NOTE: This may be dangerous and is only allowed if the security settings explicity allow it.

def get_user_type( self, user: meerschaum.core.User._User.User, debug: bool = False, **kw: Any) -> str | None:
157def get_user_type(
158    self,
159    user: 'mrsm.core.User',
160    debug: bool = False,
161    **kw: Any
162) -> Optional[str]:
163    """
164    Return the user's type.
165    """
166    return self._rust_method('get_user_type')(user)

Return the user's type.

def get_user_attributes( self, user: meerschaum.core.User._User.User, debug: bool = False) -> Dict[str, Any] | None:
114def get_user_attributes(
115    self,
116    user: 'mrsm.core.User',
117    debug: bool = False
118) -> Union[Dict[str, Any], None]:
119    """
120    Return the user's attributes.
121    """
122    return self._rust_method('get_user_attributes')(user)

Return the user's attributes.

@classmethod
def from_uri( cls, uri: str, label: str | None = None, as_dict: bool = False) -> SQLConnector | Dict[str, str | int]:
17@classmethod
18def from_uri(
19    cls,
20    uri: str,
21    label: Optional[str] = None,
22    as_dict: bool = False,
23) -> Union[
24    'meerschaum.connectors.SQLConnector',
25    Dict[str, Union[str, int]],
26]:
27    """
28    Create a new SQLConnector from a URI string.
29
30    Parameters
31    ----------
32    uri: str
33        The URI connection string.
34
35    label: Optional[str], default None
36        If provided, use this as the connector label.
37        Otherwise use the determined database name.
38
39    as_dict: bool, default False
40        If `True`, return a dictionary of the keyword arguments
41        necessary to create a new `SQLConnector`, otherwise create a new object.
42
43    Returns
44    -------
45    A new SQLConnector object or a dictionary of attributes (if `as_dict` is `True`).
46    """
47
48    params = cls.parse_uri(uri)
49    params['uri'] = uri
50    flavor = params.get('flavor', None)
51    if not flavor or flavor not in cls.flavor_configs:
52        error(f"Invalid flavor '{flavor}' detected from the provided URI.")
53
54    if 'database' not in params:
55        error("Unable to determine the database from the provided URI.")
56
57    if flavor in ('sqlite', 'duckdb', 'geopackage'):
58        if params['database'] == ':memory:':
59            params['label'] = label or f'memory_{flavor}'
60        else:
61            params['label'] = label or params['database'].split(os.path.sep)[-1].lower()
62    else:
63        params['label'] = label or (
64            (
65                (params['username'] + '@' if 'username' in params else '')
66                + params.get('host', '')
67                + ('/' if 'host' in params else '')
68                + params.get('database', '')
69            ).lower()
70        )
71
72    return cls(**params) if not as_dict else params

Create a new SQLConnector from a URI string.

Parameters
  • uri (str): The URI connection string.
  • label (Optional[str], default None): If provided, use this as the connector label. Otherwise use the determined database name.
  • as_dict (bool, default False): If True, return a dictionary of the keyword arguments necessary to create a new SQLConnector, otherwise create a new object.
Returns
  • A new SQLConnector object or a dictionary of attributes (if as_dict is True).
@staticmethod
def parse_uri(uri: str) -> Dict[str, Any]:
 77@staticmethod
 78def parse_uri(uri: str) -> Dict[str, Any]:
 79    """
 80    Parse a URI string into a dictionary of parameters.
 81
 82    Parameters
 83    ----------
 84    uri: str
 85        The database connection URI.
 86
 87    Returns
 88    -------
 89    A dictionary of attributes.
 90
 91    Examples
 92    --------
 93    >>> parse_uri('sqlite:////home/foo/bar.db')
 94    {'database': '/home/foo/bar.db', 'flavor': 'sqlite'}
 95    >>> parse_uri(
 96    ...     'mssql+pyodbc://sa:supersecureSECRETPASSWORD123!@localhost:1439'
 97    ...     + '/master?driver=ODBC+Driver+17+for+SQL+Server'
 98    ... )
 99    {'host': 'localhost', 'database': 'master', 'username': 'sa',
100    'password': 'supersecureSECRETPASSWORD123!', 'port': 1439, 'flavor': 'mssql',
101    'driver': 'ODBC Driver 17 for SQL Server'}
102    >>> 
103    """
104    ### The Rust grammar is SQLAlchemy 2.0's (golden-tested) and its message is SQLAlchemy's:
105    ### a malformed URI raises `ValueError` rather than `sqlalchemy.exc.ArgumentError`
106    ### (see PARITY.md, H6).
107    from meerschaum import _core
108    return _core.parse_sql_uri(uri)

Parse a URI string into a dictionary of parameters.

Parameters
  • uri (str): The database connection URI.
Returns
  • A dictionary of attributes.
Examples
>>> parse_uri('sqlite:////home/foo/bar.db')
{'database': '/home/foo/bar.db', 'flavor': 'sqlite'}
>>> parse_uri(
...     'mssql+pyodbc://sa:supersecureSECRETPASSWORD123!@localhost:1439'
...     + '/master?driver=ODBC+Driver+17+for+SQL+Server'
... )
{'host': 'localhost', 'database': 'master', 'username': 'sa',
'password': 'supersecureSECRETPASSWORD123!', 'port': 1439, 'flavor': 'mssql',
'driver': 'ODBC Driver 17 for SQL Server'}
>>>
class DatabaseError(builtins.Exception):
 74class DatabaseError(Exception):
 75    """
 76    A database error from raw SQL through the Rust connector (PEP 249's `DatabaseError`).
 77
 78    Attributes: `statement` (the SQL that failed), `params` (its parameters), `sqlstate` (the
 79    SQLSTATE or the driver's error code, when the database reports one) and `orig` (`None`: there
 80    is no DBAPI exception underneath).
 81    """
 82
 83    def __init__(
 84        self,
 85        message: str = '',
 86        statement: Optional[str] = None,
 87        params: Any = None,
 88        sqlstate: Optional[str] = None,
 89    ):
 90        Exception.__init__(self, message)
 91        self.message = message
 92        self.statement = statement
 93        self.params = params
 94        self.sqlstate = sqlstate
 95        self.code = sqlstate
 96        self.orig = None
 97        self.detail = []
 98        self.hide_parameters = False
 99        self.connection_invalidated = False
100        self.ismulti = False
101
102    def __str__(self) -> str:
103        if self.statement:
104            return f"{self.message}\n[SQL: {self.statement}]"
105        return self.message
106
107    def __reduce__(self):
108        return (type(self), (self.message, self.statement, self.params, self.sqlstate))

A database error from raw SQL through the Rust connector (PEP 249's DatabaseError).

Attributes: statement (the SQL that failed), params (its parameters), sqlstate (the SQLSTATE or the driver's error code, when the database reports one) and orig (None: there is no DBAPI exception underneath).

DatabaseError( message: str = '', statement: str | None = None, params: Any = None, sqlstate: str | None = None)
 83    def __init__(
 84        self,
 85        message: str = '',
 86        statement: Optional[str] = None,
 87        params: Any = None,
 88        sqlstate: Optional[str] = None,
 89    ):
 90        Exception.__init__(self, message)
 91        self.message = message
 92        self.statement = statement
 93        self.params = params
 94        self.sqlstate = sqlstate
 95        self.code = sqlstate
 96        self.orig = None
 97        self.detail = []
 98        self.hide_parameters = False
 99        self.connection_invalidated = False
100        self.ismulti = False
message
statement
params
sqlstate
code
orig
detail
hide_parameters
connection_invalidated
ismulti
class InterfaceError(meerschaum.connectors.sql.DatabaseError):
111class InterfaceError(DatabaseError):
112    """PEP 249 `InterfaceError`."""

PEP 249 InterfaceError.

class OperationalError(meerschaum.connectors.sql.DatabaseError):
115class OperationalError(DatabaseError):
116    """PEP 249 `OperationalError`: a lost connection, a locked database, a missing SQLite table."""

PEP 249 OperationalError: a lost connection, a locked database, a missing SQLite table.

class ProgrammingError(meerschaum.connectors.sql.DatabaseError):
119class ProgrammingError(DatabaseError):
120    """PEP 249 `ProgrammingError`: a syntax error, a missing table or column."""

PEP 249 ProgrammingError: a syntax error, a missing table or column.

class IntegrityError(meerschaum.connectors.sql.DatabaseError):
123class IntegrityError(DatabaseError):
124    """PEP 249 `IntegrityError`: a violated unique, foreign key, not-null or check constraint."""

PEP 249 IntegrityError: a violated unique, foreign key, not-null or check constraint.

class DataError(meerschaum.connectors.sql.DatabaseError):
127class DataError(DatabaseError):
128    """PEP 249 `DataError`: a value out of range or of the wrong type."""

PEP 249 DataError: a value out of range or of the wrong type.

class InternalError(meerschaum.connectors.sql.DatabaseError):
131class InternalError(DatabaseError):
132    """PEP 249 `InternalError`."""

PEP 249 InternalError.

class NotSupportedError(meerschaum.connectors.sql.DatabaseError):
135class NotSupportedError(DatabaseError):
136    """PEP 249 `NotSupportedError`."""
class ResourceClosedError(builtins.Exception):
139class ResourceClosedError(Exception):
140    """A result of a statement that returns no rows was asked for rows (SQLAlchemy's error)."""
141
142    def __init__(self, message: str = (
143        "This result object does not return rows. It has been closed automatically."
144    )):
145        super().__init__(message)

A result of a statement that returns no rows was asked for rows (SQLAlchemy's error).

ResourceClosedError( message: str = 'This result object does not return rows. It has been closed automatically.')
142    def __init__(self, message: str = (
143        "This result object does not return rows. It has been closed automatically."
144    )):
145        super().__init__(message)
NATIVE_SQL_FLAVORS = frozenset({'mysql', 'oracle', 'cockroachdb', 'sqlite', 'geopackage', 'citus', 'postgresql', 'timescaledb', 'duckdb', 'timescaledb-ha', 'postgis', 'mariadb', 'mssql'})