SQL#
- class astropathdb.db_io.sql.SQL(database=APDBREF.DEFAULT_DATABASE, username=None, password=None, credential_filename=None, *, db_connection=True)#
Bases:
SciBaseAn SQL base class that wraps
select().We do this so that we can use textual expressions in Object Relational Mapping (ORM) clauses vs always having to use explicit expressions as well as applying our own default custom filters functions based on the unique AstroPath database schema.
To allow for the textual ORM clauses the
AstroDBinherits from theSQL, which wrapsselect()to lookup the ORM attributes in the respective objects. Thus when writing aselectstatement using ORM you can useobj.select(*columns, table_name=table_name, context=context).See
select()for additional details on the function itself andAstroDBfor more information related to the design of the ORM generated when an instance of the class is created.To create the default custom filters, we run the function
_create_dynamic_filter()over a list of filters during import. See the_create_dynamic_filter()documentation for details on those filters andAPFiltersfor a list of the filters.- Parameters:
database (str) – The database to query by default, given in any letter case (see
canonical_database_name()). Defaults to a public database.username (str | None) – The SciServer account. With
password, it takes priority over every other source. Alone, it ranks belowcredential_filename, and a missing password may be completed from this account’s keyring.password (str | None) – The selected account’s password, preserved exactly when supplied directly.
credential_filename (str | Path | None) – A local .env, JSON, or two-line text credential file, used unless
usernameandpasswordare both given. Relative paths use the current directory; home-directory paths may start with~.db_connection (bool | CasJobsUrllib3Client) –
Trueto authenticate and open a client, or an existingCasJobsUrllib3Clientto reuse its connection pool.**kwargs – Keyword arguments for
SciBase.
See also
AstroDB:Implementation of the ORM design itself.
- Query the database with SQLAlchemy
Example use cases.
_create_dynamic_filter():The custom filter implementation provided as an extension.
APFilters:A list of the custom filters themselves.
SQL Properties#
SQL Methods#
|
Custom wrapper for |
|
If a table name is passed this will get that ORM attribute. |
|
Using mappings add our custom filters to a |
|
The basic initialization for load_<element>_queries. |
|
Authenticate or reuse the process-wide SciServer session. |
|
Query a database with a SQL statement. |
|
Print, or return, a SQL statement as the SQL sent to the database. |
|
Wrap a string in single quotes for use as a SQL string literal. |
|
Convert |
|
Run |
SQL References#
Property Reference#
- property sql#
- Type:
str | ClauseElement | Sequence[str | ClauseElement]
- Return type:
str | ClauseElement | Sequence[str | ClauseElement]
The last query sent to the database.
Holds the SQL string, or list of strings, most recently sent by
query(). Set it to a SQL string, a SQLAlchemy construct, or a sequence of either, then callquery()with nosqlto run it; the attribute then holds the SQL that was sent.
- property database#
-
The database queried when no
dbis given.Always the registered spelling of the name (see
canonical_database_name()). Setting it calls_database_setter(), which subclasses override.
Method Reference#
- method select(*columns, table_name=None, context=None)#
Custom wrapper for
select().We do this so that we can use text expressions in Object Relational Mapping (ORM) clauses vs always having to use explicit expressions.
If sqlalchemy constructs are passed as the initial arguments, it returns the sqlalchemy
select()as normal.Optionally, you can provide a list of
columns, atable_name, and/or acontextas strings and the method will perform an attribute lookup on the instance of the class to find the corresponding ORM contructs. Thus when writing aSQL.select()statement the ORMselect()for thesampleidandcellidcolumns from the Celltag Table can be built withobj.select('sampleid', 'cellid', table_name = 'celltag'). This may become simpler for longer queries than the fully qualified version:obj.select(obj.apmifwsi001_DR2.celltag.sampleid, obj.apmifwsi001_DR2.celltag.cellid).Warning
If the attribute for the
contextdoes not exist this will return an attribute not found error.- Parameters:
*columns – Positional arguments are interpretted list of columns to be selected in the database (e.g.
'sampleid', 'ptype') or a declarative base object for a table (e.g.obj.apmifwsi001_DR2.celltag.sampleid, obj.apmifwsi001_DR2.celltag.cellid).table_name (str | DeclarativeBase | None) – The table name to query as either the mapping object (e.g.
table_name=obj.apmifwsi001_DR2.celltag) or as text (e.g.table_name='celltag').context (str | DeclarativeBase | None) – The database context to query as either the mapping object (e.g.
context=obj.apmifwsi001_DR2) or as text (e.g.context='apmifwsi001_DR2') (defaults todatabaseattribute of the object).
- Return type:
See also
sqlalchemy.sql.expression.select():For the sqlalchemy
selectdocumentation.
_get_context()andget_table():Methods used for the lookup.
_create_dynamic_filter():The custom filter implementation provided as an extension.
APFilters:A list of the custom filters themselves.
- method get_table(context=None, table_name=None)#
If a table name is passed this will get that ORM attribute.
Will include the context using
_get_context()for a lookup. If the context is not provided we use thedatabaseattribute of the object.- Parameters:
table_name (str | DeclarativeBase | None) – The table name to query as either the mapping object (e.g.
table_name=obj.apmifwsi001_DR2.celltag) or as text (e.g.table_name='celltag'). If a string is passed the ORM object is looked up in the class.context (str | DeclarativeBase | None) – The database context to query as either the mapping object (e.g.
context=obj.apmifwsi001_DR2) or as text (e.g.context='apmifwsi001_DR2'). If a string is passed the ORM object is looked up in the class. (defaults todatabaseattribute of the object).
- Returns:
Returns the table attribute itself with the context.
- Return type:
- static add_sql_filters(construct, **filter_mappings)#
Using mappings add our custom filters to a
Selectconstruct.We extend the
Selectadding keyword arguments as filter mappings, where the argument name is one of the filters inAPFiltersand the value is a mapping of argument:value pairs for the filter.For example, to filter on the current
sampleidwe can addsampleid = self.sampleid. By default this is already done for us in some methods, to remove the filter we can pass the keyword argumentsampleid = '*', where ‘*’ is a special value we use to specify all values. Optionally, filtersNote
When default filters are denoted by query and loading methods they typically implement those defaults with this method.
- Parameters:
construct (Select) – The sqlalchemy contruct to add the filter to. Must have been derived from
SQL.select().**filter_mappings – The argument name is the name of a filter in the
APFiltersand the value is a mapping of argument:value pairs.
- Return type:
See also
load_query_init()Additional details on implementation
APFilters:For a list of the available filter mappings
_create_dynamic_filter():Additional internal details on the mapping arguments and logic
- method load_query_init(*columns, table_name=None, top_n=None, where=None, sql=None, **kwargs)#
The basic initialization for load_<element>_queries.
If
sqlis not empty, will return the query. Otherwise it will use our customSQL.select()to generate aSelectconstruct using the positional arguments ascolumnsand applying thetable_name,where, andtop_narguments when applicable. We always add the sampleid to the list of columns to query.We then extend the
Selectadding any other keyword arguments as filter mappings usingadd_sql_filters().Note
When default filters are denoted by query and loading methods they typically implement those defaults with the
add_sql_filters()method.- Parameters:
*columns – Positional arguments are interpretted list of columns to be selected in the database (e.g. (‘sampleid’, ‘ptype’)) or a declarative base object for a table (e.g. obj.apmifwsi001_DR2.celltag). The latter would return all columns in the provided table. By default the “sampleid” column is always added.
table_name (str | DeclarativeBase | None) – The table name to query as either the mapping object (e.g.
table_name=obj.apmifwsi001_DR2.celltag) or as text (e.g.table_name='celltag').where (Any | None) – Provide a custom ‘where’ clause to filter the table. This is passed to
where()and should be aColumnExpressionArgument.top_n (int | None) – If applied will only return the top n rows and is applied using
limit()fromsqlalchemy.sql (str | Select | None) – Provide a custom sql query for the element instead of using the default filters options, supersedes and skips all other input arguments.
**kwargs – Keyword arguments passed to
add_sql_filters()(Defaults tosampleid = {'sampleid':self.sampleid}).
- Return type:
See also
- Implementation examples:
add_sql_filters():For the dictionary implementation of custom filters.
- method sci_login(username=None, password=None, *, credential_filename=None)#
Authenticate or reuse the process-wide SciServer session.
Automatic local discovery selects an environment token, the existing session, a configured file, environment credentials, then
scicreds/sciserver_creds.txtin a source checkout. Supply explicit credentials to reauthenticate after a rejected query; a bare call may reuse the rejected session. Reused tokens are not validated against the server. Compute uses its managed session only.- Parameters:
username (str | None) – The SciServer account. With
password, it takes priority over every other source. Alone, it ranks belowcredential_filename, and a missing password may be completed from this account’s keyring.password (str | None) – The selected account’s password, preserved exactly when supplied directly.
credential_filename (str | Path | None) – A local .env, JSON, or two-line text credential file, used unless
usernameandpasswordare both given. Relative paths use the current directory; home-directory paths may start with~.
- Raises:
AstroPathAuthenticationInputError – Inputs are invalid.
AstroPathCredentialsError – No complete credentials or token are available.
FileNotFoundError – A selected credential file does not exist.
AstroPathAuthenticationError – SciServer authentication failed.
CasJobsLoginError – No active token was obtained.
- Return type:
None
Examples
db.sci_login(username="account", password=password)
- method query(sql=None, *, long=False, db=None, output_format=CASJOBSDCONST.DEFAULT_RETURNTYPE, nthreads=CASJOBSDCONST.DEFAULT_THREADS, _force_sciscript=False)#
Query a database with a SQL statement.
sqlis a SQL string, a SQLAlchemy construct, or a sequence of either. Constructs are compiled to SQL strings. A sequence is run as separate queries in parallel, and the results are returned in completion order, not input order. Splitting a large query into a sequence, or joining several queries with ‘;’, usually returns data faster.- Output formats:
“pandas”: A dataframe for a single result set, otherwise a list of the non-empty dataframes.
“pandas_concat”: The non-empty result sets concatenated into one dataframe. All result sets must have the same columns.
“json” or “dict”: The raw result set dictionaries.
“list”: A
(columns, rows)tuple with the rows of every result set. All result sets must have the same columns.“csv”, “readable”, “StringIO”, “fits”, and “BytesIO”: Supported only with
_force_sciscript; see theSciScript-Pythondocumentation.
- Parameters:
sql (str | ClauseElement | Sequence[str | ClauseElement] | None) – The query or queries to run. Defaults to
sql.long (bool) – Submit
sqlas a long-runningCasJobsjob and wait for it. Use for queries that exceed the synchronous time limit; the query must write its results to a table in ‘MyDB’, and the job status is returned instead of data.db (str | None) – The database context. Defaults to
database.output_format (str) – The output format; see above.
nthreads (int) – Number of threads used to run a sequence of queries.
_force_sciscript (bool) – Run the query through
SciScript-Pythoninstead of the package’s parallel client.
- Returns:
The query results in the
output_formatoutput format.- Return type:
dict | list[dict] | tuple[list, list] | DataFrame | list[DataFrame]
Examples
Query a table, then run two queries in parallel and join their results:
from astropathdb import AstroDB astrodb = AstroDB(database="apmifwsi001_DR2") samples = astrodb.query("SELECT sampleid, astroid FROM Samples") df = astrodb.query( [ "SELECT sampleid, astroid FROM Samples WHERE sampleid < 10", "SELECT sampleid, astroid FROM Samples WHERE sampleid >= 10", ], output_format="pandas_concat", )
- method print_sql(sql=None, *, construct=False, as_string=False)#
Print, or return, a SQL statement as the SQL sent to the database.
Defaults to the last SQLAlchemy construct passed to
query(), then tosql.- Parameters:
- Returns:
The statement if
as_stringisTrue, otherwiseNone.- Return type:
str | ClauseElement | Sequence[str] | None
- static dbstring(sql_str)#
Wrap a string in single quotes for use as a SQL string literal.
- static convert_to_geom(df, geometry_id)#
Convert
DataFrametoGeoDataFrame.The database returns
geometryvalues as well-known text (MSSQL.STAsText()) or as hex-encoded well-known binary (.STAsBinary()). Thegeometry_idcolumn is parsed as WKB when its values start with ‘0x’, otherwise as WKT, and replaced by a ‘geometry’ column. Rows with empty geometries are removed.- Parameters:
- Returns:
The query result with a ‘geometry’ column in place of
geometry_id.- Raises:
ValueError –
geometry_idis ‘geometry’.- Return type:
See also
gquery()to query and convert in one call.
- method gquery(*args, geometry_id=APDBREF.GEOM_WKT_NAME, **kwargs)#
Run
query()and convert a geometry column.The
geometry_idcolumn of the result becomes the ‘geometry’ column of aGeoDataFrame; seeconvert_to_geom().- Parameters:
- Returns:
The query result, converted when
geometry_idis given.- Return type:
See also
query()for query inputs and output formats, andconvert_to_geom()for the geometry conversion.
Private Method Reference#
- method _get_context(context=None)#
Get the database context to create the query.
- Parameters:
context (str | DeclarativeBase | None) – The database context to query as either the mapping object (e.g.
context=obj.apmifwsi001_DR2) or as text (e.g.context='apmifwsi001_DR2') (defaults todatabaseattribute of the object).- Returns:
Returns the context attribute itself.
- Return type:
str | DeclarativeBase | None
- static _get_columns(*columns, this_table=None)#
Get the database columns from string inputs to create the query.
- Parameters:
*columns – The columns to query.
this_table (str | DeclarativeBase | None) – The database table to query as a string (defaults to
None).
- Returns:
A list of columns to query either as
TextClauseobjects or, if thethis_tableargument is defined, as the ORM attributes.- Return type: