Comandi di gestione delle sessioni di PGAdapter

Spanner PGAdapter supporta le istruzioni di gestione delle sessioni, che consentono di modificare stato e comportamento della connessione, eseguire transazioni ed eseguire in modo efficiente batch di istruzioni. Tutte le istruzioni descritte in questo documento possono essere utilizzate con qualsiasi client o driver che si collega a PGAdapter.

Per ulteriori informazioni, consulta l'elenco completo dei driver PostgreSQL e gli ORM supportati. I comandi seguenti si applicano ai database di dialetti PostgreSQL.

Per ulteriori informazioni sull'uso di PGAdapter, consulta Avviare PGAdapter.

Istruzioni di connessione

Le seguenti istruzioni apportano modifiche o mostrano le proprietà della connessione attuale.

SPANNER.READONLY

Un valore booleano che indica se la connessione è in modalità di sola lettura o meno. Il valore predefinito è false.

SHOW [VARIABLE] SPANNER.READONLY
SET SPANNER.READONLY {TO|=} { true | false }

Puoi modificare il valore di questa proprietà solo quando non ci sono transazioni attive.

▶ Esempio: transazione di sola lettura (fai clic per espandere)
L'esempio seguente mostra come utilizzare questa proprietà per eseguire transazioni di sola lettura in Spanner.

SET SPANNER.READONLY = TRUE;
-- This transaction is a read-only transaction.
BEGIN TRANSACTION;

-- The following two queries both use the read-only transaction.
SELECT first_name, last_name
FROM singers
ORDER BY last_name;

SELECT first_name, last_name
FROM albums
ORDER BY title;

-- This shows the read timestamp that was used for the two queries.
SHOW SPANNER.READ_TIMESTAMP;

-- This marks the end of the read-only transaction. The next statement will
-- start a new read-only transaction.
COMMIT;

COMMERCIO AUTOMATICO

Un valore booleano che indica se la connessione è in modalità di commit automatico o meno. Il valore predefinito è true.

NOTA: in genere non è necessario modificare il valore di questa variabile se si utilizza un driver PostgreSQL con PGAdapter. Questi driver gestiscono le transazioni automaticamente per te eseguendo BEGIN e COMMIT se necessario. Puoi disattivare autocommit quando utilizzi strumenti a riga di comando come psql per impedire l'esecuzione automatica del commit di modifiche accidentali dei dati.

SHOW [VARIABLE] AUTOCOMMIT
SET AUTOCOMMIT {TO|=} { true | false }

Puoi modificare il valore di questa proprietà solo quando non ci sono transazioni attive.

Se AUTOCOMMIT viene impostato su false, viene avviata automaticamente una nuova transazione dopo che hai eseguito COMMIT o ROLLBACK. La prima istruzione che esegui avvia la transazione.

▶ Esempio: commit automatico (fai clic per espandere)
L'esempio seguente mostra come utilizzare la proprietà autocommit.

-- The default value for AUTOCOMMIT is true.
SHOW AUTOCOMMIT;

-- This insert statement is automatically committed after it is executed, as
-- the connection is in autocommit mode.
INSERT INTO T (id, col_a, col_b) VALUES (1, 100, 1);

-- Turning off autocommit means that a new transaction is automatically started
-- when the next statement is executed.
SET AUTOCOMMIT = FALSE;
-- The following statement starts a new transaction.
INSERT INTO T (id, col_a, col_b) VALUES (2, 200, 2);

-- This statement uses the same transaction as the previous statement.
INSERT INTO T (id, col_a, col_b) VALUES (3, 300, 3);

-- Commit the current transaction with the two INSERT statements.
COMMIT;

-- Transactions can also be executed in autocommit mode by executing the BEGIN
-- statement.
SET AUTOCOMMIT = FALSE;

-- Execute a transaction while in autocommit mode.
BEGIN;
INSERT INTO T (id, col_a, col_b) VALUES (4, 400, 4);
INSERT INTO T (id, col_a, col_b) VALUES (5, 500, 5);
COMMIT;

SPANNER.RETRY_ABORTS_INTERNALLY

Un valore booleano che indica se la connessione ripristina automaticamente le transazioni interrotte. Il valore predefinito è true.

SHOW [VARIABLE] SPANNER.RETRY_ABORTS_INTERNALLY
SET SPANNER.RETRY_ABORTS_INTERNALLY {TO|=} { true | false }

Puoi eseguire questo comando solo dopo l'avvio di una transazione (vedi BEGIN [TRANSACTION | WORK]) e prima che vengano eseguite eventuali istruzioni all'interno della transazione.

Quando abiliti SPANNER.RETRY_ABORTS_INTERNALLY, la connessione conserva un checksum di tutti i dati che la connessione restituisce all'applicazione client. Viene utilizzato per riprovare la transazione se viene interrotta da Spanner.

Questa opzione è abilitata per impostazione predefinita. Ti consigliamo di disattivare questa impostazione se la tua applicazione proverà già a eseguire di nuovo le transazioni interrotte.

SPANNER.AUTOCOMMIT_DML_MODE

Una proprietà STRING che indica la modalità di commit automatico per le istruzioni Data Manipulation Language (DML).

SHOW [VARIABLE] SPANNER.AUTOCOMMIT_DML_MODE
SET SPANNER.AUTOCOMMIT_DML_MODE {TO|=} { 'TRANSACTIONAL' | 'PARTITIONED_NON_ATOMIC' }

I valori possibili sono:

  • In modalità TRANSACTIONAL, il driver esegue le istruzioni DML come transazioni atomiche separate. Il driver crea una nuova transazione, esegue l'istruzione DML e, al termine dell'esecuzione, esegue il commit della transazione o ne esegue il rollback in caso di errore.
  • In modalità PARTITIONED_NON_ATOMIC, il driver esegue istruzioni DML come istruzioni di aggiornamento partizionate. Un'istruzione di aggiornamento partizionata può essere eseguita come una serie di molte transazioni, ciascuna delle quali copre un sottoinsieme di righe interessate. L'istruzione partizionata fornisce una semantica indebolita in cambio di una migliore scalabilità e prestazioni.

