Skip to main content
Welcome to AbstraOverviewAuthenticationOverviewTreasury DashboardAuthenticated Task ManagerExpense Submission FormSystem Status MonitorFiltered Orders TableStreaming Progress BarStreaming File DownloadStreaming Video with Media Source ExtensionsFile uploads in PagesGetUserFailedget_query_paramsget_userregister_staticOverviewBasicsExternal DataReactive PagesPre-filled fieldsRedirectCustom ValidationProgress BarCustom ButtonsGetting User InformationQuery ParametersCRUD with DatabaseClient-side JavaScriptOverviewAppointmentInputCardsInputCheckboxInputChecklistInputCnpjInputCodeInputCpfInputCurrencyInputCustomInputDateInputDropdownInputEmailInputOverviewCameraInputImageInputVideoInputListInputMultipleChoiceInputNpsInputNumberInputNumberSliderInputPandasRowSelectionInputPasswordInputPhoneInputRatingInputRichTextInputRowTagInputTextInputTextareaInputTimeInputToggleInputOverviewFileOutputHtmlOutputIframeOutputImageOutputLatexOutputLinkOutputMarkdownOutputPandasOutputPlotlyOutputProgressOutputTextOutputStep TypesAuthenticationForm SettingsNotificationsHome Page and SidebarOverviewBackButtonExitButtonNextButtonend_page_stepexecute_jsget_query_paramsget_userListItemSchemarunWidgetOverviewBasic HookReceiving Connector EventsReceiving EmailsTriggering Hooksget_email_requestget_raw_requestget_requestsend_jsonsend_responseJobsOverviewSending a taskGetting and using TasksIterate through tasksGet trigger task (Tasklet)TaskletsTask Schema Validationget_sent_tasksget_tasksget_trigger_taskiter_taskssend_taskTaskOverviewPrompt ConstructionToolsExamplesWorkflowAgentsPromptingFixed answer formatReading an InvoiceParsing DocumentsOverviewBrowserToolsConnectorsToolsFilesToolsTablesToolsextract_textparse_bank_statementparse_boletoparse_invoiceparse_nfeparse_nfseparse_oficiosparse_us_driver_licenseparse_us_passportpromptrun_agentOverviewCreating and Loading FilesPublic Filesget_persistent_dirget_public_dirOverviewThe custom actionrun_connection_actionDatabricksItaú ExtratosOverviewConsultasEmissão de NFS-eEventos de NFS-eTroubleshootingGoogle DriveOverviewEnvio de Lote de RPS (Versão 2)Itaú VAN (SFTP)OverviewReading dataSupplier invoice (MIRO)Bank statementTransactional sessionsValue helpsTroubleshootingAbstra Cash ConnectOverviewIssuing an NF-eEvents: Cancellation and Correction LetterTroubleshootingBlingBradescoOverviewAttaching Files to NetSuite RecordsRetrieving and Updating Files in NetSuiteSearching Files Attached to RecordsSearching Files in NetSuite File CabinetUploading Files to NetSuite File CabinetCreating Custom Reports with NetSuite Purchase OrdersCreating Purchase Orders and Attaching Files in NetSuiteFiltering Purchase Orders by Custom FieldsReading Purchase Order Line ItemsReading Purchase Order DetailsSearching and Filtering Purchase OrdersOverviewGetting Invoice Details and TransactionsListing and Searching Invoices99Abstra Manager APIAbstra Project APIADN NFS-eAdyenAnchorage DigitalAsaasAmazon Web ServicesMicrosoft AzureBanco ABCBanco do BrasilBanrisulBase ChainBanco Central do BrasilBetha e-Nota CloudBigDataCorpBinanceBitstampBlingBotConversaBradescoBrasil APIBrazeBrexBS2BTG Pactual Empresas (Custom App)BTG Pactual EmpresasAbstra Cash ConnectCelcoinCerttaCielo e-CommerceCielo EDI LinkCielo Extrato EletrônicoCieloClaraClicksignClickUpCNJ - DataJudCNJ - Domicílio Judicial EletrônicoCNJ - Diário de Justiça Eletrônico NacionalCobranSaaSCoinbase CDPCoinbase Commerce (Business)Coinbase Exchange / Prime / INTX / Derivatives (HMAC)ConfluenceConfluence (API Token)Conta AzulConta SimplesMicrosoft Copilot Studio (Custom App)CresolCRS 360Databricks AccountDatabricks WorkspaceDatatravelData Rudder (DeLorean)DFNSDiscordDocuSign (JWT)DocuSignDynamics 365 Business CentralenContacteNotas GatewayEquals ConnectEthereumFirecrawlFiservFlashFlukeFoxbitFreshserviceGoogle Cloud PlatformGitHub (Personal Access Token)GitHubGmailGoogle AnalyticsGoogle BigQuery (Service Account)Google BigQueryGoogle Calendar (Service Account)Google CalendarGoogle Chat (Service Account)Google ChatGoogle Docs (Service Account)Google DocsGoogle Drive (Service Account)Google DriveGoogle Maps (Service Account)Google Maps (API Key)Google MapsGoogle Sheets (Service Account)Google SheetsGranatumGRF/OFMHi PlatformHolmesHubSpotIBGEiFoodInfosimplesBanco InterIntercomItaú BoletosItaú ExtratosItaú Pagamentos (SISPAG)Itaú PixItaú VAN (SFTP)IuguJD Pagamentos InstantâneosJiraJira (API Token)KommoKraken DerivativesKraken SpotLinkedInLinx OMALitecoinLookerMagaluMailchimpMCPMega ERPMercado BitcoinMercado LivreMercado PagoMercosMetabaseMicrosoft 365 Copilot (Custom App)Microsoft BookingsMicrosoft ExcelMicrosoft OneNoteMicrosoft Outlook (Service Principal)Microsoft OutlookMicrosoft PlannerMicrosoft SharePoint + OneDrive (Service Principal)Microsoft SharePoint + OneDriveMicrosoft Teams (Service Principal)Microsoft TeamsMicrosoft To DoMonday.comMXM WebManagerMySQLNektnetLexNetSuite OAuth2NetSuite TBANexxera - Nix EmpresasNexxera - Nix PayNF-e São PauloNordVPNNota BarueriNota PaulistanaNota SalvadorNotionNotion (API Token)NuPayOKXOlist EcommerceOlist ERPOmie ERPOneStreamOnFlyOracle E-Business SuiteOracle DatabasePagarePagar.mePagBank EDIPagSeguroPayPalPipedrivePipedrive (API Token)PipefyPodioPolygonPostgreSQLPostmanProJuris EmpresasProJurisQiveQuickBooksRappiRDP (Windows Remote)Recall.aiReceita Federal - Apuração Assistida CBSReceiv BIRedecard (e.Rede)Amazon RedshiftRevolut BusinessRevolut MerchantRevolut Open BankingSabespSafeguardSalesforceSankhyaSantanderSAP ABAP Development Tools (ADT)SAP Cloud ConnectorSAP ConcurSAP CPI (Integration Suite)S/4HANASAP Service LayerSBA CertificationsSentrySerproSerpro Integra ContadorSFTPShopify StorefrontShopifySicoobSicrediSiengeBanco Central do Brasil - SiscomSlack (API Token)SlackSnowflakeSolanaSQL ServerBanco Central do Brasil - STA (Sistema de Transferência de Arquivos)Stark BankStripe (API Key)StripeSVB (Silicon Valley Bank)Takotl;dvTodoistTotal BankTotalPassTotvsTravellinkConsumo de Tributos GovTRONTypeformTyxterUAUWeb (Globaltec)UberVERT CapitalVindiVórtx VxRecebíveisVórtxVTEXWhatsApp BusinessWhatsApp Business (API Token)WhatsApp (RPA)WoofficeWoopayXP InvestimentosXRP Ledger (Ripple)YunoZé DeliveryZendeskZendesk (API Token)OverviewInserting rowsSelecting rowsUpdating rowsDeleting dataUsing SQLUsing comparatorsImporting & Exporting Datadelete_by_idinsertis_betweenis_eqis_gtis_gteis_ilikeis_inis_likeis_ltis_lteis_neqis_not_ilikeis_not_inis_not_likeis_not_nullis_nullquery_dfrunrun_sqlselectselect_by_idselect_dfselect_oneTablesExecutionErrorupdateupdate_by_idBuilt-in TablesTransactionsOverviewDeclaring actionsabstra.servicesOverviewExamplesOverviewSingle Sign-On (SSO)Environment VariablesOverviewUsing Abstra LoggerOverviewExamplessend_emailUI PreferencesRetrieving Project URLRetrieving Run IDPublishingUsing Legacy Threads
Cloud Console

