Connect to SLS using the PostgreSQL protocol

Updated at:

SLS supports the PostgreSQL protocol. Use psql, JDBC, or any PG-compatible tool to read, write, and manage log data with SQL.

Features

With the PostgreSQL protocol, you can:

  • Manage logstores using standard SQL syntax (create, modify, delete).

  • Analyze log data using PostgreSQL SQL syntax.

  • Write log data using INSERT statements.

  • Query logstore schema metadata using native PostgreSQL syntax, fully compatible with PostgreSQL system tables.

Limits

The following limits apply:

Limitations

Description

Prepared Statement

Prepared statements (parse/bind/execute) are not supported. For JDBC, set the query mode to simple:

props.setProperty(PGProperty.PREFER_QUERY_MODE.getName(), "simple");

Or set the preferQueryMode parameter in the JDBC URL:

jdbc:postgresql://{endpoint}:5432/{project}?preferQueryMode=simple

Transaction support

The begin, commit, and rollback statements are ignored and have no effect.

Primary keys and default values

Constraints such as primary keys and default values are not supported.

Prerequisites

  • You have created a project.

  • You have an AccessKey pair (AccessKey ID and AccessKey secret). Create an AccessKey.

  • A PostgreSQL-compatible client (such as psql) is installed.

Connect to SLS

PostgreSQL client connection URL format:

postgresql://{AccessKey_ID}:{AccessKey_Secret}@{Endpoint}:5432/{Project_Name}
# The connection enables TLS by default (MD5 for authentication). To explicitly disable TLS (for example, if the client does not support it), set the sslmode parameter to disable.
postgresql://{AccessKey_ID}:{AccessKey_Secret}@{Endpoint}:5432/{Project_Name}?sslmode=disable

JDBC connection example:

private static final String URL = "jdbc:postgresql://{Endpoint}:5432/{Project_Name}?preferQueryMode=simple";
private static final String AccessKey_ID = "xyz";
private static final String AccessKey_Secret = "123456";

public static void main(String[] args) throws Exception
{
    Properties props = new Properties();
    props.setProperty(PGProperty.USER.getName(), AccessKey_ID);
    props.setProperty(PGProperty.PASSWORD.getName(), AccessKey_Secret);

    try (Connection conn = DriverManager.getConnection(URL, props)) {
        System.out.println("Connection successful!");
    }
}

Parameters

Parameter

Description

Example

AccessKey_ID

The AccessKey ID of your Alibaba Cloud account or RAM user.

LTAI5t***

AccessKey_Secret

The AccessKey secret of your Alibaba Cloud account or RAM user.

***

Endpoint

The SLS endpoint. Must include the project name as shown in the Example column. Endpoints.

{projectName}.cn-hangzhou.log.aliyuncs.com

Project_Name

The name of the log project.

my-project

Manage tables

A table maps to an SLS logstore.

Create a table

Create a logstore with CREATE TABLE:

CREATE TABLE users (
    id           BIGINT,
    name         TEXT,
    create_time  TIMESTAMP
)
WITH (
    shard_count = 4,
    ttl = 14,
    default_query_range = '1d',
    full_text_search_enabled = true,

    index_tokens = '&[ ]",''\',

    log_time_field = 'create_time',
    insert_any_allowed = false
);

Supported column types:

PostgreSQL type

SLS type

Description

int8/bigint/int4/integer/int2/smallint/oid

long

Integer type

text/varchar/char/bpchar/uuid

text

String type

float4/real/float8/double precision/numeric

double

Floating-point number type

json

json

JSON type

Table properties (WITH clause):

Property name

Type

Description

Default value

Example

shard_count

Integer

The number of shards in the logstore.

4

4

ttl

Integer

The data retention period in days.

365

14

default_query_range

String

The default query time range. Format: {n}{d/m/s} (day/minute/second).

'1d'

'3d'

full_text_search_enabled

Boolean

Whether to enable full-text indexing.

false

true

index_tokens

String

The tokens used for tokenization.

Default delimiters