Il valore predefinito è TRANSACTIONAL.

▶ Esempio: DML partizionato (fai clic per espandere)
L'esempio seguente mostra come eseguire il DML partizionato utilizzando PGAdapter.

-- Change autocommit DML mode to use Partitioned DML.
SET SPANNER.AUTOCOMMIT_DML_MODE = 'PARTITIONED_NON_ATOMIC';

-- Delete all singers that have been marked as inactive.
-- This statement is executed using Partitioned DML.
DELETE
FROM singers
WHERE active=false;

-- Change DML mode back to standard `TRANSACTIONAL`.
SET SPANNER.AUTOCOMMIT_DML_MODE = 'TRANSACTIONAL';

STATEMENT_TIMEOUT

Una proprietà di tipo STRING che indica il valore di timeout attuale per le istruzioni.

SHOW [VARIABLE] STATEMENT_TIMEOUT
SET STATEMENT_TIMEOUT {TO|=} { '<int8>{ s | ms | us | ns }' | <int8> | DEFAULT }

Il valore int8 è un numero intero seguito da un suffisso che indica l'unità di tempo. Un valore DEFAULT indica che non è impostato alcun valore di timeout. Se è stato impostato un valore di timeout dell'istruzione, le istruzioni che impiegano più tempo rispetto al valore di timeout specificato causeranno un errore di timeout e invalideranno la transazione.

Le unità di tempo supportate sono:

  • s: secondi
  • ms: millisecondi
  • us: microsecondi
  • ns: nanosecondi

Il valore di DEFAULT è pari a 0 secondi, il che significa nessun timeout. Un numero int8 senza unità indica int8 ms. Ad esempio, i comandi seguenti impostano entrambi il timeout dell'istruzione su 2 secondi.

SET STATEMENT_TIMEOUT TO 2000;
SET STATEMENT_TIMEOUT TO '2s';

Un timeout di istruzione durante una transazione invalida la transazione; tutte le istruzioni successive nella transazione invalidata (tranne ROLLBACK) hanno esito negativo.

READ_ONLY_STALENESS

Una proprietà di tipo STRING che indica l'impostazione di inattività di sola lettura attuale utilizzata da Spanner per le query e le transazioni di sola lettura in modalità AUTOCOMMIT.

SHOW [VARIABLE] SPANNER.READ_ONLY_STALENESS
SET SPANNER.READ_ONLY_STALENESS {TO|=} staleness_type

staleness_type:

{ 'STRONG' 
  | 'MIN_READ_TIMESTAMP timestamp'
  | 'READ_TIMESTAMP timestamp'
  | 'MAX_STALENESS <int8>{ s | ms | us | ns }'
  | 'EXACT_STALENESS <int8>{ s | ms | us | ns }' }

Il valore di obsolescenza di sola lettura si applica a tutte le transazioni di sola lettura successive e a tutte le query in modalità AUTOCOMMIT.

Il valore predefinito è STRONG.

Le opzioni per le associazioni di timestamp sono le seguenti:

  • STRONG indica a Spanner di eseguire una lettura elevata.
  • MAX_STALENESS definisce l'intervallo di tempo utilizzato da Spanner per eseguire una lettura di inattività limitata, relativa a now().
  • MIN_READ_TIMESTAMP definisce un tempo assoluto utilizzato da Spanner per eseguire una lettura di inattività limitata.
  • EXACT_STALENESS definisce l'intervallo di tempo utilizzato da Spanner per eseguire una lettura di inattività esatta, relativa a now().
  • READ_TIMESTAMP definisce un tempo assoluto utilizzato da Spanner per eseguire una lettura di inattività esatta.

I timestamp devono utilizzare il seguente formato:

YYYY-[M]M-[D]D [[H]H:[M]M:[S]S[.DDDDDD]][timezone]

Le unità di tempo supportate per l'impostazione dei valori MAX_STALENESS e EXACT_STALENESS sono:

  • s: secondi
  • ms: millisecondi
  • us: microsecondi
  • ns: nanosecondi

Puoi modificare il valore di questa proprietà solo quando non ci sono transazioni attive.

▶ Esempio: mancato aggiornamento in sola lettura (fai clic per espandere)
L'esempio seguente mostra come eseguire query utilizzando un valore di inattività personalizzato con PGAdapter.

-- Set the read-only staleness to MAX_STALENESS 10 seconds.
SET SPANNER.READ_ONLY_STALENESS = 'MAX_STALENESS 10s';

-- Execute a query in auto-commit mode. This will return results that are up to
-- 10 seconds stale.
SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- Read-only staleness can also be applied to read-only transactions.
-- MAX_STALENESS is however only allowed for queries in autocommit mode.
-- Change the staleness to EXACT_STALENESS and start a read-only transaction.
SET SPANNER.READ_ONLY_STALENESS = 'EXACT_STALENESS 10s';
BEGIN;
SET TRANSACTION READ ONLY;

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

SELECT title, singer_id
FROM albums
ORDER BY title;

COMMIT;

-- Read staleness can also be an exact timestamp.
SET SPANNER.READ_ONLY_STALENESS = 'READ_TIMESTAMP 2024-01-26T10:36:00Z';

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

SPANNER.OPTIMIZER_VERSION

Una proprietà di tipo STRING che indica la versione dell'ottimizzatore. La versione è numerica o "LATEST".

SHOW [VARIABLE] SPANNER.OPTIMIZER_VERSION
SET SPANNER.OPTIMIZER_VERSION {TO|=} { 'version'|'LATEST'|'' }

Imposta la versione dell'ottimizzatore da utilizzare per tutte le seguenti dichiarazioni relative alla connessione. Impostando la versione dello strumento di ottimizzazione su '' (la stringa vuota) indica di utilizzare la versione più recente. Se non è impostata alcuna versione dell'ottimizzatore, Spanner utilizza la versione dell'ottimizzatore impostata a livello del database.

Il valore predefinito è ''.