Transactions

Use with tables.transaction(): to run multiple Tables operations as one unit: either all their transactional database changes are committed, or none are. This is useful when updating related rows must not leave your data partially changed.

Using the existing Tables functions​

transaction() takes no arguments. Inside the block, use the same Tables functions, parameters, and return values as outside it: insert, select, select_one, select_by_id, select_df, update, update_by_id, delete, delete_by_id, and run_sql.

Each call runs immediately in the same database transaction. You can use its result in the next call or make a decision in Python. The context manager does not return a transaction object; continue calling tables directly.

For example, create a version and make it the active version for its base. Before running this example, create a versions table with base_id (text) and active (boolean) columns, in addition to its default id column.

from abstra import tables base_id = "monthly-payments" with tables.transaction(): version = tables.insert("versions", {"base_id": base_id, "active": False}) tables.run_sql( "UPDATE versions SET active = (id = $1) WHERE base_id = $2", [version["id"], base_id], )

The insert returns the new row immediately, including its id. Both changes are committed when the block exits normally. Outside a transaction block, Tables functions keep their usual behavior.

A returned row does not mean it has been committed yet. Do not report success or trigger actions that depend on the changes until the block has exited successfully.

Commit and rollback​

  • A normal exit commits all the block's transactional Tables changes.
  • An exception escaping the block rolls those changes back and propagates the original exception.
  • A failed Tables call, including an invalid argument or a SQL constraint violation, prevents the block from committing even if you catch its exception inside the block. Further Tables operations cannot continue that transaction; exiting it raises TablesTransactionError with state == "aborted".

