Repository navigation
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
GetWorkGrouprequest per workgroup. A connection withoutengine_versionsends oneGetWorkGrouprequest for each workgroup that its queries target, at the first query on it, and needsathena: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 itsEffectiveEngineVersionequals the engine of the query; executions that report no engine are not reused (#1678). formatter=is deprecated onconnect(),Connection(),cursor(), andcursor_kwargsand issues aDeprecationWarning. A formatter given there is used on every engine; useconnect(engine_profiles=[dataclasses.replace(ENGINE_DUCKDB, formatter=...)])to change the formatter of one engine. Without a formatter, the connection passesformatter=Noneto the cursor class, which chooses the formatter of each query's engine; a custom cursor class that uses the formatter in its constructor must handleNone(#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"raisesProgrammingErrorbefore any request; withoutunload=True, 4.x raisedDatabaseErrorfromStartQueryExecution(#1678). TIME WITH TIME ZONEvalues fromGetQueryResults. Text with an offset in hours only (+05) or with seconds (+15:59:59) becomes an awaretime, and text without an offset stays text;TIMEandTIME WITH TIME ZONE24:00:00read as midnight on every supported Python, and otherTIMEtext in hour 24 raisesValueError. Athena engine version 3 writes none of these forms (#1678).- For subclasses (private APIs):
_prepare_query()requiresparamstyleand a newengineargument;_build_start_query_execution_request()takes anenginekeyword; the new_build_execute_request()builds the request fromExecuteOptions; 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
sqlalchemyandaiosqlalchemyextras requiresqlalchemy>=2.0.52(was>=2.0.44in 4.4.0). From 2.0.52, SQLAlchemy'sNumericliteral processor checks that a value is a number, so withliteral_executeorliteral_bindsa non-numeric string in aNumericorFloatparameter raisesCompileErrorinstead of being written into the SQL, and a NumPy scalar such asnp.int64(7)in aNumericparameter raisesCompileError;Floatparameters render NumPy scalars as before. (#1600)
Removed deprecated APIs
pyathena.filesystem.s3_filesystem(), deprecated in 4.4.0, is removed; usepyathena.fs.s3_filesystem(). (#1497)S3FileSystemandAioS3FileSystemno longer takeconnection; it raisesTypeError, also asconnection=None. Usepyathena.fs.s3_filesystem(connection)(withAioS3FileSystemas the second argument for the async filesystem), or passclient=connection.s3_clientandretry_config=connection.retry_config. (#1497)- All arguments of
S3FileSystemandAioS3FileSystemare keyword-only; a positional argument raisesTypeError. A filesystem pickled or serialized by fsspec (to_json()/to_dict()) under 4.x withconnection=or with positional arguments cannot be loaded. (#1497) - A custom
filesystem_classof the S3FS cursors is created throughpyathena.fs.s3_filesystem()withclient,retry_config,default_block_sizeandskip_instance_cache=Trueinstead ofconnection, so it must acceptclientandretry_config. (#1497)
Queries and parameters
- An explicit
paramstylepassed to a cursor'sexecute()takes precedence overpyathena.paramstyle; before, the globalqmarkwon overparamstyle="pyformat". (#1508) pyathena.formatterno longer importsAthenaFileFormatandAthenaCompression; import them frompyathena.model. (#1602)
SQLAlchemy
- Connections. The dialect compiles statements for the engine of its connections. Without
engine_versionin the URL or the connect arguments, each new DB API connection sends itsGetWorkGrouprequest when it opens, including pooled connections used only for reflection or pings. A throttled or failed request fails the connection withOperationalErrorinstead of assuming an engine for the life of the SQLAlchemy engine, and a later connection whose workgroup reports another engine than the first one raisesOperationalError(#1678). - Reflection on Athena engine version 3 recognizes
time,uuid,timestamptz,timestamp with time zone,time with time zone,varbyte, andblobcolumns, which it used to reflect asNullTypewith a warning (#1678). - The SQLAlchemy dialects always use the
pyformatparameter style, whateverpyathena.paramstyleor aparamstylepassed tocreate_engine()is. Underpyathena.paramstyle = "qmark", the sync dialects sent the bound values as Athena execution parameters, and the async dialects sent%(name)splaceholders with doubled%. Now the cursor renders the bound values into the statement. Under the globalqmark,exec_driver_sql()statements must use%(name)splaceholders with a dict and write%as%%, and values passed totext()bind parameters are values, not SQL literal text ("abc", not"'abc'"). Theon_start_query_executionexecution option is also called for executemany statements and with theno_parametersexecution option. (#1508) CREATE TABLEquotes the keys and values ofawsathena_serdepropertiesandawsathena_tblpropertiesgiven as dicts (also inconnect_args), and thecompressionvalue, 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 thepyformatstyle (for example"\\\\"→"\\","it\\'s"→"it's","%%{SYSLOGBASE}"→"%{SYSLOGBASE}"). Thecompressionvalue replaces a property of the same name in atblpropertiesdict instead of rendering it twice. With theno_parametersexecution option, a%in a dict key or value reaches Athena doubled. String forms of these options,row_formatandfile_formatare unchanged. (#1484)CREATE TABLEvalidatesbucket_count,awsathena_partition_transform_bucket_countandawsathena_partition_transform_truncate_length: each must be a positive integer or a string of decimal digits, and another value raisesCompileError. A tableawsathena_bucket_countof0raises instead of falling back to the connection'sbucket_count; an Icebergbucketortruncatepartition transform without a valid argument, and an unknownpartition_transformname, raise instead of omitting the partition column. (#1531)CREATE TABLEtakes the baseLOCATIONand the S3 Tables catalog from the connection that initializes the dialect, as it takes the default schema, instead of from the connection URL andconnect_args. Withcreator=or ado_connecthandler, the table is created under that connection's S3 staging directory, an S3 Tables catalog on the connection omitsLOCATION, and a connection without a staging directory raisesCompileErrorunlesslocationis set. A statement compiled before the engine first connects uses the connection URL. A connection thatcreator=returns must exposes3_staging_dirandcatalog_namein addition toschema_nameandcursor_kwargs(otherwiseAttributeErrorat the first connect). New dialect propertiesdefault_s3_staging_diranddefault_catalog_name. (#1544, #1583)- An
Interval()column raisesCompileErrorin DDL, since Athena tables have no interval type, andIntervalis adapted to the new nativeAthenaInterval. Declare an existing column asInterval(native=False)to keep SQLAlchemy's emulation, which stores aTIMESTAMP. (#1630)
S3 filesystem
S3FileSystem.touch()andAioS3FileSystem.touch()return the PutObject response as botocore returns it, includingResponseMetadata, instead of a dictionary keyed by private attribute names (_etag).S3PutObject.to_dict()andS3CompleteMultipartUpload.to_dict()are keyed by the field names (etag). (#1435)- An
S3Coremethod raisesTypeErrorfor a parameter that it also sets from its other arguments, such asKeywith a path that has a key. Before,get_object,put_object, the multipart methods,list_object_annotationsandcopy_object_annotationdropped the parameter silently, andgenerate_presigned_url(and sosign()) signed it instead of the path's field. A file opened with such a parameter, such asKeyor aRangefor reading, raisesTypeErrorat its first request. (#1435) S3MapResult.outcomesis renamed toresults, andS3DeleteResult.raise_for_outcomes()toraise_for_errors(); no aliases are kept. (#1549)S3DeleteResulttakesdeleted_objects=as a keyword-only argument (the fields afterbucketare keyword-only),deletedis a read-only property derived fromdeleted_objectsand leavesdataclasses.fields()/asdict(), and results compare by their delete marker fields. Pickles of earlier results restore withoutdeleted_objects. (#1590)S3MultipartUploadPart.to_api_repr()requires the checksum algorithm;S3Object.to_api_repr()of a bucket or directory entry has noStorageClass;S3Object.directory()andS3Object.from_metadata()take noversion_id;S3Core.list_object_annotations()no longer resumes from aContinuationTokeninparams(it raisesTypeError);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()andsplit_trailing_separators()are removed. (#1615, #1664)fnis positional-only inS3Executor.submit(),submit_to(),run(),run_shielded()and thesubmit()ofS3ThreadPool, andfutureis positional-only insubmit_to(); a caller that passesfn=,self=orfuture=by keyword breaks, and keyword arguments with those names now reach the callable. (#1533, item 1)pipe_file()andput_file()(sync and aio) resolve and checkblock_sizeasopen(..., "wb")does, before any request:put_file(..., block_size=0)raisesValueError(omit it or passNonefor the default);pipe_file()of data up to the block size, outside a transaction, withblock_size=0or a value outside 5 MiB to 5 GiB, raises instead of sending one PutObject, and so does such a call on a filesystem whosedefault_block_sizeis outside the write limits unless a validblock_sizeis given. (#1611)pipe_file()(andpipe()with a mapping or a single path) of data up to the block size, outside a transaction, with amax_workersthat is not positive (pipe(): negative), raisesValueErrorinstead of sending one PutObject.cp_file(),copy()andmv()of a source up to 5 GiB with ablock_sizeoutside 5 MiB to 5 GiB (other than 0 orNone), or a negativemax_workers, raiseValueErrorbefore any request instead of sending one CopyObject. (#1629)pipe_file(),put_file()andget_file()address the key as written:s3://bucket/dir/writes or reads the keydir/, notdir, ands3://bucket//the key/(pipe_file()/put_file()no longer raiseValueErrorfor 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()andget_file()no longer go throughopen(), so a subclass'sopen()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()andput()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 whatfs.ls("s3://b/dir/")lists,rm(),cat(),copy(),get(),open()andglob()address the objectdir/, andS3Path("b", "/")is the key/, not the bucket. (#1664) - A subclass that sets
protocolreads every path with its own protocols only:s3://...raisesValueErroron a subclass whose protocols do not includes3, and so does a path that starts with another protocol after one of the class. (#1664) isfile()raisesValueErrorfor a path that is not an S3 path (fsspec and s3fs returnFalse), sokey in fs.get_mapper(root)raises for such a key.cat_ranges()raises theValueErrorof an invalid path before any read, also withon_error="return".copy(),mv(),get(),put(),pipe(),rm(),cat()andexpand_path()check every path, sources and destinations, before the first request. (#1664)- A path with two leading protocols, such as
s3://s3://bucket/keyors3::s3://bucket/key, raisesValueErrorbefore any request instead of namingbucket/keyin some methods, writes included. AnS3Pathwith a version but no key raisesValueError, also throughwith_version_id()andinfo("s3://bucket", version_id=...). (#1615)
Behavior changes
Queries and parameters
DefaultParameterFormatterquotes string parameters for the engine that parses each statement: a statement starting withCREATE EXTERNAL TABLEis always Hive DDL; onlySHOW DATABASES,PARTITIONS,SCHEMAS,TABLESandTBLPROPERTIESget the Hive escaper, and otherSHOWstatements the Trino escaper; keywords are recognized with comments between them, and a line comment also ends at a carriage return. ACREATE TABLEstatement containingASkeeps the Trino escaper, and a string value with an odd run of backslashes before a quote or at its end raisesProgrammingError. (#1507)- A float in a sequence parameter, such as
IN %(xs)s, renders withrepr()(0.1234567,1e-20) instead of"%f", which rounded to six decimal places. NaN and infinity render asnan(),infinity()and-infinity()in scalar, sequence and ARRAY parameters and in SQLAlchemy inline rendering, instead ofnan,infand-inf, which Athena reads as column names. A non-finite value with a%(x).2fformat raisesTypeError. (#1530) - On Athena engine version 3, a
timedeltaparameter renders asINTERVAL '[-]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'sQueryExecutionContextnames no catalog.cursor.catalog,result_set.catalogandAthenaQueryExecution.catalogare thenNone. 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 asAwsDataCatalog. 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'raisesProgrammingErrorbefore the query starts. A customFormatterreceives the inner query instead of the UNLOAD statement, and a customwrap_unload()receives the formatted query. The UNLOAD cursors no longer call the private_execute()(use_execute_query()). (#1589) to_sql()andgenerate_ddl()quote the names (backticks, doubled) and literals of the Hive DDL they write, andAthenaTableMetadata.row_format/file_formatescape class names. A partition value with a quote is registered as itself; a partition value that fits between neither quote raisesProgrammingErrorbefore any request; a partitionLOCATIONwith a quote or backslash is registered as the uploaded prefix. Withindex=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()typedNumeric/DECIMALwith a precision is cast, toDECIMAL(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 declaredimpl: for exampleD(Integer) / Integerrendersd / CAST(i AS DOUBLE)instead of casting toDECIMAL, andInteger / F(Float)casts both operands toDOUBLEinstead ofREAL. (#1635) Float,FLOATandREALare adapted to the newAthenaFloat, andDouble,DOUBLEandDOUBLE_PRECISIONtoAthenaDouble, whose literal processor renders a float by value and NaN and infinity as functions. (#1530)Numeric,NUMERICandDECIMALare adapted to the newAthenaNumeric: an inlineDecimal(literal_binds,literal_execute, ARRAY elements) renders asDECIMAL '5.52'on Athena engine version 3 instead of5.52, which Athena reads as DOUBLE. ADecimalwhose 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 asnan()/infinity(). A user subclass ofNumeric(not aFloat) is adapted toAthenaNumeric, so its own processors are no longer used; subclassAthenaNumericor use aTypeDecoratorto keep them. (#1573)- SQLAlchemy DDL writes a CR, LF or tab in a comment, a table or SerDe property, or a location as
\r,\nor\t. The private formatter functions_escape_trino,_escape_hive,_date_literal,_timestamp_literaland_float_literalare removed in favor of the public functions below. (#1550) - On SQLAlchemy 2.0, the elements of an ARRAY of a
Floattype withasdecimal=Trueare rounded todecimal_return_scale(10 digits unless set), as the column is:0.1becomesDecimal('0.1000000000'). On SQLAlchemy 2.1, those elements are returned as numbers instead of strings. (#1577) - A
dictcompared with or written to a MAP column renders asCAST(MAP(ARRAY[...], ARRAY[...]) AS MAP(k, v)), and a ROW value (adictwith the declared fields, or a tuple) asCAST(ROW(...) AS ROW(...)); both failed before. A tuple or list compared with a ROW column is cast to the declared ROW type, so aDecimalwith 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 whoseNumerichas no precision is bound without the cast. An emptyin_()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 throughzip_with(...)so the operand is evaluated outside the lambda; a scalar function such asfunc.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::ands3a::paths.unstrip_protocol("s3::bucket/key")returnss3://bucket/key. (#1615) copy(),mv()andget()pass their paths tocp_file()/get_file()without the protocol, also those of two lists, andpipe()passes anS3Pathtopipe_file().mv()of a path onto the same path in another spelling (s3://b/kands3a://b/k) returns before any request. A file'spathisstr()of itsS3Path,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 thannullnames the entrybucket/key?versionId=<id>, anddu(total=False)uses the same key.info()["version_id"]holds the version that HeadObject returns, also withoutversion_aware. (#1618)AioS3FileSystem._du()runsdu()in a thread, sowithdirs=Trueincludes the bucket, asS3FileSystem.du()does. (#1540)
S3 filesystem: batch operations
AioS3FileSystem'scopy,mv,cat(on_error="raise")andcat_ranges(on_error="raise")stop at the first failure, as the sync API does; they used to send every request. Itsbatch_sizehas the sync meaning (the call's value, else the filesystem's, elsemax_workers;-1meansmax_workers), and0and other negative values raiseValueErrorbefore any request.AioS3FileSystem.batch_sizeforwards to the internalS3FileSystem, so_rmfollows it.await _cat(path)of one unexpanded path raises the error of its read for everyon_errorvalue. (#1555)S3FileSystem.copy(on_error=X)skips a missing source only for"ignore".cat_rangesaccepts any iterable of starts and ends, andpipeany non-string object withitems(). (#1555)mvcopies a source without a version ID withCopySourceIfMatchon 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, andmvraises anOSErrorthat lists it withPreconditionFailedafter all deletions; a source that another client deleted is no error. Deleting on an ETag needss3:GetObjecton the source. ACopySourceIfMatchorCopySourceIfUnmodifiedSincegiven to a multipart copy (source over 5 GiB) is also sent to its HeadObject.S3DeleteResult.raise_for_errors()leaves outNoSuchKey. S3-compatible endpoints without per-object ETags in DeleteObjects orCopySourceIfMatchare 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'srequest_kwargs) yield to the fields that a request sets, such as a read'sRangeor a part'sPartNumber, instead of raisingTypeError.ContentMD5,ContentLengthand checksum values among them are sent with PutObject (and the checksums with the completion of aFULL_OBJECTupload), and no longer with parts, tagging, ACL or annotation requests.S3Core.create_bucket(),put_object_acl()andput_bucket_acl()no longer send the ACL or grants ofrequest_kwargs.S3Core.plan_multipart_copy()honors the directives, tags and metadata ofrequest_kwargs, and reads the source without the destination'sExpectedBucketOwner. (#1558) - A file that
S3File(fs, ...),AioS3File(fs, ...)orAioS3StreamedFile(fs, ...)creates directly takes the filesystem'sdefault_block_size,default_cache_typeands3_additional_kwargs; before, it used a 5 MiB block size, the"bytes"cache and only the authorization parameters. Files fromopen()are unchanged. (#1588) - With an explicit
EncodingType="url",S3Corelistings 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()andsetxattr()invalidate their path after any outcome. A request that finds an object missing evicts its cached entry; a read that fails withPreconditionFailedon 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), andmkdir(bucket/prefix)withallow_bucket_creation=True, send HeadBucket even when the bucket is cached. A write andinvalidate_cache("bucket/key")keep the cached HeadBucket lookup; useexists(bucket, refresh=True)orinvalidate_cache("bucket")to check the bucket again. Withmax_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 openS3Filecloses it first, so the final flush uploads the rest.open()with a codec returns anS3CompressedFileinstead of the codec's stream (such asgzip.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 interruptedclose()/commit()raisesS3WriteStateErrorinstead 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 aclose()concurrent with a failing directflush(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):
S3MultipartStateErroris an alias of the newS3WriteStateError. (#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 asOperationalError, 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 theEngineVersionof each query; otherwise the engine of the workgroup fromGetWorkGroup, cached per workgroup and connection (#1678).- Requests built for each engine: on Athena DuckDB, no
ResultConfiguration,ExecutionParameters, orUNLOAD, withProgrammingErrororNotSupportedErrorbefore the query instead of a service rejection (#1678). DuckDBParameterFormatterformatspyformatparameters as DuckDB literals (#1678);pyathena.engine.EngineProfileandconnect(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 inGetQueryResults(#1678). - The SQLAlchemy dialect compiles DDL, reflection, views, and DML for Athena DuckDB (#1678).
timedeltaparameters and the SQLAlchemyIntervaltype 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');Intervalresults read DuckDB's interval text and thepyarrow.MonthDayNanoof the Arrow cursor;cast(x, Interval())isCAST(x AS INTERVAL)(#1674, #1684).- Inline
Decimalvalues of the SQLAlchemy dialect (literal_binds,literal_execute, ARRAY/MAP/ROW leaves) keep their precision and scale on Athena DuckDB, written with the newpyathena.formatter.duckdb_decimal_literal()as bound values are (#1675, #1680). - SQLAlchemy decimal division on Athena DuckDB: a
Numericquotient is cast toDECIMAL(38, max(s1, s2)), the scale that version 3 gives it, from both operands, with the scale of a boundDecimalread 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 beforeFLOORas version 3 does (#1676, #1682, #1683, #1685). - Cancelling an asyncio query stops the
GetWorkGroupandGetQueryResultStreamretries, asdocs/aio.mdpromises (#1679, #1681).
Result fetchers
result_fetcheronconnect(),cursor(),execute(), andExecuteOptions:"auto","GetQueryResults","GetQueryResultStream", or"S3". A forced value never falls back and raisesProgrammingErrorwhen 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 andRangeresume (#1678):Cursor,DictCursor, and their Async and Aio variants read it one record batch at a time and convert the values with aStreamConverter(connect(stream_converter=...),cursor(stream_converter=...),pyathena.stream.converter), whose default gives the scalar values ofGetQueryResults(#1678).ArrowCursor,PandasCursor,PolarsCursor, and their Async and Aio variants read it into their tables and DataFrames,PandasCursorandPolarsCursorchunk by chunk withchunksize(#1678).
"auto", the default, readsGetQueryResultStreamwhen 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, andGetQueryResultsin 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) andinterval_literal()(#1630). - SQLAlchemy:
Intervalcolumns andtimedeltaoperands render as Athena INTERVAL values, and interval results are read astimedelta; MAP and ROW values can be bound and rendered. (#1630) ArrowCursor,AsyncArrowCursorandAioArrowCursortakes3_filesystem_kwargs, keyword arguments for thepyarrow.fs.S3FileSystemthat reads CSV results and UNLOAD Parquet, in the constructor (andcursor_kwargs) and inexecute(). (#1614)pyathena.filesystem.s3_writerexposesS3WriteSession,S3WriteStateandS3WriteStateError(the former private write session). (#1627)S3MultipartUpload.version_idandS3MultipartUploadPart.version_idkeep theVersionIdof CreateMultipartUpload, ListMultipartUploads, UploadPart and UploadPartCopy responses. (#1662)- New
S3Path.remove_protocol(),strip_protocol(),parent_name()andunstrip_protocol(), and theprotocolsargument ofS3Path.parse(). (#1615) - New
S3Core.with_request_kwargs()andS3MultipartCopyPlan.request_kwargs(#1558);S3ClientError.of()andS3ClientError.bucket_name(#1561);S3DeleteBatch(etags=...),S3DeleteBatch.from_paths(etags=...)andS3ClientError.is_copy_source_precondition_failed()(#1632).
Bug fixes
- Metadata requests (
get_table_metadata(),list_table_metadata(),list_databases()) and the Glue fallback nameAwsDataCatalogwhen neither the call nor the cursor has acatalog_name; botocore rejected the missingCatalogNamebefore. (#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 VIEWandCREATE TABLE AS(SQLAlchemy 2.1CreateView,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,skipandtrimare quoted in DML. (#1641)- The
any_match()/all_match()lambda variable avoids the names of the statement, including stored SELECTs of SQLAlchemy 2.1CreateViewandSelect.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 rendersany_match()for both. (#1648)
S3 filesystem
- An
AioS3StreamedFileread, or any othermap_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 closedautocommit=Falsefile whose latercommit()replaces the object with an empty one. (#1637) - Interrupted flushes, closes and writes of
S3Fileno 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 byversion_idsizes the key as written. (#1615)
Known limitations on Athena DuckDB
- One statement per query; no
qmarkparameters; nounload=True. cache_sizereuses no Athena DuckDB execution, because Athena DuckDB does not report aStatementType(the search still sends itsListQueryExecutionsandBatchGetQueryExecutionrequests).- A query whose result has an
ENUMcolumn fails with managed query results. - With
"GetQueryResultStream",FLOATvalues can differ from those ofGetQueryResultsfor some whole numbers between about 3e7 and 6e10, andPolarsCursorreadsHUGEINTandUHUGEINTasInt128andUInt128, 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
DOUBLEand 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 asa * a, keeps the scale of its SQLAlchemy type;//of decimals with scale 0 takesFLOORfirst (3 // 2inDECIMAL(2, 0)is 1, 2 on version 3). - SQLAlchemy
Interval: an interval with months or years has notimedeltaequivalent and raisesValueError(read it withcast(expression, String()));Date±timedeltais aTIMESTAMPon Athena DuckDB (aDATEon version 3).
Documentation
- New guides:
docs/duckdb.mdanddocs/upgrading.md; the result fetchers section ofdocs/usage.md; the Athena DuckDB section ofdocs/sqlalchemy.md(#1678). just test sqla-duckdbruns the SQLAlchemy compliance suite on an Athena DuckDB workgroup (#1678).docs/sqlalchemy.mdsays to pass the parameters of a statement with a time-travel hint on an alias toexecute(), sinceSelect.params()andSelect.unique_params()can drop the hint. (#1633)- The versioning and bucket-lifecycle examples of
docs/filesystem.mduses3_filesystem(connection, ...). (#1548)
What's Changed
- Record the filesystem re-measurement of 2026-11-15 (GH-1332) by @laughingman7743 in #1420
- Act on listed identities in expansion, lookups, invalidation and fan-outs (GH-1402) by @laughingman7743 in #1414
- Act on listed identities in pairing and copy/mv/get (GH-1403) by @laughingman7743 in #1421
- Resolve Furo only where a fixed soupsieve installs by @laughingman7743 in #1428
- Reject conflicting pairs in the batch coroutines of AioS3FileSystem (GH-1398) by @laughingman7743 in #1422
- Look up every conflicting source of a move, as of a copy (GH-1397) by @laughingman7743 in #1423
- Type put destinations and document path addressing (GH-1404) by @laughingman7743 in #1426
- Remove and rewrite the core, executor, reader and init filesystem tests (GH-1328) by @laughingman7743 in #1430
- Make the filesystem package independent of the rest of PyAthena (GH-1388) by @laughingman7743 in #1431
- Make S3Object a dict subclass and return copies of cached entries (GH-1382) by @laughingman7743 in #1433
- Pair, check and expand the paths of get() and cat() alike in both filesystems (GH-1425) by @laughingman7743 in #1432
- Consolidate the S3 response models and return the copy and delete results (GH-1383) by @laughingman7743 in #1434
- Share the upload body of put_file() with the async transaction write and window the async batch transfers (GH-1427) by @laughingman7743 in #1438
- Derive the default CREATE TABLE location from the statement's cursor options (GH-1440) by @laughingman7743 in #1443
- Return what fsspec returns from the async _get() and a _put() that uploads nothing (GH-1429) by @laughingman7743 in #1441
- Own the listing cache keys and invalidation in one cache object (GH-1384) by @laughingman7743 in #1442
- Remove, rewrite, and add test_s3.py tests from the filesystem test audit (GH-1328) by @laughingman7743 in #1451
- Reflect the default database when the cursor has no schema (GH-1445) by @laughingman7743 in #1448
- Apply schema_translate_map to SQLAlchemy DDL statements (GH-1439) by @laughingman7743 in #1444
- Remove the filesystem's test seams and dead code (GH-1452) by @laughingman7743 in #1466
- Finish the filesystem test audit leftovers (GH-1458) by @laughingman7743 in #1462
- Read the version named by a VersionId parameter of open() (GH-1437) by @laughingman7743 in #1463
- Ignore cached parameterized lookups that an invalidation evicted (GH-1459) by @laughingman7743 in #1471
- Return None for path-like sources of only directories from AioS3FileSystem._get() and _put() (GH-1470) by @laughingman7743 in #1476
- Add coroutine forms and s3fs attributes to AioS3FileSystem (GH-1457) by @laughingman7743 in #1468
- Render the filter() lambda text when the statement runs (GH-1449) by @laughingman7743 in #1464
- Download the requested version of a get() source whose name is a prefix (GH-1467) by @laughingman7743 in #1479
- Evict the cached entries below a bucket that is created or deleted (GH-1460) by @laughingman7743 in #1477
- Quote dict SerDe and table properties as string literals (GH-1447) by @laughingman7743 in #1484
- Keep the precision and scale of DECIMAL division operands (GH-1450) by @laughingman7743 in #1465
- Add a differential check for changes to shared behavior to the workflow (GH-1488) by @laughingman7743 in #1489
- Keep the slashes that end a version ID in path strings (GH-1469) by @laughingman7743 in #1481
- Set the dialect's default schema to the cursor's database (GH-1446) by @laughingman7743 in #1478
- Pair tuples as lists and align put() progress with _put() (GH-1482) by @laughingman7743 in #1498
- Remove the filesystem's connection argument and the deprecated s3_filesystem (GH-1386) by @laughingman7743 in #1497
- Move the filesystem helpers to the objects they operate on (GH-1453) by @laughingman7743 in #1480
- Return the raw touch() response and settle one request parameter rule (GH-1383) by @laughingman7743 in #1435
- Remove only the leading serde.param. prefix from SerDe property names (GH-1486) by @laughingman7743 in #1501
- Quote parameters for the engine that parses each DDL statement by @laughingman7743 in #1507
- Run SQLAlchemy statements in pyformat under the global qmark (GH-1485) by @laughingman7743 in #1508
- Provision the AWS test session only for the tests that use it (GH-1512) by @laughingman7743 in #1515
- Reject get() files that other destinations lie below and keep folder markers as directories (GH-1487) by @laughingman7743 in #1516
- Validate the integer options of SQLAlchemy CREATE TABLE (GH-1473) by @laughingman7743 in #1531
- Render float parameters and literals without rounding or bare NaN by @laughingman7743 in #1530
- Read the DDL staging directory and catalog from the first connection (GH-1499) by @laughingman7743 in #1544
- Store an empty S3Path version ID as None (GH-1509) by @laughingman7743 in #1534
- Share one walk body and take du() sizes from the listed entries (GH-1519) by @laughingman7743 in #1540
- Make the S3Executor call contract consistent (GH-1472) by @laughingman7743 in #1533
- Keep writes from destroying or mixing object data by @laughingman7743 in #1535
- Fix the write session's abort, queued creation, and last part (GH-1526) by @laughingman7743 in #1537
- Keep the response fields, page directory-bucket uploads, and fix S3Object copies (GH-1527) by @laughingman7743 in #1545
- Add an offline test target that no AWS account authorizes (GH-1495) by @laughingman7743 in #1532
- Select request parameters correctly for correct calls by @laughingman7743 in #1548
- Fix the read path of S3 files (GH-1517) by @laughingman7743 in #1541
- Look up the object that cp_file() copies, and leave the bucket out of a recursive copy (GH-1510) by @laughingman7743 in #1538
- Share the Hive and Trino literal functions as public formatter functions by @laughingman7743 in #1550
- Run the tests that need no AWS without the live fixtures (GH-1514) by @laughingman7743 in #1557
- Evict cached entries that failed writes and requests show to be stale (GH-1523) by @laughingman7743 in #1536
- Reject writelines() of AioS3StreamedFile (GH-1517) by @laughingman7743 in #1556
- Render the time-travel hint of an aliased table before its alias by @laughingman7743 in #1547
- Compile update() on SQLAlchemy 2.1 (GH-1563) by @laughingman7743 in #1566
- Move the test connection helpers to tests/pyathena/util.py and remove duplicate offline tests (GH-1513, GH-1564) by @laughingman7743 in #1567
- Read a version ID query only after a key, and not as a glob (GH-1491) by @laughingman7743 in #1551
- Commit an open S3File by closing it first, close it in discard(), and close compressed files of open() (GH-1518) by @laughingman7743 in #1539
- Take SQLAlchemy DDL options in connect_args from the first connection (GH-1542) by @laughingman7743 in #1559
- Rename S3MapResult.outcomes to results and raise_for_outcomes to raise_for_errors (GH-1500) by @laughingman7743 in #1549
- Render inline Decimal values as Athena DECIMAL literals (GH-1483) by @laughingman7743 in #1573
- Invalidate the cache at the commit sites only once the request was sent (GH-1562) by @laughingman7743 in #1579
- Let inherited request parameters yield to the fields of each request by @laughingman7743 in #1558
- Check that verify, use_ssl and duration_seconds reach the clients and the STS requests (GH-1580) by @laughingman7743 in #1581
- Treat directory-bucket access points as directory buckets (GH-1529) by @laughingman7743 in #1585
- Store S3DeleteResult's deleted objects and settle model cleanups (GH-1529) by @laughingman7743 in #1590
- Keep no default schema from a connection that fails to initialize the dialect (GH-1572) by @laughingman7743 in #1583
- Resolve the open defaults in the file initializers (GH-1454) by @laughingman7743 in #1588
- Answer the role tests' AssumeRole with STSResponder instead of patching Connection._assume_role (GH-1596) by @laughingman7743 in #1597
- Give the final flush, close, and close without commit of AioS3StreamedFile one owner (GH-1546) by @laughingman7743 in #1593
- Decode the keys of URL-encoded listings in S3Core (GH-1529) by @laughingman7743 in #1599
- Share the single-object copy and copy every annotation of a committed destination (GH-1520) by @laughingman7743 in #1587
- Quote view reflection names and the UNLOAD destination, and format before wrapping in UNLOAD (GH-1506) by @laughingman7743 in #1589
- Decode float ARRAY elements and import the compliance suite on SQLAlchemy 2.1 (GH-1569) by @laughingman7743 in #1577
- Require SQLAlchemy 2.0.52 (GH-1574) by @laughingman7743 in #1600
- Evict a missing bucket's cached entries, check mkdir() uncached, and keep max_paths entries (GH-1492) by @laughingman7743 in #1561
- Run the aio batch operations with the sync failure policy (GH-1456) by @laughingman7743 in #1555
- Fix found defects in the current PR instead of only filing them by @laughingman7743 in #1617
- Quote the names and literals of the Hive DDL that to_sql() and generate_ddl() write (GH-1474) by @laughingman7743 in #1602
- Name explicit versions in info() and record HeadObject's VersionId (GH-1529) by @laughingman7743 in #1618
- Keep the ARRAY lambda variable from capturing names in stored and ordinary SELECTs (GH-1571) by @laughingman7743 in #1612
- Check the block size of pipe_file and put_file as open() checks it (GH-1592) by @laughingman7743 in #1611
- Name the catalog in the query context only when it is not AwsDataCatalog (GH-1604) by @laughingman7743 in #1624
- Pass pyarrow S3FileSystem keyword arguments through ArrowCursor (GH-1595) by @laughingman7743 in #1614
- Declare the operator classes of the Athena temporal, MAP and ROW types (GH-1570) by @laughingman7743 in #1607
- Remove one protocol, s3:: included, from the paths of every method, and reject an S3Path version without a key (GH-1491) by @laughingman7743 in #1615
- Drain a stopped batch before its map raises, and wait for the running calls after an interrupt (GH-1613) by @laughingman7743 in #1622
- Place a time-travel hint before a generated alias and accept irregular whitespace (GH-1575) by @laughingman7743 in #1582
- Make the write session public and share the file drivers (GH-1455) by @laughingman7743 in #1627
- Check max_workers of pipe_file and the multipart options of cp_file before any request (GH-1619) by @laughingman7743 in #1629
- Classify a TypeDecorator division operand by its impl by @laughingman7743 in #1635
- Say to pass parameters to execute() for a selected alias with a time-travel hint (GH-1576) by @laughingman7743 in #1633
- Delete only the copied source objects in mv (GH-1521) by @laughingman7743 in #1632
- Quote CREATE VIEW, DROP VIEW, and CREATE TABLE AS names for Trino (GH-1609) by @laughingman7743 in #1631
- Evaluate ARRAY quantifier operands with subqueries or functions outside the lambda (GH-1621) by @laughingman7743 in #1636
- Quote the Trino reserved words that Athena's SELECT list lacks (GH-1634) by @laughingman7743 in #1641
- Keep an interrupted discard() from committing an empty object (GH-1628) by @laughingman7743 in #1637
- Evict the cached entries that a fresh result contradicts (GH-1525) by @laughingman7743 in #1626
- Test SQLAlchemy offline on the declared minimum and the latest release (GH-1543) by @laughingman7743 in #1620
- Render timedelta, MAP, and ROW values as Athena literals (GH-1616) by @laughingman7743 in #1630
- End a hint's trailing line comment with a line break by @laughingman7743 in #1644
- Keep the caller's function when compiling a function comparison with an ARRAY quantifier by @laughingman7743 in #1648
- Address the key as written in pipe_file, put_file and get_file (GH-1511) by @laughingman7743 in #1645
- Keep interrupted writes, closes, and hand-overs of S3File from committing partial data or waiting forever (GH-1638) by @laughingman7743 in #1646
- Keep the VersionId of multipart upload responses (GH-1660) by @laughingman7743 in #1662
- Require boto3 and botocore 1.44.17 by @laughingman7743 in #1665
- Fix the MAP and ROW regressions against 4.4.0 from #1630 (GH-1657) by @laughingman7743 in #1661
- Evaluate the BETWEEN bounds of an ARRAY quantified comparison outside the lambda by @laughingman7743 in #1658
- Keep the justfile readable by just releases before 1.40.0 (GH-1666) by @laughingman7743 in #1667
- Convert every path once through the filesystem's entry (GH-1491) by @laughingman7743 in #1664
- Support the Athena DuckDB engine by @laughingman7743 in #1678
- Keep the scale of inline Decimal values on Athena DuckDB by @laughingman7743 in #1680
- Type a decimal quotient on Athena DuckDB from both operands by @laughingman7743 in #1683
- Stop the GetWorkGroup and GetQueryResultStream retries of a cancelled asyncio task by @laughingman7743 in #1681
- Give a DuckDB decimal quotient the scale of its bound values by @laughingman7743 in #1685
- Write and read intervals as Athena DuckDB does by @laughingman7743 in #1684
- Link the Athena User Guide pages on Athena DuckDB by @laughingman7743 in #1686
- Make the synchronous test_cancel and a DuckDB GetWorkGroup call robust by @laughingman7743 in #1688
Full Changelog: v4.3.0...v5.0.0