▶ Esempio: versione dell'ottimizzatore (fai clic per espandere)
L'esempio seguente mostra come eseguire query utilizzando una versione di ottimizzazione specifica con PGAdapter.

-- Set the optimizer version to 5 and execute a query.
SET SPANNER.OPTIMIZER_VERSION = '5';

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- Execute the same query with the latest optimizer version.
SET SPANNER.OPTIMIZER_VERSION = 'LATEST';

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- Revert back to using the default optimizer version that has been set for the
-- database.
SET SPANNER.OPTIMIZER_VERSION = '';

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

SPANNER.OPTIMIZER_STATISTICS_PACKAGE

Una proprietà di tipo STRING che indica l'attuale pacchetto di statistiche di ottimizzazione utilizzato da questa connessione.

SHOW [VARIABLE] SPANNER.OPTIMIZER_STATISTICS_PACKAGE
SET SPANNER.OPTIMIZER_STATISTICS_PACKAGE {TO|=} { 'package'|'' }

Imposta il pacchetto di statistiche dell'ottimizzatore da utilizzare per tutte le seguenti istruzioni relative alla connessione. <package> deve essere un nome di pacchetto valido. Se non viene impostato alcun pacchetto di statistiche di ottimizzazione, Spanner utilizza il pacchetto di statistiche di ottimizzazione impostato a livello di database.

Il valore predefinito è ''.

▶ Esempio: pacchetto di statistiche dell'ottimizzatore (fai clic per espandere)
L'esempio seguente mostra come eseguire query utilizzando uno specifico pacchetto di statistiche di ottimizzazione con PGAdapter.

-- Show the available optimizer statistics packages in this database.
SELECT * FROM INFORMATION_SCHEMA.SPANNER_STATISTICS;

-- Set the optimizer statistics package and execute a query.
SET SPANNER.OPTIMIZER_STATISTICS_PACKAGE = 'auto_20240124_06_47_29UTC';

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- Execute the same query with the default optimizer statistics package.
SET SPANNER.OPTIMIZER_VERSION = '';

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

SPANNER.RETURN_COMMIT_STATS

Una proprietà di tipo BOOL che indica se è necessario restituire statistiche per le transazioni su questa connessione. Puoi visualizzare le statistiche restituite eseguendo il comando SHOW [VARIABLE] COMMIT_RESPONSE.

SHOW [VARIABLE] SPANNER.RETURN_COMMIT_STATS
SET SPANNER.RETURN_COMMIT_STATS {TO|=} { true | false }

Il valore predefinito è false.

▶ Esempio: eseguire il commit delle statistiche (Fai clic per espandere)
L'esempio seguente mostra come visualizzare le statistiche di commit per una transazione con PGAdapter.

-- Enable the returning of commit stats.
SET SPANNER.RETURN_COMMIT_STATS = true;

-- Execute a transaction.
BEGIN;
INSERT INTO T (id, col_a, col_b)
VALUES (1, 100, 1), (2, 200, 2), (3, 300, 3);
COMMIT;

-- View the commit response with the transaction statistics for the last
-- transaction that was committed.
SHOW SPANNER.COMMIT_RESPONSE;

SPANNER.RPC_PRIORITY

Una proprietà di tipo STRING che indica la priorità relativa per le richieste di Spanner. La priorità funge da suggerimento per lo scheduler di Spanner e non garantisce l'ordine di esecuzione.

SHOW [VARIABLE] SPANNER.RPC_PRIORITY
SET SPANNER.RPC_PRIORITY {TO|=} {'HIGH'|'MEDIUM'|'LOW'|'NULL'}

'NULL' significa che nella richiesta non deve essere incluso alcun suggerimento.

Il valore predefinito è 'NULL'.

Puoi anche utilizzare un hint di istruzioni per specificare la priorità RPC:

/*@RPC_PRIORITY=PRIORITY_LOW*/ SELECT * FROM Albums

Per ulteriori informazioni, vedi Priority.

Estratti conto transazioni

Le seguenti istruzioni gestiscono ed eseguono il commit delle transazioni Spanner.

LIVELLO DI ISOLAZIONE DELLE TRANSAZIONI

SHOW [ VARIABLE ] TRANSACTION ISOLATION LEVEL

Restituisce un insieme di risultati con una riga e una colonna di tipo STRING. Il valore restituito è sempre serializable, poiché questo è l'unico livello di isolamento supportato per i database di dialetti PostgreSQL di Spanner.

SPANNER.READ_TIMESTAMP

SHOW [VARIABLE] SPANNER.READ_TIMESTAMP

Restituisce un set di risultati con una riga e una colonna di tipo TIMESTAMP contenenti il timestamp di lettura della transazione di sola lettura più recente. Questa istruzione restituisce un timestamp solo quando una transazione di sola lettura è ancora attiva e ha eseguito almeno una query oppure subito dopo l'impegno di una transazione di sola lettura e prima dell'inizio di una nuova transazione. In caso contrario, il risultato è NULL.

▶ Esempio: lettura del timestamp (fai clic per espandere)
L'esempio seguente mostra come visualizzare il timestamp dell'ultima lettura per un'operazione di sola lettura con PGAdapter.

-- Execute a query in autocommit mode using the default read-only staleness
-- (strong).
SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- Shows the read timestamp that was used for the previous query.
SHOW SPANNER.READ_TIMESTAMP;

-- Set a non-deterministic read-only staleness and execute the same query.
SET SPANNER.READ_ONLY_STALENESS = 'MAX_STALENESS 20s';

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- Shows the read timestamp that was used for the previous query. The timestamp
-- is determined by Spanner, and is guaranteed to be no less than 20
-- seconds stale.
SHOW SPANNER.READ_TIMESTAMP;

-- The read timestamp of a read-only transaction can also be retrieved.
SET SPANNER.READ_ONLY_STALENESS = 'STRONG';
BEGIN;
SET TRANSACTION READ ONLY;

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- Shows the read timestamp of the current read-only transaction. All queries in
-- this transaction will use this read timestamp.
SHOW SPANNER.READ_TIMESTAMP;

