Skip to content

v5.0.0

Latest

Choose a tag to compare

@github-actions github-actions released this 04 Dec 15:49
v5.0.0
cdd42d7

v5.0.0 runs queries on Amazon Athena DuckDB as well as on Athena engine version 3, with the same cursors and the same SQLAlchemy dialect.
PyAthena determines the engine of each query before sending it, because Athena DuckDB rejects some request parameters and reads some parameter literals differently; on Athena engine version 3 too, this adds a GetWorkGroup request.

Read Breaking changes and the new upgrading guide (docs/upgrading.md) before upgrading.
The new Athena DuckDB guide (docs/duckdb.md) covers engine selection, query results, IAM actions, limitations, parameters, and result types; docs/usage.md describes the new result_fetcher option.

Note

These notes list the changes since 4.4.0. The master PRs that 4.4.0 already shipped (the 4.x cut at #1477, and the backports #1552, #1553, #1554, #1560, #1568, #1578, #1594, #1601 and #1623) are not repeated here; see the 4.4.0 release notes.
Athena DuckDB support (#1678, #1680, #1681, #1683, #1684, #1685) and the changes it brings to Athena engine version 3 are described in their own section and in docs/upgrading.md.
#1582, #1589, #1622, #1633 and #1644, and the discard() part of #1539, are also on 4.x for 4.4.1 (#1591, #1640, #1650, #1653, #1659).
Python 3.11 or later is required, as in 4.4.0.

Breaking changes

Connections and cursors

  • A GetWorkGroup request per workgroup. A connection without engine_version sends one GetWorkGroup request for each workgroup that its queries target, at the first query on it, and needs athena:GetWorkGroup. A denied request, InvalidRequestException, or an engine that PyAthena does not know assumes Athena engine version 3 with a logged warning, which keeps the 4.x requests. Other failures, such as throttling after the retries, assume version 3 for that query only, and the next query asks again. connect(engine_version=...) skips the request (#1678).
  • Client-side result reuse (cache_size, cache_expiration_time) reuses an execution only when its EffectiveEngineVersion equals the engine of the query; executions that report no engine are not reused (#1678).
  • formatter= is deprecated on connect(), Connection(), cursor(), and cursor_kwargs and issues a DeprecationWarning. A formatter given there is used on every engine; use connect(engine_profiles=[dataclasses.replace(ENGINE_DUCKDB, formatter=...)]) to change the formatter of one engine. Without a formatter, the connection passes formatter=None to the cursor class, which chooses the formatter of each query's engine; a custom cursor class that uses the formatter in its constructor must handle None (#1678).
  • Order of errors. Formatting errors other than an empty query, such as a missing parameter, now come after the engine lookup. An empty or whitespace-only query with paramstyle="qmark" raises ProgrammingError before any request; without unload=True, 4.x raised DatabaseError from StartQueryExecution (#1678).
  • TIME WITH TIME ZONE values from GetQueryResults. Text with an offset in hours only (+05) or with seconds (+15:59:59) becomes an aware time, and text without an offset stays text; TIME and TIME WITH TIME ZONE 24:00:00 read as midnight on every supported Python, and other TIME text in hour 24 raises ValueError. Athena engine version 3 writes none of these forms (#1678).
  • For subclasses (private APIs): _prepare_query() requires paramstyle and a new engine argument; _build_start_query_execution_request() takes an engine keyword; the new _build_execute_request() builds the request from ExecuteOptions; result sets and cursors declare the result fetchers they read in _result_fetchers (#1678).

Dependencies

  • boto3 and botocore 1.44.17 or later are required (was 1.43.31 in 4.4.0). (#1665)
  • The sqlalchemy and aiosqlalchemy extras require sqlalchemy>=2.0.52 (was >=2.0.44 in 4.4.0). From 2.0.52, SQLAlchemy's Numeric literal processor checks that a value is a number, so with literal_execute or literal_binds a non-numeric string in a Numeric or Float parameter raises CompileError instead of being written into the SQL, and a NumPy scalar such as np.int64(7) in a Numeric parameter raises CompileError; Float parameters render NumPy scalars as before. (#1600)

Removed deprecated APIs

  • pyathena.filesystem.s3_filesystem(), deprecated in 4.4.0, is removed; use pyathena.fs.s3_filesystem(). (#1497)
  • S3FileSystem and AioS3FileSystem no longer take connection; it raises TypeError, also as connection=None. Use pyathena.fs.s3_filesystem(connection) (with AioS3FileSystem as the second argument for the async filesystem), or pass client=connection.s3_client and retry_config=connection.retry_config. (#1497)
  • All arguments of S3FileSystem and AioS3FileSystem are keyword-only; a positional argument raises TypeError. A filesystem pickled or serialized by fsspec (to_json()/to_dict()) under 4.x with connection= or with positional arguments cannot be loaded. (#1497)
  • A custom filesystem_class of the S3FS cursors is created through pyathena.fs.s3_filesystem() with client, retry_config, default_block_size and skip_instance_cache=True instead of connection, so it must accept client and retry_config. (#1497)

Queries and parameters

  • An explicit paramstyle passed to a cursor's execute() takes precedence over pyathena.paramstyle; before, the global qmark won over paramstyle="pyformat". (#1508)
  • pyathena.formatter no longer imports AthenaFileFormat and AthenaCompression; import them from pyathena.model. (#1602)

SQLAlchemy

  • Connections. The dialect compiles statements for the engine of its connections. Without engine_version in the URL or the connect arguments, each new DB API connection sends its GetWorkGroup request when it opens, including pooled connections used only for reflection or pings. A throttled or failed request fails the connection with OperationalError instead of assuming an engine for the life of the SQLAlchemy engine, and a later connection whose workgroup reports another engine than the first one raises OperationalError (#1678).
  • Reflection on Athena engine version 3 recognizes time, uuid, timestamptz, timestamp with time zone, time with time zone, varbyte, and blob columns, which it used to reflect as NullType with a warning (#1678).
  • The SQLAlchemy dialects always use the pyformat parameter style, whatever pyathena.paramstyle or a paramstyle passed to create_engine() is. Under pyathena.paramstyle = "qmark", the sync dialects sent the bound values as Athena execution parameters, and the async dialects sent %(name)s placeholders with doubled %. Now the cursor renders the bound values into the statement. Under the global qmark, exec_driver_sql() statements must use %(name)s placeholders with a dict and write % as %%, and values passed to text() bind parameters are values, not SQL literal text ("abc", not "'abc'"). The on_start_query_execution execution option is also called for executemany statements and with the no_parameters execution option. (#1508)
  • CREATE TABLE quotes the keys and values of awsathena_serdeproperties and awsathena_tblproperties given as dicts (also in connect_args), and the compression value, as string literals. Pass them as the text Athena should store, which is the form reflection returns, and remove escaping added only for Hive or the pyformat style (for example "\\\\" → "\\", "it\\'s" → "it's", "%%{SYSLOGBASE}" → "%{SYSLOGBASE}"). The compression value replaces a property of the same name in a tblproperties dict instead of rendering it twice. With the no_parameters execution option, a % in a dict key or value reaches Athena doubled. String forms of these options, row_format and file_format are unchanged. (#1484)
  • CREATE TABLE validates bucket_count, awsathena_partition_transform_bucket_count and awsathena_partition_transform_truncate_length: each must be a positive integer or a string of decimal digits, and another value raises CompileError. A table awsathena_bucket_count of 0 raises instead of falling back to the connection's bucket_count; an Iceberg bucket or truncate partition transform without a valid argument, and an unknown partition_transform name, raise instead of omitting the partition column. (#1531)
  • CREATE TABLE takes the base LOCATION and the S3 Tables catalog from the connection that initializes the dialect, as it takes the default schema, instead of from the connection URL and connect_args. With creator= or a do_connect handler, the table is created under that connection's S3 staging directory, an S3 Tables catalog on the connection omits LOCATION, and a connection without a staging directory raises CompileError unless location is set. A statement compiled before the engine first connects uses the connection URL. A connection that creator= returns must expose s3_staging_dir and catalog_name in addition to schema_name and cursor_kwargs (otherwise AttributeError at the first connect). New dialect properties default_s3_staging_dir and default_catalog_name. (#1544, #1583)
  • An Interval() column raises CompileError in DDL, since Athena tables have no interval type, and Interval is adapted to the new native AthenaInterval. Declare an existing column as Interval(native=False) to keep SQLAlchemy's emulation, which stores a TIMESTAMP. (#1630)

S3 filesystem

  • S3FileSystem.touch() and AioS3FileSystem.touch() return the PutObject response as botocore returns it, including ResponseMetadata, instead of a dictionary keyed by private attribute names (_etag). S3PutObject.to_dict() and S3CompleteMultipartUpload.to_dict() are keyed by the field names (etag). (#1435)
  • An S3Core method raises TypeError for a parameter that it also sets from its other arguments, such as Key with a path that has a key. Before, get_object, put_object, the multipart methods, list_object_annotations and copy_object_annotation dropped the parameter silently, and generate_presigned_url (and so sign()) signed it instead of the path's field. A file opened with such a parameter, such as Key or a Range for reading, raises TypeError at its first request. (#1435)
  • S3MapResult.outcomes is renamed to results, and S3DeleteResult.raise_for_outcomes() to raise_for_errors(); no aliases are kept. (#1549)
  • S3DeleteResult takes deleted_objects= as a keyword-only argument (the fields after bucket are keyword-only), deleted is a read-only property derived from deleted_objects and leaves dataclasses.fields()/asdict(), and results compare by their delete marker fields. Pickles of earlier results restore without deleted_objects. (#1590)
  • S3MultipartUploadPart.to_api_repr() requires the checksum algorithm; S3Object.to_api_repr() of a bucket or directory entry has no StorageClass; S3Object.directory() and S3Object.from_metadata() take no version_id; S3Core.list_object_annotations() no longer resumes from a ContinuationToken in params (it raises TypeError); S3MultipartUpload.request_identity() no longer raises for a missing bucket or key. (#1590, #1618)
  • S3Path.version_separators(), has_version_id(), split_version_id(), partition_by_version() and split_trailing_separators() are removed. (#1615, #1664)
  • fn is positional-only in S3Executor.submit(), submit_to(), run(), run_shielded() and the submit() of S3ThreadPool, and future is positional-only in submit_to(); a caller that passes fn=, self= or future= by keyword breaks, and keyword arguments with those names now reach the callable. (#1533, item 1)
  • pipe_file() and put_file() (sync and aio) resolve and check block_size as open(..., "wb") does, before any request: put_file(..., block_size=0) raises ValueError (omit it or pass None for the default); pipe_file() of data up to the block size, outside a transaction, with block_size=0 or a value outside 5 MiB to 5 GiB, raises instead of sending one PutObject, and so does such a call on a filesystem whose default_block_size is outside the write limits unless a valid block_size is given. (#1611)
  • pipe_file() (and pipe() with a mapping or a single path) of data up to the block size, outside a transaction, with a max_workers that is not positive (pipe(): negative), raises ValueError instead of sending one PutObject. cp_file(), copy() and mv() of a source up to 5 GiB with a block_size outside 5 MiB to 5 GiB (other than 0 or None), or a negative max_workers, raise ValueError before any request instead of sending one CopyObject. (#1629)
  • pipe_file(), put_file() and get_file() address the key as written: s3://bucket/dir/ writes or reads the key dir/, not dir, and s3://bucket// the key / (pipe_file()/put_file() no longer raise ValueError for it). get() with lists of both sources and destinations downloads each source at its key as written. pipe_file(..., compression="infer") infers the codec from the key as written. put_file() checks its destination also when the local path is a directory. put_file() and get_file() no longer go through open(), so a subclass's open() override does not see their calls. AioS3FileSystem._pipe() of a single path passes it to _pipe_file() without the protocol and trailing slashes. open(), pipe() and put() keep fsspec's meaning of a trailing slash. (#1645)
  • Every method converts a caller's path once, and accepts an S3Path, which names the object of its key as written and the directory of its key without trailing slashes: fs.ls(S3Path("b", "dir/")) lists what fs.ls("s3://b/dir/") lists, rm(), cat(), copy(), get(), open() and glob() address the object dir/, and S3Path("b", "/") is the key /, not the bucket. (#1664)
  • A subclass that sets protocol reads every path with its own protocols only: s3://... raises ValueError on a subclass whose protocols do not include s3, and so does a path that starts with another protocol after one of the class. (#1664)
  • isfile() raises ValueError for a path that is not an S3 path (fsspec and s3fs return False), so key in fs.get_mapper(root) raises for such a key. cat_ranges() raises the ValueError of an invalid path before any read, also with on_error="return". copy(), mv(), get(), put(), pipe(), rm(), cat() and expand_path() check every path, sources and destinations, before the first request. (#1664)
  • A path with two leading protocols, such as s3://s3://bucket/key or s3::s3://bucket/key, raises ValueError before any request instead of naming bucket/key in some methods, writes included. An S3Path with a version but no key raises ValueError, also through with_version_id() and info("s3://bucket", version_id=...). (#1615)

Behavior changes

Queries and parameters

  • DefaultParameterFormatter quotes string parameters for the engine that parses each statement: a statement starting with CREATE EXTERNAL TABLE is always Hive DDL; only SHOW DATABASES, PARTITIONS, SCHEMAS, TABLES and TBLPROPERTIES get the Hive escaper, and other SHOW statements the Trino escaper; keywords are recognized with comments between them, and a line comment also ends at a carriage return. A CREATE TABLE statement containing AS keeps the Trino escaper, and a string value with an odd run of backslashes before a quote or at its end raises ProgrammingError. (#1507)
  • A float in a sequence parameter, such as IN %(xs)s, renders with repr() (0.1234567, 1e-20) instead of "%f", which rounded to six decimal places. NaN and infinity render as nan(), infinity() and -infinity() in scalar, sequence and ARRAY parameters and in SQLAlchemy inline rendering, instead of nan, inf and -inf, which Athena reads as column names. A non-finite value with a %(x).2f format raises TypeError. (#1530)
  • On Athena engine version 3, a timedelta parameter renders as INTERVAL '[-]D HH:MM:SS.mmm' DAY TO SECOND, truncated below a millisecond toward zero. (#1630)
  • With the default catalog_name (awsdatacatalog, case-insensitive), the query's QueryExecutionContext names no catalog. cursor.catalog, result_set.catalog and AthenaQueryExecution.catalog are then None. With the default catalog, a run of spaces in a Hive DDL string literal (table and column comments, table and SerDe properties, partition values and locations) is stored as written, and so is a run of raw line breaks in a table comment; a column comment with a run of raw line breaks is now rejected by Glue. Client-side result reuse (cache_size) treats a context without a catalog as AwsDataCatalog. Whether Athena's own result reuse (result_reuse_enable) matches executions from before and after the upgrade was not measured. (#1624)
  • UNLOAD cursors (Pandas, Arrow, Polars) format the query with its parameters first and wrap it in UNLOAD afterwards. A SELECT/WITH that starts with a comment is converted to UNLOAD; a query ending with ; works with UNLOAD; a multi-line query is embedded as written; a destination containing ' raises ProgrammingError before the query starts. A custom Formatter receives the inner query instead of the UNLOAD statement, and a custom wrap_unload() receives the formatted query. The UNLOAD cursors no longer call the private _execute() (use _execute_query()). (#1589)
  • to_sql() and generate_ddl() quote the names (backticks, doubled) and literals of the Hive DDL they write, and AthenaTableMetadata.row_format/file_format escape class names. A partition value with a quote is registered as itself; a partition value that fits between neither quote raises ProgrammingError before any request; a partition LOCATION with a quote or backslash is registered as the uploaded prefix. With index=False, an index level with the name of a partition column no longer makes the grouping ambiguous. (#1602)

SQLAlchemy: rendering and types

  • In a division with a DECIMAL operand, only a literal_column() typed Numeric/DECIMAL with a precision is cast, to DECIMAL(38, s) with its own scale; columns, expressions, aggregates, cast() and bind parameters are left to Athena. Before, both operands were cast to the expression's result type. (#1465)
  • A division classifies each operand by its TypeDecorator's declared impl: for example D(Integer) / Integer renders d / CAST(i AS DOUBLE) instead of casting to DECIMAL, and Integer / F(Float) casts both operands to DOUBLE instead of REAL. (#1635)
  • Float, FLOAT and REAL are adapted to the new AthenaFloat, and Double, DOUBLE and DOUBLE_PRECISION to AthenaDouble, whose literal processor renders a float by value and NaN and infinity as functions. (#1530)
  • Numeric, NUMERIC and DECIMAL are adapted to the new AthenaNumeric: an inline Decimal (literal_binds, literal_execute, ARRAY elements) renders as DECIMAL '5.52' on Athena engine version 3 instead of 5.52, which Athena reads as DOUBLE. A Decimal whose fixed-point form has more than 38 digits is rejected by Athena, as when bound. A float NaN or infinity in a fixed-point type renders as nan()/infinity(). A user subclass of Numeric (not a Float) is adapted to AthenaNumeric, so its own processors are no longer used; subclass AthenaNumeric or use a TypeDecorator to keep them. (#1573)
  • SQLAlchemy DDL writes a CR, LF or tab in a comment, a table or SerDe property, or a location as \r, \n or \t. The private formatter functions _escape_trino, _escape_hive, _date_literal, _timestamp_literal and _float_literal are removed in favor of the public functions below. (#1550)
  • On SQLAlchemy 2.0, the elements of an ARRAY of a Float type with asdecimal=True are rounded to decimal_return_scale (10 digits unless set), as the column is: 0.1 becomes Decimal('0.1000000000'). On SQLAlchemy 2.1, those elements are returned as numbers instead of strings. (#1577)
  • A dict compared with or written to a MAP column renders as CAST(MAP(ARRAY[...], ARRAY[...]) AS MAP(k, v)), and a ROW value (a dict with the declared fields, or a tuple) as CAST(ROW(...) AS ROW(...)); both failed before. A tuple or list compared with a ROW column is cast to the declared ROW type, so a Decimal with more digits than a field's scale is rounded before the comparison (=, IN, and the WHERE clause of UPDATE and DELETE); in 4.4.0 it was compared as it was. A MAP or ROW whose Numeric has no precision is bound without the cast. An empty in_() list for an ARRAY, MAP or ROW column renders invalid SQL. ARRAY, MAP and ROW element types must be hashable, as SQLAlchemy requires. (#1630, #1661)
  • When the non-array operand of an ARRAY quantified comparison (x <op> any_(array)/all_(array)) contains a subquery or a function call, the comparison renders through zip_with(...) so the operand is evaluated outside the lambda; a scalar function such as func.lower(name) == any_(tags) is then evaluated once per row instead of once per element. The bounds of a quantified BETWEEN with a subquery, aggregate or window function are evaluated the same way. (#1636, #1658)
  • Once a connection fails to initialize the dialect, the dialect keeps the default schema it had before the attempt. (#1583)

S3 filesystem: paths

  • Every method accepts s3:: and s3a:: paths. unstrip_protocol("s3::bucket/key") returns s3://bucket/key. (#1615)
  • copy(), mv() and get() pass their paths to cp_file()/get_file() without the protocol, also those of two lists, and pipe() passes an S3Path to pipe_file(). mv() of a path onto the same path in another spelling (s3://b/k and s3a://b/k) returns before any request. A file's path is str() of its S3Path, compression="infer" reads the extension of the key, and a pickled file reopens its bucket, key and version. (#1664)
  • info() of an explicitly requested version other than null names the entry bucket/key?versionId=<id>, and du(total=False) uses the same key. info()["version_id"] holds the version that HeadObject returns, also without version_aware. (#1618)
  • AioS3FileSystem._du() runs du() in a thread, so withdirs=True includes the bucket, as S3FileSystem.du() does. (#1540)

S3 filesystem: batch operations

  • AioS3FileSystem's copy, mv, cat(on_error="raise") and cat_ranges(on_error="raise") stop at the first failure, as the sync API does; they used to send every request. Its batch_size has the sync meaning (the call's value, else the filesystem's, else max_workers; -1 means max_workers), and 0 and other negative values raise ValueError before any request. AioS3FileSystem.batch_size forwards to the internal S3FileSystem, so _rm follows it. await _cat(path) of one unexpanded path raises the error of its read for every on_error value. (#1555)
  • S3FileSystem.copy(on_error=X) skips a missing source only for "ignore". cat_ranges accepts any iterable of starts and ends, and pipe any non-string object with items(). (#1555)
  • mv copies a source without a version ID with CopySourceIfMatch on the ETag of its lookup and deletes it with that ETag per object in DeleteObjects: a source that another client replaced during the move is kept, and mv raises an OSError that lists it with PreconditionFailed after all deletions; a source that another client deleted is no error. Deleting on an ETag needs s3:GetObject on the source. A CopySourceIfMatch or CopySourceIfUnmodifiedSince given to a multipart copy (source over 5 GiB) is also sent to its HeadObject. S3DeleteResult.raise_for_errors() leaves out NoSuchKey. S3-compatible endpoints without per-object ETags in DeleteObjects or CopySourceIfMatch are not covered. (#1632)
  • After a failed annotation copy of a committed copy, the other annotations are still attempted, and a stop that reaches a multipart copy after its upload completed is raised after them. A sent CompleteMultipartUpload keeps its retries after a stop, also for file commits. An aio copy in a stopped scope sends no CopyObject. S3Executor.run() cancels or stops its call on an interrupt of the event loop's thread. (#1587)

S3 filesystem: requests and parameters

  • Inherited request parameters (s3_additional_kwargs, a writer's or core's request_kwargs) yield to the fields that a request sets, such as a read's Range or a part's PartNumber, instead of raising TypeError. ContentMD5, ContentLength and checksum values among them are sent with PutObject (and the checksums with the completion of a FULL_OBJECT upload), and no longer with parts, tagging, ACL or annotation requests. S3Core.create_bucket(), put_object_acl() and put_bucket_acl() no longer send the ACL or grants of request_kwargs. S3Core.plan_multipart_copy() honors the directives, tags and metadata of request_kwargs, and reads the source without the destination's ExpectedBucketOwner. (#1558)
  • A file that S3File(fs, ...), AioS3File(fs, ...) or AioS3StreamedFile(fs, ...) creates directly takes the filesystem's default_block_size, default_cache_type and s3_additional_kwargs; before, it used a 5 MiB block size, the "bytes" cache and only the authorization parameters. Files from open() are unchanged. (#1588)
  • With an explicit EncodingType="url", S3Core listings return decoded keys, prefixes and markers; a caller that unquoted them itself now decodes twice. (#1599)

S3 filesystem: cache

  • Single-request writes, S3File.commit(), rm_file() and setxattr() invalidate their path after any outcome. A request that finds an object missing evicts its cached entry; a read that fails with PreconditionFailed on a cached ETag invalidates the path. Exclusive writes (pipe_file(mode="create"), open("xb"), put_file(mode="create")) check with HeadObject without the cache and no longer send the ListObjectsV2 probe. (#1536)
  • A commit invalidates the cache only once its PutObject or CompleteMultipartUpload has been sent. (#1579)
  • A missing bucket, found by HeadBucket or reported as NoSuchBucket, evicts every cached entry of the bucket. mkdir(bucket), and mkdir(bucket/prefix) with allow_bucket_creation=True, send HeadBucket even when the bucket is cached. A write and invalidate_cache("bucket/key") keep the cached HeadBucket lookup; use exists(bucket, refresh=True) or invalidate_cache("bucket") to check the bucket again. With max_paths, a lookup of an uncached path no longer pushes other cached entries out. (#1561)
  • A fresh listing or lookup evicts the cached entries that it contradicts, and lookups are cached by the parameters that their requests carry. Of overlapping requests, an older result can stay cached until it is invalidated, contradicted or expires. (#1626)

S3 filesystem: writes and closes

  • discard() closes the file. commit() of an open S3File closes it first, so the final flush uploads the rest. open() with a codec returns an S3CompressedFile instead of the codec's stream (such as gzip.GzipFile); it delegates other attributes to that stream, and its close commits the object and raises a commit failure. (#1539)
  • A retried commit() after an interrupted close()/commit() raises S3WriteStateError instead of committing incomplete data, and an interrupted close of a multipart write aborts the upload. A write during garbage collection reports its failure when the handed-over close runs. Closing a file that is already closed does not wait for its running requests. (#1637, #1646)
  • AioS3StreamedFile: an exit with an exception waits for another task's close, final flush or abort, and a close() concurrent with a failing direct flush(force=True) raises the flush's error. Writing to one file from several tasks at once is documented as unsupported. (#1593)
  • The write session is public (see below): S3MultipartStateError is an alias of the new S3WriteStateError. (#1627)

Arrow cursor

  • On the UNLOAD metadata read, which AsyncArrowCursor.description(query_id) also uses, an error creating the PyArrow filesystem is raised as PyArrow raised it instead of as OperationalError, and a result without a file creates no filesystem. (#1614)

New features

Athena DuckDB

  • connect(engine_version=...) with "DuckDB" or "Athena engine version 3", sent as the EngineVersion of each query; otherwise the engine of the workgroup from GetWorkGroup, cached per workgroup and connection (#1678).
  • Requests built for each engine: on Athena DuckDB, no ResultConfiguration, ExecutionParameters, or UNLOAD, with ProgrammingError or NotSupportedError before the query instead of a service rejection (#1678).
  • DuckDBParameterFormatter formats pyformat parameters as DuckDB literals (#1678); pyathena.engine.EngineProfile and connect(engine_profiles=...) replace the built-in profile of an engine (#1678).
  • DuckDB type names in cursor.description (lowercase base names) and converters for the DuckDB types in GetQueryResults (#1678).
  • The SQLAlchemy dialect compiles DDL, reflection, views, and DML for Athena DuckDB (#1678).
  • timedelta parameters and the SQLAlchemy Interval type on Athena DuckDB: pyathena.formatter.duckdb_interval_literal() writes days and a time with microseconds, with the sign on both parts (INTERVAL '-1 day -02:00:00.000001'); Interval results read DuckDB's interval text and the pyarrow.MonthDayNano of the Arrow cursor; cast(x, Interval()) is CAST(x AS INTERVAL) (#1674, #1684).
  • Inline Decimal values of the SQLAlchemy dialect (literal_binds, literal_execute, ARRAY/MAP/ROW leaves) keep their precision and scale on Athena DuckDB, written with the new pyathena.formatter.duckdb_decimal_literal() as bound values are (#1675, #1680).
  • SQLAlchemy decimal division on Athena DuckDB: a Numeric quotient is cast to DECIMAL(38, max(s1, s2)), the scale that version 3 gives it, from both operands, with the scale of a bound Decimal read from its value when the statement is executed (the compiled SQL carries a parameter such as %(pyathena_quotient_scale_1)s); a floor division of bound values rounds to that scale before FLOOR as version 3 does (#1676, #1682, #1683, #1685).
  • Cancelling an asyncio query stops the GetWorkGroup and GetQueryResultStream retries, as docs/aio.md promises (#1679, #1681).

Result fetchers

  • result_fetcher on connect(), cursor(), execute(), and ExecuteOptions: "auto", "GetQueryResults", "GetQueryResultStream", or "S3". A forced value never falls back and raises ProgrammingError when it cannot serve the query (#1678).
  • "GetQueryResultStream" reads the result of a query on Athena DuckDB with managed query results as an Apache Arrow stream, with truncation detection and Range resume (#1678):
    • Cursor, DictCursor, and their Async and Aio variants read it one record batch at a time and convert the values with a StreamConverter (connect(stream_converter=...), cursor(stream_converter=...), pyathena.stream.converter), whose default gives the scalar values of GetQueryResults (#1678).
    • ArrowCursor, PandasCursor, PolarsCursor, and their Async and Aio variants read it into their tables and DataFrames, PandasCursor and PolarsCursor chunk by chunk with chunksize (#1678).
  • "auto", the default, reads GetQueryResultStream when it serves the query and the cursor reads it; otherwise the result file in S3 when the query has an output location and the cursor reads result files, and GetQueryResults in every other case (#1678).

Other features and improvements

  • New public SQL literal functions in pyathena.formatter: trino_string_literal(), hive_string_literal(), date_literal(), timestamp_literal(), double_literal() (#1550), decimal_literal(), varbinary_literal() (#1573), trino_quoted_identifier() (#1589), hive_quoted_identifier(), hive_partition_value() (#1602) and interval_literal() (#1630).
  • SQLAlchemy: Interval columns and timedelta operands render as Athena INTERVAL values, and interval results are read as timedelta; MAP and ROW values can be bound and rendered. (#1630)
  • ArrowCursor, AsyncArrowCursor and AioArrowCursor take s3_filesystem_kwargs, keyword arguments for the pyarrow.fs.S3FileSystem that reads CSV results and UNLOAD Parquet, in the constructor (and cursor_kwargs) and in execute(). (#1614)
  • pyathena.filesystem.s3_writer exposes S3WriteSession, S3WriteState and S3WriteStateError (the former private write session). (#1627)
  • S3MultipartUpload.version_id and S3MultipartUploadPart.version_id keep the VersionId of CreateMultipartUpload, ListMultipartUploads, UploadPart and UploadPartCopy responses. (#1662)
  • New S3Path.remove_protocol(), strip_protocol(), parent_name() and unstrip_protocol(), and the protocols argument of S3Path.parse(). (#1615)
  • New S3Core.with_request_kwargs() and S3MultipartCopyPlan.request_kwargs (#1558); S3ClientError.of() and S3ClientError.bucket_name (#1561); S3DeleteBatch(etags=...), S3DeleteBatch.from_paths(etags=...) and S3ClientError.is_copy_source_precondition_failed() (#1632).

Bug fixes

  • Metadata requests (get_table_metadata(), list_table_metadata(), list_databases()) and the Glue fallback name AwsDataCatalog when neither the call nor the cursor has a catalog_name; botocore rejected the missing CatalogName before. (#1624)
  • get_view_definition() quotes the schema and view names, so a " in either name no longer ends the identifier. (#1589)

SQLAlchemy

  • A time-travel hint is placed before an alias that SQLAlchemy generates, and is recognized with leading whitespace or line breaks, tabs or repeated spaces between its keywords. (#1582)
  • A FROM hint or statement hint whose last line contains -- ends with a line break, so a trailing line comment no longer swallows the rest of the statement. (#1644)
  • The PyAthena temporal, MAP and ROW types declare their operator classes on SQLAlchemy 2.1, which warned for IS NULL, =, <, IN, .desc() and date arithmetic on them. (#1607)
  • CREATE VIEW, DROP VIEW and CREATE TABLE AS (SQLAlchemy 2.1 CreateView, DropView, Select.into()) quote their names with Trino's double quotes and SELECT reserved words. (#1631)
  • alter, json_array, json_exists, json_object, json_query, json_table, json_value, listagg, skip and trim are quoted in DML. (#1641)
  • The any_match()/all_match() lambda variable avoids the names of the statement, including stored SELECTs of SQLAlchemy 2.1 CreateView and Select.into(), and schemas named _pyathena_element_<n>. (#1612)
  • An aggregate, window function or subquery compared with an ARRAY quantifier, such as func.max(t.c.id) == any_(t.c.items) in HAVING, renders SQL that Athena accepts. (#1636, #1658)
  • Compiling a function used as a comparison with an ARRAY quantifier (as_comparison()) no longer changes the caller's expression, so a statement that uses it twice renders any_match() for both. (#1648)

S3 filesystem

  • An AioS3StreamedFile read, or any other map_async(), no longer hangs on Python 3.11 and 3.12 after one of its calls fails; a stopped batch is drained before its error is raised. (#1622)
  • A stopped aio batch no longer leaves RuntimeWarning: coroutine ... was never awaited. (#1555)
  • An interrupt of discard() no longer leaves a closed autocommit=False file whose later commit() replaces the object with an empty one. (#1637)
  • Interrupted flushes, closes and writes of S3File no longer leave a committable write without its data, and an interrupted hand-over of a close during garbage collection no longer makes the exit wait forever. (#1646)
  • cat_file() with a negative or empty range of a version given by version_id sizes the key as written. (#1615)

Known limitations on Athena DuckDB

  • One statement per query; no qmark parameters; no unload=True.
  • cache_size reuses no Athena DuckDB execution, because Athena DuckDB does not report a StatementType (the search still sends its ListQueryExecutions and BatchGetQueryExecution requests).
  • A query whose result has an ENUM column fails with managed query results.
  • With "GetQueryResultStream", FLOAT values can differ from those of GetQueryResults for some whole numbers between about 3e7 and 6e10, and PolarsCursor reads HUGEINT and UHUGEINT as Int128 and UInt128, which Polars cannot convert to Arrow or pandas.
  • SQLAlchemy: views over Hive tables only; Iceberg table names limited to letters, digits, and underscores; decimal division computed as DOUBLE and then cast to version 3's scale, so it can differ from version 3 beyond about 15 significant digits and in rounding; an expression that Athena widens, such as a * a, keeps the scale of its SQLAlchemy type; // of decimals with scale 0 takes FLOOR first (3 // 2 in DECIMAL(2, 0) is 1, 2 on version 3).
  • SQLAlchemy Interval: an interval with months or years has no timedelta equivalent and raises ValueError (read it with cast(expression, String())); Date ± timedelta is a TIMESTAMP on Athena DuckDB (a DATE on version 3).

Documentation

  • New guides: docs/duckdb.md and docs/upgrading.md; the result fetchers section of docs/usage.md; the Athena DuckDB section of docs/sqlalchemy.md (#1678).
  • just test sqla-duckdb runs the SQLAlchemy compliance suite on an Athena DuckDB workgroup (#1678).
  • docs/sqlalchemy.md says to pass the parameters of a statement with a time-travel hint on an alias to execute(), since Select.params() and Select.unique_params() can drop the hint. (#1633)
  • The versioning and bucket-lifecycle examples of docs/filesystem.md use s3_filesystem(connection, ...). (#1548)

What's Changed

Full Changelog: v4.3.0...v5.0.0