'&[]",'''

log_time_field

String

The field used as log time during writes. Must be timestamp or long (epoch seconds, milliseconds, microseconds, or nanoseconds). The unit is auto-detected.

-

'create_time'

insert_any_allowed

Boolean

Whether to allow writes without schema validation. Set to false to enforce schema checks.

true

false

hot_ttl

Integer

Days to retain data in hot storage before transitioning to IA storage. If unset, data stays in hot storage for its full TTL. Manage intelligent tiering.

-

7

chn_columns

String

Columns that contain Chinese text, enabling Chinese tokenization for their indexes. Separate multiple names with commas. Use __line__ for full-text index. Note: Chinese tokenization affects performance. Use with caution.

-

'__line__,message,error'

Modify a column

Supported column modifications:

Add a column:

ALTER TABLE users ADD COLUMN change_time TEXT;

Rename a column:

ALTER TABLE users RENAME COLUMN change_time TO update_time;

Modify a column type:

ALTER TABLE users ALTER COLUMN update_time TYPE TIMESTAMP;

Delete a column:

ALTER TABLE users DROP COLUMN update_time;

Clear data

Clear all data from a table with TRUNCATE:

TRUNCATE TABLE users;
Note : After data is deleted, it takes about 30 seconds for the change to become visible in SQL queries.

Delete a table

Delete a table and its corresponding logstore with DROP TABLE:

DROP TABLE users;

Query data

Basic query

Query data with SELECT:

SELECT id, name FROM users LIMIT 10;
Note : If no time range is specified in the SQL statement, the default time range defined by default_query_range is used. If default_query_range was not set when the table was created, the query defaults to the last 15 minutes of data.

Specify a query time range

Two ways to specify a query time range:

Method 1: Use the __time__ field

-- Specify the lower limit of the time range
SELECT id, name FROM users 
WHERE __time__ > 1766646000
LIMIT 10;

-- Specify the time range
SELECT id, name FROM users 
WHERE __time__ > 1766646000 AND __time__ < 1766646987
LIMIT 10;
Note : The value of __time__ is a Unix timestamp in seconds. You must set a lower limit for the time range to take effect. If no upper limit is set, the end time defaults to the current time.

Method 2: Use the query_begin and query_end variables

-- Set the lower limit of the time range
SET query_begin = 1766646000; 
SELECT id, name FROM users LIMIT 10;

-- Set the time range
SET query_begin = 1766646000; 
SET query_end = 1766646987; 
SELECT id, name FROM users LIMIT 10;

-- Set the variables in a single statement (recommended)
SET query_begin = 1766646000; SET query_end = 1766646987; SELECT id, name FROM users LIMIT 10;
Note : Once set, the query_begin and query_end variables remain valid for the entire connection session. Run show query_begin or show query_end to view their current values. A value of 0 means the variable has not been set.

Write data

Basic write

Write data with INSERT INTO:

INSERT INTO users (id, name, create_time) 
VALUES
    (1, 'Name#1', '2025-12-25T06:54:19'),
    (2, 'Name#2', '2025-12-25T06:54:20'),
    (3, 'Name#3', '2025-12-25T06:54:21');

EXACTLY-ONCE writes

SLS supports the PostgreSQL protocol for controlling write sequence numbers with hash_key, seq_id, and the optional max_seq_id to prevent duplicate writes caused by retries. For the same data source, maintain stable, increasing sequence numbers and submit data in order.

This mechanism identifies duplicates by write sequence number. It does not identify duplicates from field values or primary keys.

Parameters

Parameter

Description

hash_key

A key that identifies the data source, such as a file identifier or a message queue partition identifier. Use the same value when retrying data from the same source.

seq_id

The sequence number for the current request. When writing batches by source sequence number, set it to the starting sequence number of the batch. It must be a positive integer and greater than the server-side sequence watermark already successfully written for the hash_key.

max_seq_id

Optional. The ending sequence number for the current batch. It must be greater than or equal to seq_id. After a successful write, the server advances the sequence watermark to this value. If it is not set, the watermark advances to seq_id.