SELECT title
FROM albums
ORDER BY title;

-- The read timestamp is the same as for the previous query, as all queries in
-- the same transaction use the same read timestamp.
SHOW SPANNER.READ_TIMESTAMP;

COMMIT;

SPANNER.COMMIT_TIMESTAMP

SHOW [VARIABLE] SPANNER.COMMIT_TIMESTAMP

Restituisce un set di risultati con una riga e una colonna di tipo TIMESTAMP contenente il timestamp di commit dell'ultima transazione di lettura-scrittura eseguita da Spanner. Questa istruzione restituisce un timestamp solo quando la esegui dopo il commit di una transazione di lettura-scrittura e prima di eseguire eventuali successive istruzioni SELECT, DML o di modifica dello schema. In caso contrario, il risultato è NULL.

▶ Esempio: timestamp del commit (fai clic per espandere)
L'esempio seguente mostra come visualizzare il timestamp dell'ultimo commit per un'operazione di scrittura con PGAdapter.

-- Execute a DML statement.
INSERT INTO T (id, col_a, col_b)
VALUES (1, 100, 1), (2, 200, 2), (3, 300, 3);

-- Show the timestamp that the statement was committed.
SHOW SPANNER.COMMIT_TIMESTAMP;

SPANNER.COMMIT_RESPONSE

SHOW [VARIABLE] SPANNER.COMMIT_RESPONSE

Restituisce un insieme di risultati con una riga e due colonne:

  • COMMIT_TIMESTAMP (type=TIMESTAMP) indica quando è stata impegnata la transazione più recente.
  • MUTATION_COUNT (type=int8) indica quante mutazioni sono state applicate alla transazione impegnata. Questo valore è sempre vuoto quando viene eseguito sull'emulatore.

Il conteggio delle mutazioni è disponibile solo se SET RETURN_COMMIT_STATS è stato impostato su true prima del commit della transazione.

▶ Esempio: commit di risposta (fai clic per espandere)
L'esempio seguente mostra come visualizzare l'ultima risposta al commit per un'operazione di scrittura con PGAdapter.

-- Enable returning commit stats in addition to the commit timestamp.
SET SPANNER.RETURN_COMMIT_STATS = true;

-- Execute a DML statement.
INSERT INTO T (id, col_a, col_b)
VALUES (1, 100, 1), (2, 200, 2), (3, 300, 3);

-- Show the timestamp that the statement was committed.
SHOW SPANNER.COMMIT_RESPONSE;

{ AVVIO | INIZIO } [ TRANSAZIONE | LAVORO ]

{ START | BEGIN } [ TRANSACTION | WORK ] [{ READ ONLY | READ WRITE }]

Avvia una nuova transazione. Le parole chiave TRANSACTION e WORK sono facoltative, equivalenti e non hanno alcun effetto.

  • Utilizza COMMIT o ROLLBACK per terminare una transazione.
  • Se hai abilitato la modalità AUTOCOMMIT, questa istruzione disattiva temporaneamente la connessione dalla modalità AUTOCOMMIT. Al termine della transazione, la connessione torna alla modalità AUTOCOMMIT.
  • Se READ ONLY o READ WRITE non sono specificati, la modalità di transazione viene determinata dalla modalità di transazione predefinita della sessione. Questa impostazione predefinita viene impostata utilizzando il comando SET SESSION CHARACTERISTICS AS TRANSACTION.

È possibile eseguire questa istruzione solo quando non ci sono transazioni attive.

▶ Esempio: INIZIO TRANSAZIONE (fai clic per espandere)
L'esempio seguente mostra come avviare diversi tipi di transazioni con PGAdapter.

-- This starts a transaction using the current defaults of this connection.
-- The value of SPANNER.READONLY determines whether the transaction is a
-- read/write or a read-only transaction.

BEGIN;
INSERT INTO T (id, col_a, col_b)
VALUES (1, 100, 1);
COMMIT;

-- Set SPANNER.READONLY to TRUE to use read-only transactions by default.
SET SPANNER.READONLY=TRUE;

-- This starts a read-only transaction.
BEGIN;
SELECT first_name, last_name
FROM singers
ORDER BY last_name;
COMMIT;

-- Use the 'READ WRITE' or 'READ ONLY' qualifier in the BEGIN statement to
-- override the current default of the connection.
SET SPANNER.READONLY=FALSE;
BEGIN READ ONLY;
SELECT first_name, last_name
FROM singers
ORDER BY last_name;
COMMIT;

IMPEGNO [TRANSAZIONE | LAVORO]

COMMIT [TRANSACTION | WORK]

Esegue il commit della transazione corrente. Le parole chiave TRANSACTION e WORK sono facoltative ed equivalenti e non hanno alcun effetto.

  • Il commit di una transazione di lettura/scrittura rende tutti gli aggiornamenti di questa transazione visibili alle altre transazioni e rilascia tutti i blocchi della transazione su Spanner.
  • Il commit di una transazione di sola lettura termina l'attuale transazione di sola lettura. Qualsiasi istruzione successiva avvia una nuova transazione. Non esiste alcuna differenza semantica tra COMMIT e ROLLBACK per una transazione di sola lettura.

Puoi eseguire questa istruzione solo mentre è presente una transazione attiva.

▶ Esempio: TRANSAZIONE DI IMPEGNO (fai clic per espandere)
L'esempio seguente mostra come eseguire il commit di una transazione con PGAdapter.

-- Execute a regular read/write transaction.
BEGIN;
INSERT INTO T (id, col_a, col_b)
VALUES (1, 100, 1);
COMMIT;

-- Execute a read-only transaction. Read-only transactions also need to be
-- either committed or rolled back in PGAdapter in order to mark the
-- end of the transaction.
BEGIN READ ONLY;
SELECT first_name, last_name
FROM singers
ORDER BY last_name;
COMMIT;

ROLLBACK [TRANSAZIONE | LAVORO]

ROLLBACK [TRANSACTION | WORK]

Esegue un ROLLBACK della transazione corrente. Le parole chiave TRANSACTION e WORK sono facoltative ed equivalenti e non hanno alcun effetto.

  • L'esecuzione di un ROLLBACK di una transazione di lettura/scrittura cancella eventuali mutazioni presenti nel buffer, esegue il rollback della transazione su Spanner e rilascia eventuali blocchi della transazione trattenuta.
  • L'esecuzione di un ROLLBACK di una transazione di sola lettura termina la transazione di sola lettura corrente. Eventuali istruzioni successive avviano una nuova transazione. Non esiste una differenza semantica tra COMMIT e ROLLBACK per una transazione di sola lettura su una connessione.

Puoi eseguire questa istruzione solo mentre è presente una transazione attiva.

▶ Esempio: TRANSAZIONE DI ROLLBACK (fai clic per espandere)
L'esempio seguente mostra come eseguire il rollback di una transazione con PGAdapter.

-- Use ROLLBACK to undo the effects of a transaction.
BEGIN;
INSERT INTO T (id, col_a, col_b)
VALUES (1, 100, 1);
-- This will ensure that the insert statement is not persisted in the database.
ROLLBACK;

-- Read-only transactions also need to be either committed or rolled back in
-- PGAdapter in order to mark the end of the transaction. There is no
-- semantic difference between rolling back or committing a read-only
-- transaction.
BEGIN READ ONLY;
SELECT first_name, last_name
FROM singers
ORDER BY last_name;
ROLLBACK;

IMPOSTA TRANSAZIONE

SET TRANSACTION { READ ONLY | READ WRITE }

Imposta la modalità di transazione per la transazione corrente.

Puoi eseguire questa istruzione solo quando AUTOCOMMIT è false o se hai avviato una transazione eseguendo BEGIN [TRANSACTION | WORK] e non hai ancora eseguito alcuna istruzione nella transazione.

Questa istruzione imposta la modalità di transazione solo per la transazione corrente. Quando la transazione esegue il commit o il rollback, la transazione successiva utilizza la modalità predefinita per la connessione. Vedi SET SESSION CHARACTERISTICS.

▶ Esempio: IMPOSTA TRANSAZIONE (fai clic per espandere)
L'esempio seguente mostra come impostare le caratteristiche della transazione con PGAdapter.

-- Start a transaction and set the transaction mode to read-only.
BEGIN;
SET TRANSACTION READ ONLY;

SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- Commit the read-only transaction to mark the end of the transaction.
COMMIT;

-- Start a transaction and set the transaction mode to read/write.
BEGIN;
SET TRANSACTION READ WRITE;

INSERT INTO T (id, col_a, col_b)
VALUES (1, 100, 1);

COMMIT;

IMPOSTA CARATTERISTICHE DELLA SESSIONE

SET SESSION CHARACTERISTICS AS TRANSACTION { READ ONLY | READ WRITE }

Consente di impostare la modalità di transazione predefinita per le transazioni nella sessione su READ ONLY o READ WRITE. Questa istruzione è consentita solo in assenza di transazioni attive.

Il comando SET TRANSACTION può sostituire questa impostazione.

▶ Esempio: IMPOSTA CARATTERISTICHE DELLA SESSIONE (fai clic per espandere)
L'esempio seguente mostra come impostare le caratteristiche di sessione con PGAdapter.

-- Set the default transaction mode to read-only.
SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;

-- This will now start a read-only transaction.
BEGIN;
SELECT first_name, last_name
FROM singers
ORDER BY last_name;
COMMIT;

-- You can override the default transaction mode with the SET TRANSACTION
-- statement.
SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE;
BEGIN;
SET TRANSACTION READ ONLY;
SELECT first_name, last_name
FROM singers
ORDER BY last_name;
COMMIT;

SPANNER.STATEMENT_TAG

Una proprietà di tipo STRING contenente il tag di richiesta per l'istruzione successiva.

SHOW [ VARIABLE ] SPANNER.STATEMENT_TAG
SET SPANNER.STATEMENT_TAG {TO|=} 'tag-name'

Imposta il tag di richiesta per l'istruzione successiva da eseguire. È possibile impostare un solo tag per istruzione. Il tag non comprende più istruzioni; deve essere impostato per singole istruzioni. Un tag di richiesta può essere rimosso impostandolo sulla stringa vuota ('').

Il valore predefinito è ''.

Per la stessa istruzione è possibile impostare sia tag di transazione che tag di istruzioni.

Puoi anche utilizzare un suggerimento di istruzioni per aggiungere un tag di istruzioni:

/*@STATEMENT_TAG='my-tag'*/ SELECT * FROM albums

Per ulteriori informazioni, consulta Risoluzione dei problemi relativi a tag di richiesta e tag di transazione.

▶ Esempio: tag di istruzione (fai clic per espandere)
L'esempio seguente mostra come impostare tag di istruzioni con PGAdapter.

-- Set the statement tag that should be included with the next statement.
SET SPANNER.STATEMENT_TAG = 'tag1';
SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- The statement tag property is cleared after each statement execution.
SHOW SPANNER.STATEMENT_TAG;
-- Set another tag for the next statement.
SET SPANNER.STATEMENT_TAG = 'tag2';
SELECT title
FROM albums
ORDER BY title;

-- Set a statement tag with a query hint.
/*@STATEMENT_TAG='tag3'*/
SELECT track_number, title
FROM tracks
WHERE album_id=1 AND singer_id=1
ORDER BY track_number;

SPANNER.TRANSACTION_TAG

Una proprietà di tipo STRING contenente il tag transazione per la transazione successiva.

SHOW [ VARIABLE ] SPANNER.TRANSACTION_TAG
SET SPANNER.TRANSACTION_TAG {TO|=} 'tag-name'

Imposta il tag della transazione per la transazione corrente da eseguire. È possibile impostare un solo tag per transazione. Il tag non comprende più transazioni; deve essere impostato per ogni transazione. È possibile rimuovere un tag transazioni impostandolo sulla stringa vuota (''). Il tag transazione deve essere impostato prima di eseguire qualsiasi istruzione nella transazione.

Il valore predefinito è ''.

