meerschaum.connectors.valkey
Import the ValkeyConnector.
16@make_connector 17class ValkeyConnector(InstanceConnector): 18 """ 19 Manage a Valkey instance. 20 21 Build a `ValkeyConnector` from connection attributes or a URI string. 22 The commands are run by the Rust client (`meerschaum._core.ValkeyConnector`, one per 23 connector and process, connected by the first command). 24 """ 25 REQUIRED_ATTRIBUTES: List[str] = ['host'] 26 OPTIONAL_ATTRIBUTES: List[str] = [ 27 'port', 'username', 'password', 'db', 'socket_timeout', 28 ] 29 DEFAULT_ATTRIBUTES: Dict[str, Any] = { 30 'username': 'default', 31 'port': 6379, 32 'db': 0, 33 'socket_timeout': 300, 34 } 35 KEY_SEPARATOR: str = ':' 36 37 from ._pipes import ( 38 register_pipe, 39 get_pipe_id, 40 get_pipe_attributes, 41 edit_pipe, 42 pipe_exists, 43 drop_pipe, 44 delete_pipe, 45 get_pipe_data, 46 sync_pipe, 47 get_pipe_columns_types, 48 clear_pipe, 49 get_sync_time, 50 get_pipe_rowcount, 51 fetch_pipes_keys, 52 get_document_key, 53 get_table_quoted_doc_key, 54 ) 55 from ._fetch import ( 56 fetch, 57 ) 58 59 from ._users import ( 60 get_users_pipe, 61 get_user_key, 62 get_user_keys_vals, 63 register_user, 64 get_user_id, 65 edit_user, 66 get_user_attributes, 67 delete_user, 68 get_users, 69 get_user_password_hash, 70 get_user_type, 71 ) 72 from ._plugins import ( 73 get_plugins_pipe, 74 get_plugin_key, 75 get_plugin_keys_vals, 76 register_plugin, 77 get_plugin_id, 78 get_plugin_version, 79 get_plugin_user_id, 80 get_plugin_username, 81 get_plugin_attributes, 82 delete_plugin, 83 ) 84 85 def _rust_client(self): 86 """ 87 Return the `meerschaum._core.ValkeyConnector` of this connector (built once per process: 88 a forked child builds its own connection). It connects on the first command. 89 """ 90 import os 91 attributes = { 92 key: value 93 for key, value in self.__dict__.items() 94 if not str(key).startswith('_') 95 and isinstance(value, (str, int, float, bool)) 96 } 97 client = self.__dict__.get('_rust_client_obj', None) 98 if ( 99 client is not None 100 and self.__dict__.get('_rust_client_pid', None) == os.getpid() 101 and self.__dict__.get('_rust_client_attributes', None) == attributes 102 ): 103 return client 104 105 ### A new process, or credentials / address changed (`conn.password = ...`): build a client 106 ### with the current attributes (it logs in again; the native flows find it by them). 107 from meerschaum import _core 108 client = _core.ValkeyConnector(self.label, attributes) 109 self.__dict__['_rust_client_obj'] = client 110 self.__dict__['_rust_client_pid'] = os.getpid() 111 self.__dict__['_rust_client_attributes'] = attributes 112 return client 113 114 from meerschaum import _core 115 attributes = { 116 key: value 117 for key, value in self.__dict__.items() 118 if not str(key).startswith('_') 119 and isinstance(value, (str, int, float, bool)) 120 } 121 client = _core.ValkeyConnector(self.label, attributes) 122 self.__dict__['_rust_client_obj'] = client 123 self.__dict__['_rust_client_pid'] = os.getpid() 124 return client 125 126 def __getstate__(self): 127 state = self.__dict__.copy() 128 for key in ('_rust_client_obj', '_rust_client_pid', '_rust_client_attributes', '_client'): 129 state.pop(key, None) 130 return state 131 132 def __setstate__(self, state): 133 self.__dict__.update(state) 134 135 @property 136 def client(self): 137 """ 138 Return a client for raw commands (`get`, `set`, `keys`, `delete`, ...). 139 140 When the `valkey` package is installed (Meerschaum does not depend on it and never 141 installs it) this is a `valkey.Valkey` client; otherwise it is a small built-in client 142 over the Rust connector which supports the commands of `ValkeyClient`. 143 """ 144 if '_client' in self.__dict__: 145 return self.__dict__['_client'] 146 147 valkey = mrsm.attempt_import('valkey', install=False, warn=False, lazy=False) 148 if valkey is None: 149 from ._client import ValkeyClient 150 self._client = ValkeyClient(self) 151 return self._client 152 153 if 'uri' in self.__dict__: 154 ### `?protected=true` is Meerschaum's (`Connector.protected`), not the client's. 155 from meerschaum.connectors.sql._SQLConnector import _strip_uri_param 156 self._client = valkey.Valkey.from_url( 157 _strip_uri_param(self.__dict__.get('uri'), 'protected') 158 ) 159 return self._client 160 161 optional_kwargs = { 162 key: self.__dict__.get(key) 163 for key in self.OPTIONAL_ATTRIBUTES 164 if key in self.__dict__ 165 } 166 connection_kwargs = { 167 'host': self.host, 168 **optional_kwargs 169 } 170 171 self._client = valkey.Valkey(**connection_kwargs) 172 return self._client 173 174 @property 175 def URI(self) -> str: 176 """ 177 Return the connection URI for this connector. 178 """ 179 return self._rust_client().uri 180 181 def set(self, key: str, value: Any, **kwargs: Any) -> bool: 182 """ 183 Set the `key` to `value`. 184 `ex` sets an expiration in seconds; other keyword arguments (`px`, `nx`) go to `client`. 185 """ 186 if set(kwargs) <= {'ex'}: 187 return self._rust_client().set(key, value, **kwargs) 188 return self.client.set(key, value, **kwargs) 189 190 def get(self, key: str, decode: bool = True) -> Union[str, None]: 191 """ 192 Get the value for `key`. 193 """ 194 return self._rust_client().get(key, decode) 195 196 def test_connection(self) -> bool: 197 """ 198 Return whether a connection may be established. 199 """ 200 return self._rust_client().test_connection() 201 202 @classmethod 203 def quote_table(cls, table: str) -> str: 204 """ 205 Return a quoted key. 206 """ 207 from meerschaum import _core 208 return _core.ValkeyConnector.quote_table(table) 209 210 @classmethod 211 def get_counter_key(cls, table: str) -> str: 212 """ 213 Return the counter key for a given table. 214 """ 215 from meerschaum import _core 216 return _core.ValkeyConnector.get_counter_key(table) 217 218 def push_df( 219 self, 220 df: 'pd.DataFrame', 221 table: str, 222 datetime_column: Optional[str] = None, 223 debug: bool = False, 224 ) -> int: 225 """ 226 Append a pandas DataFrame to a table. 227 228 Parameters 229 ---------- 230 df: pd.DataFrame 231 The pandas DataFrame to append to the table. 232 233 table: str 234 The "table" name (root key). 235 236 datetime_column: Optional[str], default None 237 If provided, use this key as the datetime index. 238 239 Returns 240 ------- 241 The current index counter value (how many docs have been pushed). 242 """ 243 return self._rust_client().push_df(df, table, datetime_column) 244 245 def push_docs( 246 self, 247 docs: List[Dict[str, Any]], 248 table: str, 249 datetime_column: Optional[str] = None, 250 debug: bool = False, 251 ) -> int: 252 """ 253 Append a list of documents to a table. 254 255 Parameters 256 ---------- 257 docs: List[Dict[str, Any]] 258 The docs to be pushed. 259 All keys and values will be coerced into strings. 260 261 table: str 262 The "table" name (root key). 263 264 datetime_column: Optional[str], default None 265 If set, create a sorted set with this datetime column as the index. 266 Otherwise push the docs to a set. 267 268 Returns 269 ------- 270 The current index counter value (how many docs have been pushed). 271 """ 272 return self._rust_client().push_docs(docs, table, datetime_column) 273 274 def get_datetime_column_key(self, table: str) -> str: 275 """ 276 Return the key to store the datetime index for `table`. 277 """ 278 return self._rust_client().get_datetime_column_key(table) 279 280 def read( 281 self, 282 table: str, 283 begin: Union[datetime, int, str, None] = None, 284 end: Union[datetime, int, str, None] = None, 285 params: Optional[Dict[str, Any]] = None, 286 datetime_column: Optional[str] = None, 287 select_columns: Optional[List[str]] = None, 288 omit_columns: Optional[List[str]] = None, 289 debug: bool = False, 290 as_polars: Optional[bool] = None, 291 as_pandas: Optional[bool] = None, 292 ) -> Union['pd.DataFrame', None]: 293 """ 294 Query the table and return the result dataframe (of the `meerschaum:dataframe` library; 295 `as_polars=True` / `as_pandas=True` choose one). 296 297 Parameters 298 ---------- 299 table: str 300 The "table" name to be queried. 301 302 begin: Union[datetime, int, str, None], default None 303 If provided, only return rows greater than or equal to this datetime. 304 305 end: Union[datetime, int, str, None], default None 306 If provided, only return rows older than this datetime. 307 308 params: Optional[Dict[str, Any]] 309 Additional Meerschaum filter parameters. 310 311 datetime_column: Optional[str], default None 312 If provided, use this column for the datetime index. 313 Otherwise infer from the table metadata. 314 315 select_columns: Optional[List[str]], default None 316 If provided, only return these columns. 317 318 omit_columns: Optional[List[str]], default None 319 If provided, do not include these columns in the result. 320 321 Returns 322 ------- 323 A DataFrame of the result, or `None`. 324 """ 325 from meerschaum.utils.dataframe import frame_from_arrow, frame_library_of 326 df = self._rust_client().read( 327 table, 328 begin=begin, 329 end=end, 330 params=params, 331 datetime_column=datetime_column, 332 select_columns=select_columns, 333 omit_columns=omit_columns, 334 ) 335 if frame_library_of(df) is None: 336 return df 337 return frame_from_arrow(df, as_polars=as_polars, as_pandas=as_pandas) 338 339 def read_docs( 340 self, 341 table: str, 342 begin: Union[datetime, int, str, None] = None, 343 end: Union[datetime, int, str, None] = None, 344 debug: bool = False, 345 ) -> List[Dict[str, str]]: 346 """ 347 Return a list of previously pushed docs. 348 349 Parameters 350 ---------- 351 table: str 352 The "table" name (root key) from which to read docs. 353 354 begin: Union[datetime, int, str, None], default None 355 If provided and the table was created with a datetime index, only return documents 356 newer than this datetime. If the table was not created with a datetime index 357 and `begin` is an `int`, return documents with a positional index 358 greater than or equal to this value. 359 360 end: Union[datetime, int, str, None], default None 361 If provided and the table was created with a datetime index, only return documents 362 older than this datetime (inclusive, as `ZRANGEBYSCORE` is). 363 364 Returns 365 ------- 366 A list of dictionaries, one for each document. 367 """ 368 return self._rust_client().read_docs(table, begin=begin, end=end) 369 370 def drop_table(self, table: str, debug: bool = False) -> None: 371 """ 372 Delete a "table" (the root key and its datetime column key). 373 """ 374 return self._rust_client().drop_table(table) 375 376 @classmethod 377 def get_entity_key(cls, *keys: Any) -> str: 378 """ 379 Join the keys with the key separator (`:`). 380 A key may not contain the separator. 381 """ 382 from meerschaum import _core 383 return _core.ValkeyConnector.get_entity_key(*keys)
Manage a Valkey instance.
Build a ValkeyConnector from connection attributes or a URI string.
The commands are run by the Rust client (meerschaum._core.ValkeyConnector, one per
connector and process, connected by the first command).
135 @property 136 def client(self): 137 """ 138 Return a client for raw commands (`get`, `set`, `keys`, `delete`, ...). 139 140 When the `valkey` package is installed (Meerschaum does not depend on it and never 141 installs it) this is a `valkey.Valkey` client; otherwise it is a small built-in client 142 over the Rust connector which supports the commands of `ValkeyClient`. 143 """ 144 if '_client' in self.__dict__: 145 return self.__dict__['_client'] 146 147 valkey = mrsm.attempt_import('valkey', install=False, warn=False, lazy=False) 148 if valkey is None: 149 from ._client import ValkeyClient 150 self._client = ValkeyClient(self) 151 return self._client 152 153 if 'uri' in self.__dict__: 154 ### `?protected=true` is Meerschaum's (`Connector.protected`), not the client's. 155 from meerschaum.connectors.sql._SQLConnector import _strip_uri_param 156 self._client = valkey.Valkey.from_url( 157 _strip_uri_param(self.__dict__.get('uri'), 'protected') 158 ) 159 return self._client 160 161 optional_kwargs = { 162 key: self.__dict__.get(key) 163 for key in self.OPTIONAL_ATTRIBUTES 164 if key in self.__dict__ 165 } 166 connection_kwargs = { 167 'host': self.host, 168 **optional_kwargs 169 } 170 171 self._client = valkey.Valkey(**connection_kwargs) 172 return self._client
174 @property 175 def URI(self) -> str: 176 """ 177 Return the connection URI for this connector. 178 """ 179 return self._rust_client().uri
Return the connection URI for this connector.
181 def set(self, key: str, value: Any, **kwargs: Any) -> bool: 182 """ 183 Set the `key` to `value`. 184 `ex` sets an expiration in seconds; other keyword arguments (`px`, `nx`) go to `client`. 185 """ 186 if set(kwargs) <= {'ex'}: 187 return self._rust_client().set(key, value, **kwargs) 188 return self.client.set(key, value, **kwargs)
Set the key to value.
ex sets an expiration in seconds; other keyword arguments (px, nx) go to client.
190 def get(self, key: str, decode: bool = True) -> Union[str, None]: 191 """ 192 Get the value for `key`. 193 """ 194 return self._rust_client().get(key, decode)
Get the value for key.
196 def test_connection(self) -> bool: 197 """ 198 Return whether a connection may be established. 199 """ 200 return self._rust_client().test_connection()
Return whether a connection may be established.
202 @classmethod 203 def quote_table(cls, table: str) -> str: 204 """ 205 Return a quoted key. 206 """ 207 from meerschaum import _core 208 return _core.ValkeyConnector.quote_table(table)
Return a quoted key.
210 @classmethod 211 def get_counter_key(cls, table: str) -> str: 212 """ 213 Return the counter key for a given table. 214 """ 215 from meerschaum import _core 216 return _core.ValkeyConnector.get_counter_key(table)
Return the counter key for a given table.
218 def push_df( 219 self, 220 df: 'pd.DataFrame', 221 table: str, 222 datetime_column: Optional[str] = None, 223 debug: bool = False, 224 ) -> int: 225 """ 226 Append a pandas DataFrame to a table. 227 228 Parameters 229 ---------- 230 df: pd.DataFrame 231 The pandas DataFrame to append to the table. 232 233 table: str 234 The "table" name (root key). 235 236 datetime_column: Optional[str], default None 237 If provided, use this key as the datetime index. 238 239 Returns 240 ------- 241 The current index counter value (how many docs have been pushed). 242 """ 243 return self._rust_client().push_df(df, table, datetime_column)
Append a pandas DataFrame to a table.
Parameters
- df (pd.DataFrame): The pandas DataFrame to append to the table.
- table (str): The "table" name (root key).
- datetime_column (Optional[str], default None): If provided, use this key as the datetime index.
Returns
- The current index counter value (how many docs have been pushed).
245 def push_docs( 246 self, 247 docs: List[Dict[str, Any]], 248 table: str, 249 datetime_column: Optional[str] = None, 250 debug: bool = False, 251 ) -> int: 252 """ 253 Append a list of documents to a table. 254 255 Parameters 256 ---------- 257 docs: List[Dict[str, Any]] 258 The docs to be pushed. 259 All keys and values will be coerced into strings. 260 261 table: str 262 The "table" name (root key). 263 264 datetime_column: Optional[str], default None 265 If set, create a sorted set with this datetime column as the index. 266 Otherwise push the docs to a set. 267 268 Returns 269 ------- 270 The current index counter value (how many docs have been pushed). 271 """ 272 return self._rust_client().push_docs(docs, table, datetime_column)
Append a list of documents to a table.
Parameters
- docs (List[Dict[str, Any]]): The docs to be pushed. All keys and values will be coerced into strings.
- table (str): The "table" name (root key).
- datetime_column (Optional[str], default None): If set, create a sorted set with this datetime column as the index. Otherwise push the docs to a set.
Returns
- The current index counter value (how many docs have been pushed).
274 def get_datetime_column_key(self, table: str) -> str: 275 """ 276 Return the key to store the datetime index for `table`. 277 """ 278 return self._rust_client().get_datetime_column_key(table)
Return the key to store the datetime index for table.
280 def read( 281 self, 282 table: str, 283 begin: Union[datetime, int, str, None] = None, 284 end: Union[datetime, int, str, None] = None, 285 params: Optional[Dict[str, Any]] = None, 286 datetime_column: Optional[str] = None, 287 select_columns: Optional[List[str]] = None, 288 omit_columns: Optional[List[str]] = None, 289 debug: bool = False, 290 as_polars: Optional[bool] = None, 291 as_pandas: Optional[bool] = None, 292 ) -> Union['pd.DataFrame', None]: 293 """ 294 Query the table and return the result dataframe (of the `meerschaum:dataframe` library; 295 `as_polars=True` / `as_pandas=True` choose one). 296 297 Parameters 298 ---------- 299 table: str 300 The "table" name to be queried. 301 302 begin: Union[datetime, int, str, None], default None 303 If provided, only return rows greater than or equal to this datetime. 304 305 end: Union[datetime, int, str, None], default None 306 If provided, only return rows older than this datetime. 307 308 params: Optional[Dict[str, Any]] 309 Additional Meerschaum filter parameters. 310 311 datetime_column: Optional[str], default None 312 If provided, use this column for the datetime index. 313 Otherwise infer from the table metadata. 314 315 select_columns: Optional[List[str]], default None 316 If provided, only return these columns. 317 318 omit_columns: Optional[List[str]], default None 319 If provided, do not include these columns in the result. 320 321 Returns 322 ------- 323 A DataFrame of the result, or `None`. 324 """ 325 from meerschaum.utils.dataframe import frame_from_arrow, frame_library_of 326 df = self._rust_client().read( 327 table, 328 begin=begin, 329 end=end, 330 params=params, 331 datetime_column=datetime_column, 332 select_columns=select_columns, 333 omit_columns=omit_columns, 334 ) 335 if frame_library_of(df) is None: 336 return df 337 return frame_from_arrow(df, as_polars=as_polars, as_pandas=as_pandas)
Query the table and return the result dataframe (of the meerschaum:dataframe library;
as_polars=True / as_pandas=True choose one).
Parameters
- table (str): The "table" name to be queried.
- begin (Union[datetime, int, str, None], default None): If provided, only return rows greater than or equal to this datetime.
- end (Union[datetime, int, str, None], default None): If provided, only return rows older than this datetime.
- params (Optional[Dict[str, Any]]): Additional Meerschaum filter parameters.
- datetime_column (Optional[str], default None): If provided, use this column for the datetime index. Otherwise infer from the table metadata.
- select_columns (Optional[List[str]], default None): If provided, only return these columns.
- omit_columns (Optional[List[str]], default None): If provided, do not include these columns in the result.
Returns
- A DataFrame of the result, or
None.
339 def read_docs( 340 self, 341 table: str, 342 begin: Union[datetime, int, str, None] = None, 343 end: Union[datetime, int, str, None] = None, 344 debug: bool = False, 345 ) -> List[Dict[str, str]]: 346 """ 347 Return a list of previously pushed docs. 348 349 Parameters 350 ---------- 351 table: str 352 The "table" name (root key) from which to read docs. 353 354 begin: Union[datetime, int, str, None], default None 355 If provided and the table was created with a datetime index, only return documents 356 newer than this datetime. If the table was not created with a datetime index 357 and `begin` is an `int`, return documents with a positional index 358 greater than or equal to this value. 359 360 end: Union[datetime, int, str, None], default None 361 If provided and the table was created with a datetime index, only return documents 362 older than this datetime (inclusive, as `ZRANGEBYSCORE` is). 363 364 Returns 365 ------- 366 A list of dictionaries, one for each document. 367 """ 368 return self._rust_client().read_docs(table, begin=begin, end=end)
Return a list of previously pushed docs.
Parameters
- table (str): The "table" name (root key) from which to read docs.
- begin (Union[datetime, int, str, None], default None):
If provided and the table was created with a datetime index, only return documents
newer than this datetime. If the table was not created with a datetime index
and
beginis anint, return documents with a positional index greater than or equal to this value. - end (Union[datetime, int, str, None], default None):
If provided and the table was created with a datetime index, only return documents
older than this datetime (inclusive, as
ZRANGEBYSCOREis).
Returns
- A list of dictionaries, one for each document.
370 def drop_table(self, table: str, debug: bool = False) -> None: 371 """ 372 Delete a "table" (the root key and its datetime column key). 373 """ 374 return self._rust_client().drop_table(table)
Delete a "table" (the root key and its datetime column key).
376 @classmethod 377 def get_entity_key(cls, *keys: Any) -> str: 378 """ 379 Join the keys with the key separator (`:`). 380 A key may not contain the separator. 381 """ 382 from meerschaum import _core 383 return _core.ValkeyConnector.get_entity_key(*keys)
Join the keys with the key separator (:).
A key may not contain the separator.
110def register_pipe( 111 self, 112 pipe: mrsm.Pipe, 113 debug: bool = False, 114 **kwargs: Any 115) -> SuccessTuple: 116 """ 117 Register a pipe's parameters and assign it an ID. 118 """ 119 return self._rust_client().register_pipe(pipe)
Register a pipe's parameters and assign it an ID.
122def get_pipe_id( 123 self, 124 pipe: mrsm.Pipe, 125 debug: bool = False, 126 **kwargs: Any 127) -> Union[str, int, None]: 128 """ 129 Return the pipe's ID. 130 """ 131 return self._rust_client().get_pipe_id(pipe)
Return the pipe's ID.
134def get_pipe_attributes( 135 self, 136 pipe: mrsm.Pipe, 137 debug: bool = False, 138 **kwargs: Any 139) -> Dict[str, Any]: 140 """ 141 Return the pipe's document from the pipes table. 142 """ 143 return self._rust_client().get_pipe_attributes(pipe)
Return the pipe's document from the pipes table.
146def edit_pipe( 147 self, 148 pipe: mrsm.Pipe, 149 debug: bool = False, 150 **kwargs: Any 151) -> mrsm.SuccessTuple: 152 """ 153 Edit the attributes of the pipe. 154 """ 155 return self._rust_client().edit_pipe(pipe)
Edit the attributes of the pipe.
158def pipe_exists( 159 self, 160 pipe: mrsm.Pipe, 161 debug: bool = False, 162 **kwargs: Any 163) -> bool: 164 """ 165 Check whether a pipe's target table exists. 166 """ 167 return self._rust_client().pipe_exists(pipe)
Check whether a pipe's target table exists.
170def drop_pipe( 171 self, 172 pipe: mrsm.Pipe, 173 debug: bool = False, 174 **kwargs: Any 175) -> mrsm.SuccessTuple: 176 """ 177 Drop a pipe's collection but maintain its registration. 178 """ 179 return self._rust_client().drop_pipe(pipe)
Drop a pipe's collection but maintain its registration.
182def delete_pipe( 183 self, 184 pipe: mrsm.Pipe, 185 debug: bool = False, 186 **kwargs: Any 187) -> mrsm.SuccessTuple: 188 """ 189 Delete a pipe's registration from the `mrsm_pipes` collection. 190 """ 191 return self._rust_client().delete_pipe(pipe)
Delete a pipe's registration from the mrsm_pipes collection.
194def get_pipe_data( 195 self, 196 pipe: mrsm.Pipe, 197 select_columns: Optional[List[str]] = None, 198 omit_columns: Optional[List[str]] = None, 199 begin: Union[datetime, int, None] = None, 200 end: Union[datetime, int, None] = None, 201 params: Optional[Dict[str, Any]] = None, 202 debug: bool = False, 203 as_polars: Optional[bool] = None, 204 as_pandas: Optional[bool] = None, 205 **kwargs: Any 206) -> Union['pd.DataFrame', None]: 207 """ 208 Query a pipe's target table and return the DataFrame (of the `meerschaum:dataframe` library; 209 `as_polars=True` / `as_pandas=True` choose one). 210 211 Parameters 212 ---------- 213 pipe: mrsm.Pipe 214 The pipe with the target table from which to read. 215 216 select_columns: Optional[List[str]], default None 217 If provided, only select these given columns. 218 219 omit_columns: Optional[List[str]], default None 220 If provided, remove these columns from the selection. 221 222 begin: Union[datetime, int, None], default None 223 The earliest `datetime` value to search from (inclusive). 224 225 end: Union[datetime, int, None], default None 226 The lastest `datetime` value to search from (inclusive: `ZRANGEBYSCORE` is). 227 228 params: Optional[Dict[str, Any]], default None 229 Additional filters to apply to the query. 230 231 Returns 232 ------- 233 The target table's data as a DataFrame, or `None` if the table does not exist. 234 """ 235 from meerschaum.utils.dataframe import frame_from_arrow, frame_library_of 236 df = self._rust_client().get_pipe_data( 237 pipe, 238 select_columns=select_columns, 239 omit_columns=omit_columns, 240 begin=begin, 241 end=end, 242 params=params, 243 ) 244 if frame_library_of(df) is None: 245 return df 246 return frame_from_arrow(df, as_polars=as_polars, as_pandas=as_pandas)
Query a pipe's target table and return the DataFrame (of the meerschaum:dataframe library;
as_polars=True / as_pandas=True choose one).
Parameters
- pipe (mrsm.Pipe): The pipe with the target table from which to read.
- select_columns (Optional[List[str]], default None): If provided, only select these given columns.
- omit_columns (Optional[List[str]], default None): If provided, remove these columns from the selection.
- begin (Union[datetime, int, None], default None):
The earliest
datetimevalue to search from (inclusive). - end (Union[datetime, int, None], default None):
The lastest
datetimevalue to search from (inclusive:ZRANGEBYSCOREis). - params (Optional[Dict[str, Any]], default None): Additional filters to apply to the query.
Returns
- The target table's data as a DataFrame, or
Noneif the table does not exist.
249def sync_pipe( 250 self, 251 pipe: mrsm.Pipe, 252 df: 'pd.DataFrame' = None, 253 check_existing: bool = True, 254 debug: bool = False, 255 **kwargs: Any 256) -> mrsm.SuccessTuple: 257 """ 258 Add new documents to the pipe's target table. 259 260 Parameters 261 ---------- 262 pipe: mrsm.Pipe 263 The pipe whose target table to receive the new documents. 264 265 df: 'pd.DataFrame', default None 266 The data to be synced. 267 268 check_existing: bool, default True 269 If `False`, do not check the documents against existing data and instead insert directly. 270 271 kwargs: Any 272 `replace=True` clears the pipe's documents of `[begin, end)` (matching `params`), then 273 writes the rows of `df` (a bound that is not given is the rows' own datetime range). 274 275 Returns 276 ------- 277 A `SuccessTuple` indicating success. 278 """ 279 replace_kw = ( 280 { 281 'replace': True, 282 'begin': kwargs.get('begin', None), 283 'end': kwargs.get('end', None), 284 'params': kwargs.get('params', None), 285 } 286 if kwargs.get('replace', False) 287 else {} 288 ) 289 return self._rust_client().sync_pipe(pipe, df, check_existing=check_existing, **replace_kw)
Add new documents to the pipe's target table.
Parameters
- pipe (mrsm.Pipe): The pipe whose target table to receive the new documents.
- df ('pd.DataFrame', default None): The data to be synced.
- check_existing (bool, default True):
If
False, do not check the documents against existing data and instead insert directly. - kwargs (Any):
replace=Trueclears the pipe's documents of[begin, end)(matchingparams), then writes the rows ofdf(a bound that is not given is the rows' own datetime range).
Returns
- A
SuccessTupleindicating success.
292def get_pipe_columns_types( 293 self, 294 pipe: mrsm.Pipe, 295 debug: bool = False, 296 **kwargs: Any 297) -> Dict[str, str]: 298 """ 299 Return the data types for the columns in the target table for data type enforcement. 300 301 Parameters 302 ---------- 303 pipe: mrsm.Pipe 304 The pipe whose target table contains columns and data types. 305 306 Returns 307 ------- 308 A dictionary mapping columns to data types. 309 """ 310 return self._rust_client().get_pipe_columns_types(pipe)
Return the data types for the columns in the target table for data type enforcement.
Parameters
- pipe (mrsm.Pipe): The pipe whose target table contains columns and data types.
Returns
- A dictionary mapping columns to data types.
313def clear_pipe( 314 self, 315 pipe: mrsm.Pipe, 316 begin: Union[datetime, int, None] = None, 317 end: Union[datetime, int, None] = None, 318 params: Optional[Dict[str, Any]] = None, 319 debug: bool = False, 320) -> mrsm.SuccessTuple: 321 """ 322 Delete rows within `begin`, `end`, and `params`. 323 324 Parameters 325 ---------- 326 pipe: mrsm.Pipe 327 The pipe whose rows to clear. 328 329 begin: Union[datetime, int, None], default None 330 If provided, remove rows >= `begin`. 331 332 end: Union[datetime, int, None], default None 333 If provided, remove rows < `end`. 334 335 params: Optional[Dict[str, Any]], default None 336 If provided, only remove rows which match the `params` filter. 337 338 Returns 339 ------- 340 A `SuccessTuple` indicating success. 341 """ 342 return self._rust_client().clear_pipe(pipe, begin=begin, end=end, params=params)
Delete rows within begin, end, and params.
Parameters
- pipe (mrsm.Pipe): The pipe whose rows to clear.
- begin (Union[datetime, int, None], default None):
If provided, remove rows >=
begin. - end (Union[datetime, int, None], default None):
If provided, remove rows <
end. - params (Optional[Dict[str, Any]], default None):
If provided, only remove rows which match the
paramsfilter.
Returns
- A
SuccessTupleindicating success.
345def get_sync_time( 346 self, 347 pipe: mrsm.Pipe, 348 newest: bool = True, 349 **kwargs: Any 350) -> Union[datetime, int, None]: 351 """ 352 Return the most recent datetime value in the pipe's target table 353 (`params` is not supported by Valkey instances). 354 355 Parameters 356 ---------- 357 pipe: mrsm.Pipe 358 The pipe whose target table contains the datetime column. 359 360 newest: bool, default True 361 If `True`, get the newest value, otherwise the oldest. 362 363 Returns 364 ------- 365 A `datetime` or `int`, if the pipe exists, otherwise `None`. 366 """ 367 return self._rust_client().get_sync_time(pipe, newest)
Return the most recent datetime value in the pipe's target table
(params is not supported by Valkey instances).
Parameters
- pipe (mrsm.Pipe): The pipe whose target table contains the datetime column.
- newest (bool, default True):
If
True, get the newest value, otherwise the oldest.
Returns
- A
datetimeorint, if the pipe exists, otherwiseNone.
370def get_pipe_rowcount( 371 self, 372 pipe: mrsm.Pipe, 373 begin: Union[datetime, int, None] = None, 374 end: Union[datetime, int, None] = None, 375 params: Optional[Dict[str, Any]] = None, 376 debug: bool = False, 377 **kwargs: Any 378) -> Union[int, None]: 379 """ 380 Return the number of documents in the pipe's set. 381 382 Parameters 383 ---------- 384 pipe: mrsm.Pipe 385 The pipe whose target table to count. 386 387 begin: Union[datetime, int, None], default None 388 If provided, only count rows >= `begin`. 389 390 end: Union[datetime, int, None], default None 391 If provided, only count rows < `end`. 392 393 params: Optional[Dict[str, Any]], default None 394 If provided, only count rows which match the `params` filter. 395 396 Returns 397 ------- 398 The number of matching documents, or `None` if the pipe does not exist. 399 """ 400 return self._rust_client().get_pipe_rowcount(pipe, begin=begin, end=end, params=params)
Return the number of documents in the pipe's set.
Parameters
- pipe (mrsm.Pipe): The pipe whose target table to count.
- begin (Union[datetime, int, None], default None):
If provided, only count rows >=
begin. - end (Union[datetime, int, None], default None):
If provided, only count rows <
end. - params (Optional[Dict[str, Any]], default None):
If provided, only count rows which match the
paramsfilter.
Returns
- The number of matching documents, or
Noneif the pipe does not exist.
403def fetch_pipes_keys( 404 self, 405 connector_keys: Optional[List[str]] = None, 406 metric_keys: Optional[List[str]] = None, 407 location_keys: Optional[List[str]] = None, 408 tags: Optional[List[str]] = None, 409 params: Optional[Dict[str, Any]] = None, 410 debug: bool = False 411) -> List[Tuple[str, str, Union[str, None], Dict[str, Any]]]: 412 """ 413 Return the keys (and parameters) of the registered pipes which match the filters. 414 415 Parameters 416 ---------- 417 connector_keys: Optional[List[str]], default None 418 The connector keys (`_` negates). 419 420 metric_keys: Optional[List[str]], default None 421 The metric keys. 422 423 location_keys: Optional[List[str]], default None 424 The location keys (`None` matches a pipe without a location). 425 426 tags: Optional[List[str]], default None 427 The tags (comma-separated groups are ANDed, groups are ORed). 428 429 params: Optional[Dict[str, Any]], default None 430 Additional filters against the pipes' parameters. 431 432 Returns 433 ------- 434 A list of tuples of `(connector_keys, metric_key, location_key, parameters)`. 435 """ 436 return self._rust_client().fetch_pipes_keys( 437 connector_keys, 438 metric_keys, 439 location_keys, 440 tags, 441 params, 442 )
Return the keys (and parameters) of the registered pipes which match the filters.
Parameters
- connector_keys (Optional[List[str]], default None):
The connector keys (
_negates). - metric_keys (Optional[List[str]], default None): The metric keys.
- location_keys (Optional[List[str]], default None):
The location keys (
Nonematches a pipe without a location). - tags (Optional[List[str]], default None): The tags (comma-separated groups are ANDed, groups are ORed).
- params (Optional[Dict[str, Any]], default None): Additional filters against the pipes' parameters.
Returns
- A list of tuples of
(connector_keys, metric_key, location_key, parameters).
55@staticmethod 56def get_document_key( 57 doc: Dict[str, Any], 58 indices: List[str], 59 table_name: Optional[str] = None, 60) -> str: 61 """ 62 Return a serialized string for a document's indices only. 63 64 Parameters 65 ---------- 66 doc: Dict[str, Any] 67 The document containing index values to be serialized. 68 69 indices: List[str] 70 The name of the indices to be serialized. 71 72 table_name: Optional[str], default None 73 If provided, prepend the table to the key. 74 75 Returns 76 ------- 77 A serialized string of the document's indices. 78 """ 79 from meerschaum import _core 80 return _core.ValkeyConnector.get_document_key(doc, indices, table_name)
Return a serialized string for a document's indices only.
Parameters
- doc (Dict[str, Any]): The document containing index values to be serialized.
- indices (List[str]): The name of the indices to be serialized.
- table_name (Optional[str], default None): If provided, prepend the table to the key.
Returns
- A serialized string of the document's indices.
83@classmethod 84def get_table_quoted_doc_key( 85 cls, 86 table_name: str, 87 doc: Dict[str, Any], 88 indices: List[str], 89 datetime_column: Optional[str] = None, 90) -> str: 91 """ 92 Return the document string as stored in the underling set. 93 """ 94 from meerschaum.utils.dtypes import json_serialize_value 95 return json.dumps( 96 { 97 cls.get_document_key(doc, indices, table_name): serialize_document(doc), 98 **( 99 {datetime_column: doc.get(datetime_column, 0)} 100 if datetime_column 101 else {} 102 ) 103 }, 104 sort_keys=True, 105 separators=(',', ':'), 106 default=json_serialize_value, 107 )
Return the document string as stored in the underling set.
15def fetch( 16 self, 17 pipe: mrsm.Pipe, 18 begin: Union[datetime, int, None] = None, 19 end: Union[datetime, int, None] = None, 20 params: Optional[Dict[str, Any]] = None, 21 debug: bool = False, 22 **kwargs: Any 23) -> List[Dict[str, Any]]: 24 """ 25 Return the documents of the source key `parameters['valkey']['key']` 26 (a set's members, a sorted set's members within `begin` and `end`, or `{key: value}`). 27 """ 28 return self._rust_client().fetch(pipe, begin=begin, end=end, params=params)
Return the documents of the source key parameters['valkey']['key']
(a set's members, a sorted set's members within begin and end, or {key: value}).
18def get_users_pipe(self): 19 """ 20 Return the pipe which stores the registered users. 21 """ 22 return mrsm.Pipe( 23 'mrsm', 'users', 24 columns=['user_id'], 25 temporary=True, 26 target=USERS_TABLE, 27 instance=self, 28 )
Return the pipe which stores the registered users.
31@classmethod 32def get_user_key(cls, user_id_or_username: str, sub_key: str, by_username: bool = False) -> str: 33 """ 34 Return the key to store metadata about a user. 35 36 Parameters 37 ---------- 38 user_id_or_username: str 39 The user ID or username of the given user. 40 If `by_username` is `True`, then provide the username. 41 42 sub_key: str 43 The key suffix, e.g. `'attributes'`. 44 45 by_username: bool, default False 46 If `True`, then treat `user_id_or_username` as a username. 47 48 Returns 49 ------- 50 A key to store information about a user. 51 52 Examples 53 -------- 54 >>> get_user_key('deadbeef', 'attributes') 55 'mrsm_user:user_id:deadbeef:attributes' 56 >>> get_user_key('foo', 'user_id', by_username=True) 57 'mrsm_user:username:foo:user_id' 58 """ 59 from meerschaum import _core 60 return _core.ValkeyConnector.get_user_key(user_id_or_username, sub_key, by_username)
Return the key to store metadata about a user.
Parameters
- user_id_or_username (str):
The user ID or username of the given user.
If
by_usernameisTrue, then provide the username. - sub_key (str):
The key suffix, e.g.
'attributes'. - by_username (bool, default False):
If
True, then treatuser_id_or_usernameas a username.
Returns
- A key to store information about a user.
Examples
>>> get_user_key('deadbeef', 'attributes')
'mrsm_user:user_id:deadbeef:attributes'
>>> get_user_key('foo', 'user_id', by_username=True)
'mrsm_user:username:foo:user_id'
63@classmethod 64def get_user_keys_vals( 65 cls, 66 user: 'mrsm.core.User', 67 mutable_only: bool = False, 68) -> Dict[str, str]: 69 """ 70 Return a dictionary containing keys and values to set for the user. 71 72 Parameters 73 ---------- 74 user: mrsm.core.User 75 The user for which to generate the keys. 76 77 mutable_only: bool, default False 78 If `True`, only return keys which may be edited. 79 80 Returns 81 ------- 82 A dictionary mapping a user's keys to values. 83 """ 84 from meerschaum import _core 85 return _core.ValkeyConnector.get_user_keys_vals( 86 user, 87 user.password_hash, 88 mutable_only, 89 )
Return a dictionary containing keys and values to set for the user.
Parameters
- user (mrsm.core.User): The user for which to generate the keys.
- mutable_only (bool, default False):
If
True, only return keys which may be edited.
Returns
- A dictionary mapping a user's keys to values.
92def register_user( 93 self, 94 user: 'mrsm.core.User', 95 debug: bool = False, 96 **kwargs: Any 97) -> SuccessTuple: 98 """ 99 Register a new user (a new 12-character `user_id` is set on `user`). 100 """ 101 return self._rust_client().register_user(user)
Register a new user (a new 12-character user_id is set on user).
104def get_user_id( 105 self, 106 user: 'mrsm.core.User', 107 debug: bool = False 108) -> Union[str, None]: 109 """ 110 Return the user ID for a username (`None` if it is not registered). 111 A read that fails raises `ConnectionError`. 112 """ 113 return self._rust_client().get_user_id(user)
Return the user ID for a username (None if it is not registered).
A read that fails raises ConnectionError.
116def edit_user( 117 self, 118 user: 'mrsm.core.User', 119 debug: bool = False, 120 **kw: Any 121) -> SuccessTuple: 122 """ 123 Update a user's mutable attributes. 124 """ 125 return self._rust_client().edit_user(user)
Update a user's mutable attributes.
128def get_user_attributes( 129 self, 130 user: 'mrsm.core.User', 131 debug: bool = False 132) -> Union[Dict[str, Any], None]: 133 """ 134 Return the user's attributes (`None` if there are none). 135 A read that fails raises `ConnectionError`: it never reads as "no attributes", 136 which grants every scope. 137 """ 138 return self._rust_client().get_user_attributes(user)
Return the user's attributes (None if there are none).
A read that fails raises ConnectionError: it never reads as "no attributes",
which grants every scope.
141def delete_user( 142 self, 143 user: 'mrsm.core.User', 144 debug: bool = False 145) -> SuccessTuple: 146 """ 147 Delete a user's keys and its row in the users pipe. 148 """ 149 return self._rust_client().delete_user(user)
Delete a user's keys and its row in the users pipe.
152def get_users( 153 self, 154 debug: bool = False, 155 **kw: Any 156) -> List[str]: 157 """ 158 Get the registered usernames. 159 """ 160 return self._rust_client().get_users()
Get the registered usernames.
163def get_user_password_hash( 164 self, 165 user: 'mrsm.core.User', 166 debug: bool = False, 167 **kw: Any 168) -> Union[str, None]: 169 """ 170 Return the password hash for a user (`None` if there is none). 171 A read that fails raises `ConnectionError`. 172 """ 173 return self._rust_client().get_user_password_hash(user)
Return the password hash for a user (None if there is none).
A read that fails raises ConnectionError.
176def get_user_type( 177 self, 178 user: 'mrsm.core.User', 179 debug: bool = False, 180 **kw: Any 181) -> Union[str, None]: 182 """ 183 Return the user's type (`None` if there is none). 184 A read that fails raises `ConnectionError`. 185 """ 186 return self._rust_client().get_user_type(user)
Return the user's type (None if there is none).
A read that fails raises ConnectionError.
18def get_plugins_pipe(self) -> mrsm.Pipe: 19 """ 20 Return the pipe to store the plugins. 21 """ 22 return mrsm.Pipe( 23 'mrsm', 'plugins', 24 columns=['plugin_name'], 25 temporary=True, 26 target=PLUGINS_TABLE, 27 instance=self, 28 )
Return the pipe to store the plugins.
31@classmethod 32def get_plugin_key(cls, plugin_name: str, sub_key: str) -> str: 33 """ 34 Return the key for a plugin's attribute. 35 """ 36 from meerschaum import _core 37 return _core.ValkeyConnector.get_plugin_key(plugin_name, sub_key)
Return the key for a plugin's attribute.
40@classmethod 41def get_plugin_keys_vals( 42 cls, 43 plugin: 'mrsm.core.Plugin', 44 mutable_only: bool = False, 45) -> Dict[str, str]: 46 """ 47 Return a dictionary containing keys and values to set for the plugin. 48 49 Parameters 50 ---------- 51 plugin: mrsm.core.Plugin 52 The plugin for which to generate the keys. 53 54 mutable_only: bool, default False 55 If `True`, only return keys which may be edited. 56 57 Returns 58 ------- 59 A dictionary mapping a plugins's keys to values. 60 """ 61 from meerschaum import _core 62 return _core.ValkeyConnector.get_plugin_keys_vals(plugin, mutable_only)
Return a dictionary containing keys and values to set for the plugin.
Parameters
- plugin (mrsm.core.Plugin): The plugin for which to generate the keys.
- mutable_only (bool, default False):
If
True, only return keys which may be edited.
Returns
- A dictionary mapping a plugins's keys to values.
65def register_plugin( 66 self, 67 plugin: 'mrsm.core.Plugin', 68 force: bool = False, 69 debug: bool = False, 70 **kw: Any 71) -> SuccessTuple: 72 """ 73 Register a new plugin to the `mrsm_plugins` "table". 74 """ 75 return self._rust_client().register_plugin(plugin, force)
Register a new plugin to the mrsm_plugins "table".
78def get_plugin_id( 79 self, 80 plugin: 'mrsm.core.Plugin', 81 debug: bool = False 82) -> Union[str, None]: 83 """ 84 Return a plugin's ID (its name when it is registered). 85 """ 86 return self._rust_client().get_plugin_id(plugin)
Return a plugin's ID (its name when it is registered).
89def get_plugin_version( 90 self, 91 plugin: 'mrsm.core.Plugin', 92 debug: bool = False 93) -> Union[str, None]: 94 """ 95 Return the version for a plugin. 96 """ 97 return self._rust_client().get_plugin_version(plugin)
Return the version for a plugin.
100def get_plugin_user_id( 101 self, 102 plugin: 'mrsm.core.Plugin', 103 debug: bool = False 104) -> Union[str, None]: 105 """ 106 Return the user ID for a plugin's owner. 107 """ 108 return self._rust_client().get_plugin_user_id(plugin)
Return the user ID for a plugin's owner.
111def get_plugin_username( 112 self, 113 plugin: 'mrsm.core.Plugin', 114 debug: bool = False 115) -> Union[str, None]: 116 """ 117 Return the username for a plugin's owner. 118 """ 119 return self._rust_client().get_plugin_username(plugin)
Return the username for a plugin's owner.
122def get_plugin_attributes( 123 self, 124 plugin: 'mrsm.core.Plugin', 125 debug: bool = False 126) -> Dict[str, Any]: 127 """ 128 Return the attributes of a plugin. 129 """ 130 return self._rust_client().get_plugin_attributes(plugin)
Return the attributes of a plugin.
133def delete_plugin( 134 self, 135 plugin: 'mrsm.core.Plugin', 136 debug: bool = False, 137 **kw: Any 138) -> SuccessTuple: 139 """ 140 Delete a plugin's registration. 141 """ 142 return self._rust_client().delete_plugin(plugin)
Delete a plugin's registration.