Note

Sequence numbers can start at 1 and do not need to be contiguous. The server compares only sequence numbers. It does not verify that a sequence range matches the number of written rows or automatically assign a sequence number to each row.

Write using only seq_id

If the client assigns a unique, increasing batch sequence number to each write request and keeps the batch data unchanged when retrying, set only hash_key and seq_id:

SET hash_key = 'file#1';
SET seq_id = 1;

INSERT INTO users (id, name)
VALUES
 (1, 'Name#1'),
 (2, 'Name#2'),
 (3, 'Name#3');

After this write succeeds, the sequence watermark for file#1 is 1. If you write again with the same hash_key and seq_id=1, the server rejects the request. Use a larger sequence number for the next new batch.

Why max_seq_id is needed

If you use source sequence numbers, such as file line numbers or message offsets, as seq_id, and retries or recovery can repartition batches, seq_id alone cannot record the complete range covered by a batch.

For example:

  1. The first batch writes data with source sequence numbers 101–103 and sets seq_id=101.

  2. After the write succeeds, the server records only watermark 101.

  3. After recovery, the client repartitions the batches and sends data with source sequence numbers 102–104 with seq_id=102.

  4. Because 102 is greater than 101, the request passes the sequence-number check, causing data with source sequence numbers 102 and 103 to be written again.

Instead, set both seq_id=101 and max_seq_id=103. After the first batch succeeds, the server records watermark 103, and an overlapping batch that starts at 102 is rejected.

Write batches using max_seq_id

The following example assumes that the three rows have source sequence numbers 101, 102, and 103:

SET hash_key = 'file#1';
SET seq_id = 101;
SET max_seq_id = 103;

INSERT INTO users (id, name)
VALUES
 (101, 'Name#101'),
 (102, 'Name#102'),
 (103, 'Name#103');

After the write succeeds, the sequence watermark for this hash_key is 103. Subsequent requests are handled as follows:

Subsequent request

Result

Retry with seq_id=101, max_seq_id=103

Rejected to prevent duplicate writes.

Write with seq_id=102, max_seq_id=104

The entire batch is rejected because its starting sequence number is not greater than the current watermark.

Write with seq_id=104, max_seq_id=106

Passes the sequence-number check.

Important

The server does not deduplicate rows in an overlapping batch or write only its new rows. For an overlapping batch such as 102–104, remove the already processed portion according to the current watermark, and then submit data starting at 104. max_seq_id must accurately represent the ending sequence number of data processed in the batch. If it is set too high, later requests can skip smaller sequence numbers that have not yet been written.

Handle duplicate or stale requests

When a request's seq_id is less than or equal to the current server-side watermark, the server rejects the entire batch and returns an error similar to the following:

error: sequence id is lower than expected, hash_key=file#1,current sequence_id=103,requested sequence_id=101

current sequence_id is the watermark currently recorded by the server. When you use max_seq_id, this value can be the ending sequence number of a previously successful batch.

Use the following regular expression to extract the watermark:

current\s+sequence_id=(\d+)

Use local source progress to decide whether to skip data or repartition the batch. Do not simply increase the sequence number and resend the original batch, because doing so can create duplicate writes.

Usage notes

  • After every INSERT, hash_key, seq_id, and max_seq_id are cleared. Set them again before the next write or retry.

  • Set hash_key, seq_id, and max_seq_id in that order, and then run INSERT.

  • Submit batches for the same hash_key in sequence. If a larger sequence number succeeds first, later requests with smaller sequence numbers are rejected.

  • seq_id and max_seq_id are write-control parameters and do not need to be written as log fields. They have no automatic relationship with the id column in the example.

Query metadata

Query all logstores

SELECT 
    table_schema, 
    table_name
FROM 
    information_schema.tables;
Note : By default, a logstore is mapped to a schema under a project of the same name.

Query the field structure

SELECT 
    column_name, 
    data_type
FROM 
    information_schema.columns 
WHERE 
    table_name = 'access_log';

References