Per la stessa istruzione è possibile impostare sia tag di transazione che tag di istruzioni.

Per ulteriori informazioni, consulta Risoluzione dei problemi relativi a tag di richiesta e tag di transazione.

▶ Esempio: tag transazione (fai clic per espandere)
L'esempio seguente mostra come impostare i tag transazione con PGAdapter.

BEGIN;
-- Set the transaction tag for the current transaction.
SET SPANNER.TRANSACTION_TAG = 'transaction-tag-1';

-- Set the statement tag that should be included with the next statement.
-- The statement will include both the statement tag and the transaction tag.
SET SPANNER.STATEMENT_TAG = 'select-statement';
SELECT first_name, last_name
FROM singers
ORDER BY last_name;

-- The statement tag property is cleared after each statement execution.
SHOW SPANNER.STATEMENT_TAG;

-- Set another tag for the next statement.
SET SPANNER.STATEMENT_TAG = 'insert-statement';
INSERT INTO T (id, col_a, col_b)
VALUES (1, 100, 1);

COMMIT;

-- The transaction tag property is cleared when the transaction finishes.
SHOW SPANNER.TRANSACTION_TAG;

Istruzioni batch

Le istruzioni riportate di seguito gestiscono i batch di istruzioni DDL e li inviano a Spanner.

AVVIA DDL DI BATCH

START BATCH DDL

Avvia un batch di istruzioni DDL sulla connessione. Tutte le istruzioni successive durante il batch devono essere istruzioni DDL. Le istruzioni DDL vengono memorizzate nel buffer localmente e inviate a Spanner come un unico batch quando esegui RUN BATCH. L'esecuzione di più istruzioni DDL come un unico batch è in genere più rapida rispetto all'esecuzione delle istruzioni separatamente.

È possibile eseguire questa istruzione solo quando non ci sono transazioni attive.

▶ Esempio: batch DDL (fai clic per espandere)
L'esempio seguente mostra come eseguire un batch DDL con PGAdapter.

-- Start a DDL batch. All following statements must be DDL statements.
START BATCH DDL;

-- This statement is buffered locally until RUN BATCH is executed.
CREATE TABLE singers (
  id bigint primary key,
  first_name varchar,
  last_name varchar
);

-- This statement is buffered locally until RUN BATCH is executed.
CREATE TABLE albums (
  id bigint primary key,
  title varchar,
  singer_id bigint,
  constraint fk_albums_singers foreign key (singer_id) references singers (id)
);

-- This runs the DDL statements as one batch.
RUN BATCH;

ESEGUI BATCH

RUN BATCH

Invia al database tutte le istruzioni DDL incluse nel buffer nel batch DDL attuale, attende che Spanner esegua queste istruzioni e termina il batch DDL attuale.

Se Spanner non può eseguire almeno un'istruzione DDL, RUN BATCH restituisce un errore per la prima istruzione DDL che Spanner non può eseguire. In caso contrario, l'articolo RUN BATCH viene restituito correttamente.

PRIMA DEL LOTTO

Cancella tutte le istruzioni DDL incluse nel buffer nel batch DDL corrente e termina il batch.

È possibile eseguire questa istruzione solo quando è attivo un batch DDL. Puoi utilizzare ABORT BATCH indipendentemente dal fatto che il batch abbia istruzioni DDL incluse nel buffer. Tutte le istruzioni DDL precedenti nel batch verranno interrotte.

▶ Esempio: interrompere il batch DDL (fai clic per espandere)
L'esempio seguente mostra come interrompere un batch DDL con PGAdapter.

-- Start a DDL batch. All following statements must be DDL statements.
START BATCH DDL;

-- The following statements are buffered locally.
CREATE TABLE singers (
  id bigint primary key,
  first_name varchar,
  last_name varchar
);
CREATE TABLE albums (
  id bigint primary key,
  title varchar,
  singer_id bigint,
  constraint fk_albums_singers foreign key (singer_id) references singers (id)
);

-- This aborts the DDL batch and removes the DDL statements from the buffer.
ABORT BATCH;

AVVIA DML BATCH

Le seguenti istruzioni raggruppano le due istruzioni DML e le inviano in una sola chiamata al server. Un batch DML può essere eseguito come parte di una transazione o in modalità di commit automatico.

START BATCH DML;
INSERT INTO MYTABLE (ID, NAME) VALUES (1, 'ONE');
INSERT INTO MYTABLE (ID, NAME) VALUES (2, 'TWO');
RUN BATCH;

▶ Esempio: batch DML (fai clic per espandere)
L'esempio seguente mostra come eseguire un batch DML con PGAdapter.

-- Start a DML batch. All following statements must be a DML statement.
START BATCH DML;

-- The following statements are buffered locally.
INSERT INTO MYTABLE (ID, NAME) VALUES (1, 'ONE');
INSERT INTO MYTABLE (ID, NAME) VALUES (2, 'TWO');

-- This sends the statements to Spanner.
RUN BATCH;

-- DML batches can also be part of a read/write transaction.
BEGIN;
-- Insert a row using a single statement.
INSERT INTO MYTABLE (ID, NAME) VALUES (3, 'THREE');

-- Insert two rows using a batch.
START BATCH DML;
INSERT INTO MYTABLE (ID, NAME) VALUES (4, 'FOUR');
INSERT INTO MYTABLE (ID, NAME) VALUES (5, 'FIVE');
RUN BATCH;

-- Rollback the current transaction. This rolls back both the single DML
-- statement and the DML batch.
ROLLBACK;

Comandi Savepoint

I punti di salvataggio in PGAdapter vengono emulati. Il rollback a un punto di salvataggio esegue il rollback dell'intera transazione e ne fa un nuovo tentativo fino al punto in cui era stato impostato il punto di salvataggio. Questa operazione non riuscirà con un errore AbortedDueToConcurrentModificationException se i dati sottostanti utilizzati dalla transazione fino al punto di salvataggio sono cambiati.

La creazione e il rilascio dei punti di salvataggio hanno sempre esito positivo quando è abilitato il supporto dei punti di salvataggio.