For example, an application validation error undoes an insert:

from abstra import tables try: with tables.transaction(): tables.insert("versions", {"base_id": "monthly-payments", "active": False}) raise ValueError("The new version did not pass validation") except ValueError: print("Validation failed; the inserted version was not committed")

Catch errors outside the block when you want to handle a failed transaction. Catching a Python exception inside the block does not itself force rollback if all Tables calls succeeded.

The transaction covers Tables database operations only. It does not undo Python variables, sent emails, connector calls, file changes, or other external effects. PostgreSQL effects that are not transactional, such as advancing a sequence, are not undone either.

Handling transaction errors​

Import TablesTransactionError from abstra.tables. Its state attribute describes the transaction outcome when a transaction request fails:

StateMeaning
unknownThe commit could not be confirmed. The changes may already have been committed.
committedThe block committed, but a later Tables call using its old context did not run.
aborted, rolled_back, unavailable, activeThe affected transaction's changes were not committed. active can occur when a nested transaction is rejected; it does not end the outer transaction by itself.

Ordinary Python exceptions and errors from individual Tables calls can also propagate; not every error is a TablesTransactionError.

from abstra import tables from abstra.tables import TablesTransactionError try: with tables.transaction(): tables.insert("versions", {"base_id": "monthly-payments", "active": False}) except TablesTransactionError as error: if error.state == "unknown": print("Commit outcome unknown; verify the stored data before taking further action") elif error.state == "committed": print("The block committed, but a late Tables call did not run") else: print("The transaction did not commit:", error)

If the connection fails while confirming the commit, rollback cannot be guaranteed. The SDK does not automatically replay transaction operations or commit requests. Verify the outcome using application-specific identifiers before deciding whether another attempt is safe.

Limits and supported SQL​

  • Keep transactions short. The backend rolls back transactions left idle for about 60 seconds or open for 5 minutes. Avoid user input, long-running computation, and network calls inside the block.
  • Nested transaction blocks and savepoints are not supported.
  • Use the transaction in the thread that opened it. Calls from threads that copy its context, such as asyncio.to_thread, are rejected. A separate thread does not automatically join the transaction. Do not run concurrent operations or let tasks created inside the block use its context after the block has ended.
  • Inside a transaction, run_sql accepts one statement per call: SELECT, INSERT, UPDATE, DELETE, or MERGE. Schema changes, explicit transaction control (BEGIN, COMMIT, ROLLBACK, SAVEPOINT), set_config, and system catalog access are not allowed. Let the context manager control commit and rollback.
  • Transactions require a backend that supports them. An older backend produces a clear incompatibility error (TablesTransactionError with state == "unavailable"); the SDK never falls back to separately committed calls.

Atomicity is not idempotency and does not by itself prevent conflicting business decisions from concurrent transactions. Use appropriate database constraints and application-specific concurrency rules; this API does not provide a separate lock-by-key or automatic retry feature.