Le seguenti istruzioni abilitano e disabilitano i punti di salvataggio emulati nelle transazioni.

SPANNER.SAVEPOINT_SUPPORT

SHOW [VARIABLE] SPANNER.SAVEPOINT_SUPPORT
SET SPANNER.SAVEPOINT_SUPPORT = { 'DISABLED' | 'FAIL_AFTER_ROLLBACK' | 'ENABLED' }

Una proprietà di tipo STRING che indica l'attuale configurazione di SAVEPOINT_SUPPORT. I valori possibili sono:

  • DISABLED: tutti i comandi del punto di salvataggio sono disabilitati e non riusciranno.
  • FAIL_AFTER_ROLLBACK: i comandi Savepoint sono abilitati. Il rollback a un punto di salvataggio comporta il rollback dell'intera transazione. L'operazione non riesce se provi a utilizzare la transazione dopo il rollback a un punto di salvataggio.
  • ENABLED: tutti i comandi Savepoint sono abilitati. Il rollback a un punto di salvataggio esegue il rollback della transazione e il nuovo tentativo viene eseguito sul punto di salvataggio. Questa operazione non va a buon fine e restituisce un errore AbortedDueToConcurrentModificationException se i dati sottostanti utilizzati dalla transazione fino al punto di salvataggio sono cambiati.

Il valore predefinito è ENABLED.

È possibile eseguire questa istruzione solo quando non ci sono transazioni attive.

SAVEPOINT nome_punto_salvataggio

SAVEPOINT savepoint-name;

SAVEPOINT crea un nuovo punto di salvataggio all'interno della transazione corrente. È possibile eseguire il rollback di una transazione in un punto di salvataggio per annullare tutte le operazioni eseguite dopo la creazione del punto di salvataggio.

▶ Esempio: punto di salvataggio (fai clic per espandere)
L'esempio seguente mostra come salvare i punti con PGAdapter.

-- Start a transaction and execute an insert statement.
BEGIN;
INSERT INTO T (id, col_a, col_b) VALUES (1, 100, 1);

-- Set a savepoint and then execute another insert statement.
SAVEPOINT one_row_inserted;
INSERT INTO T (id, col_a, col_b) VALUES (2, 200, 2);

-- Roll back to the savepoint. This will undo all statements that have been
-- executed after the savepoint.
ROLLBACK TO one_row_inserted;

-- This only commits the first insert statement.
COMMIT;

ROLLBACK A salvataggio_nome

ROLLBACK TO savepoint_name

Esegue il rollback della transazione corrente nel punto di salvataggio con il nome specificato.

Non è garantito che il rollback a un punto di salvataggio abbia esito positivo in tutti i casi. Il rollback a un punto di salvataggio esegue il rollback dell'intera transazione, riprova fino al punto in cui è stato impostato il punto di salvataggio. Questa operazione non riuscirà con AbortedDueToConcurrentModificationException se i dati sottostanti utilizzati dalla transazione fino al punto di salvataggio sono cambiati.

RILASCIA [SAVEPOINT] savepoint_name

RELEASE savepoint_name

Rimuove il punto di salvataggio dalla transazione corrente. Non può più essere utilizzato per eseguire un'istruzione ROLLBACK TO savepoint_name.

Dichiarazioni preparate

Le istruzioni riportate di seguito creano ed eseguono le istruzioni preparate.

PREPARATI

PREPARE statement_name [(data_type, ...)] AS statement

Prepara una dichiarazione su questa connessione. L'istruzione viene analizzata e convalidata da Spanner e archiviata in memoria in PGAdapter.

▶ Esempio: istruzioni preparate (fai clic per espandere)
L'esempio seguente mostra come creare ed eseguire istruzioni preparate con PGAdapter.

-- Create a prepared statement that can be used to insert a single row.
PREPARE insert_t AS INSERT INTO T (id, col_a, col_b) VALUES ($1, $2, $3);

-- The prepared statement can be used to insert rows both in autocommit, in a
-- transaction, and in DML batches.

-- Execute in autocommit.
EXECUTE insert_t (1, 100, 1);

-- Execute in transaction.
BEGIN;
EXECUTE insert_t (2, 200, 2);
EXECUTE insert_t (3, 300, 3);
COMMIT;

-- Execute in a DML batch.
START BATCH DML;
EXECUTE insert_t (4, 400, 4);
EXECUTE insert_t (5, 500, 5);
RUN BATCH;

-- Prepared statements can be removed with the DEALLOCATE command.
DEALLOCATE insert_t;

ESEGUI

EXECUTE statement_name [(value, ...)]

Esegue un'istruzione creata su questa connessione con PREPARE.

▶ Esempio: Esegui (fai clic per espandere)
L'esempio seguente mostra come preparare ed eseguire istruzioni con PGAdapter.

-- Create a prepared statement.
PREPARE my_statement AS insert into my_table (id, value) values ($1, $2);

-- Execute the statement twice with different parameter values.
EXECUTE my_statement (1, 'One');
EXECUTE my_statement (2, 'Two');

DEALLOCATE

DEALLOCATE statement_name

Rimuove un'istruzione preparata da questa connessione.

Copia

PGAdapter supporta un sottoinsieme del comando PostgreSQL COPY.

COPY table_name FROM STDIN

COPY table_name FROM STDIN [BINARY]

Copia i dati da stdin in Spanner. È più efficiente utilizzare COPY per importare un set di dati di grandi dimensioni in Spanner anziché eseguire istruzioni INSERT.

COPY può essere combinato con SPANNER.AUTOCOMMIT_DML_MODE per eseguire una transazione non atomica. Ciò consente alla transazione di eseguire più mutazioni rispetto al limite standard di mutazioni.

▶ Esempio: copia (fai clic per espandere)
Gli esempi seguenti mostrano come copiare dati da e verso Spanner con PGAdapter.

create table numbers (number bigint not null primary key, name varchar);

Esegui un'operazione COPY atomica:

cat numbers.txt | psql -h /tmp -d test-db -c "copy numbers from stdin;"

Esegui un'operazione COPY non atomica:

cat numbers.txt | psql -h /tmp -d test-db \
  -c "set spanner.autocommit_dml_mode='partitioned_non_atomic'; copy numbers from stdin;"

Copia i dati da PostgreSQL in Spanner:

psql -h localhost -p 5432 -d my-local-db \
  -c "copy (select i, to_char(i, 'fm000') from generate_series(1, 1000000) s(i)) to stdout binary" \
  | psql -h localhost -p 5433 -d my-spanner-db \
  -c "set spanner.autocommit_dml_mode='partitioned_non_atomic'; copy numbers from stdin binary;"

In questo esempio si presuppone che PostgreSQL venga eseguito sulla porta 5432 e che PGAdapter venga eseguito sulla porta 5433.

Per altri esempi, consulta la sezione Supporto di PGAdapter - COPY.

COPIA table_name PER STDOUT [BINARY]

COPY table_name TO STDOUT [BINARY]

Copia i dati in una tabella o da una query in stdout.

Data Boost e istruzioni di query partizionate

Data Boost consente di eseguire query di analisi ed esportazioni di dati con un impatto quasi zero sui carichi di lavoro esistenti sull'istanza Spanner di cui è stato eseguito il provisioning. Data Boost è supportato solo per le query partizionate.

Puoi attivare Data Boost con l'istruzione SET SPANNER.DATA_BOOST_ENABLED.

PGAdapter supporta tre alternative per l'esecuzione di query partizionate:

  • SET SPANNER.AUTO_PARTITION_MODE = true
  • RUN PARTITIONED QUERY sql
  • PARTITION sql seguito da più RUN PARTITION 'partition-token'

Nelle sezioni che seguono vengono descritti tutti questi metodi.

SPANNER.DATA_BOOST_ENABLED

SHOW SPANNER.DATA_BOOST_ENABLED
SET SPANNER.DATA_BOOST_ENABLED {TO|=} { true | false }

Consente di impostare se questa connessione deve utilizzare Data Boost per le query partizionate.

Il valore predefinito è false.

▶ Esempio: eseguire una query utilizzando Data Boost (fai clic per espandere)
L'esempio seguente mostra come eseguire una query utilizzando Data Boost con PGAdapter.

-- Enable Data Boost on this connection.
SET SPANNER.DATA_BOOST_ENABLED = true;

-- Execute a partitioned query. Data Boost is only used for partitioned queries.
RUN PARTITIONED QUERY SELECT FirstName, LastName FROM Singers;

SPANNER.AUTO_PARTITION_MODE

SHOW SPANNER.AUTO_PARTITION_MODE
SET SPANNER.AUTO_PARTITION_MODE {TO|=} { true | false}

Una proprietà di tipo BOOL che indica se la connessione utilizza automaticamente query partizionate per tutte le query eseguite.

  • Imposta questa variabile su true se vuoi che la connessione utilizzi una query partizionata per tutte le query eseguite.
  • Imposta anche SPANNER.DATA_BOOST_ENABLED su true se vuoi che la connessione utilizzi Data Boost per tutte le query.

Il valore predefinito è false.

▶ Esempio: Esegui (fai clic per espandere)
Questo esempio esegue due query con PGAdapter utilizzando Data Boost

SET SPANNER.AUTO_PARTITION_MODE = true
SET SPANNER.DATA_BOOST_ENABLED = true
SELECT first_name, last_name FROM singers
SELECT singer_id, title FROM albums

ESEGUI QUERY PARZIATA

RUN PARTITIONED QUERY <sql>

Esegue una query come query partizionata su Spanner. Assicurati che SPANNER.DATA_BOOST_ENABLED sia impostato su true per eseguire la query con Data Boost:

SET SPANNER.DATA_BOOST_ENABLED = true
RUN PARTITIONED QUERY SELECT FirstName, LastName FROM Singers

PGAdapter partiziona internamente la query ed esegue le partizioni in parallelo. I risultati vengono uniti in un unico set di risultati e restituiti all'applicazione. Il numero di thread worker che eseguono le partizioni può essere impostato con la variabile SPANNER.MAX_PARTITIONED_PARALLELISM.

PARTIZIONE <SQL>

PARTITION <sql>

Crea un elenco di partizioni per eseguire una query su Spanner e restituisce un elenco di token di partizione. Ogni token di partizione può essere eseguito su una connessione separata sulla stessa istanza PGAdapter o su un'altra utilizzando il comando RUN PARTITION 'partition-token'.

▶ Esempio: query di partizione (fai clic per espandere)
L'esempio seguente mostra come eseguire il partizionamento di una query e quindi eseguire ogni partizione separatamente utilizzando PGAdapter.

-- Partition a query. This returns a list of partition tokens that can be
-- executed either on this connection or on any other connection to the same
-- database.
PARTITION SELECT FirstName, LastName FROM Singers;

-- Run the partitions that were returned from the previous statement.
RUN PARTITION 'partition-token-1';
RUN PARTITION 'partition-token-2';

RUN PARTITION "partition-token"

RUN PARTITION 'partition-token'

Esegue una partizione di query precedentemente restituita dal comando PARTITION. Il comando può essere eseguito su qualsiasi connessione connessa allo stesso database del database che ha creato i token di partizione.

SPANNER.MAX_PARTITIONED_PARALLELISM

Una proprietà di tipo bigint che indica il numero di thread worker utilizzati da PGAdapter per eseguire le partizioni. Questo valore viene utilizzato per:

  • SPANNER.AUTO_PARTITION_MODE = true
  • RUN PARTITIONED QUERY sql
SHOW SPANNER.MAX_PARTITIONED_PARALLELISM
SET SPANNER.MAX_PARTITIONED_PARALLELISM {TO|=} <bigint>

Imposta il numero massimo di thread worker che PGAdapter può utilizzare per eseguire le partizioni. Se questo valore viene impostato su 0, PGAdapter utilizza le istruzioni per usare al massimo il numero di core della CPU sulla macchina client.

Il valore predefinito è 0.

Passaggi successivi