Skip to content

Repository files navigation

Postgres.jl

CIdocscodecov

Postgres.jl is a PostgreSQL client written in Julia that implements the v3 wire protocol with DBInterface and Tables integration.

Installation

import Pkg
Pkg.add("Postgres")

Quick start

using Postgres
DBInterface.connect(Postgres.Connection, "host=127.0.0.1;port=5432;user=postgres;password=postgres;dbname=postgres") do conn
row =only(DBInterface.execute(conn, "SELECT 1 AS a"))
@show row.a
end

Connections

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "postgresql://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable")
DBInterface.close!(conn)

Connection options support:

  • libpq-style keyword strings such as host=127.0.0.1 port=5432 user=postgres dbname=postgres.
  • PostgreSQL URIs such as postgresql://postgres:postgres@127.0.0.1:5432/postgres.
  • Environment defaults: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGAPPNAME, PGCONNECT_TIMEOUT, and TLS-related PGSSL* variables.
  • sslmode values: disable, prefer (the default), require, verify-full. Only verify-full verifies the server's certificate; require encrypts without authenticating the server, and the default prefer falls back to an unencrypted connection if the server declines TLS. Use verify-full with sslrootcert when the connection needs to be authenticated.
  • TLS files: sslrootcert, sslcert, sslkey, and sslcapath (sslcapath is a fallback CA bundle or directory, used only when sslrootcert is unset and ignored otherwise). sslservername overrides the TLS server name when connecting to a pre-resolved address; under verify-full it is also the name the certificate is verified against, so it must name the server you intend to authenticate.
  • connect_timeout (seconds) and statement_timeout (milliseconds).
  • application_name and statement_cache_maxsize.

See the 1.0 support policy for tested Julia and PostgreSQL versions, TLS limits, and transaction-pooler requirements.

You can also use ConnectionParams:

using Postgres, DBInterface
params = Postgres.ConnectionParams(host="127.0.0.1", user="postgres", password="postgres", dbname="postgres", sslmode="disable")
conn = DBInterface.connect(Postgres.Connection, params)
DBInterface.close!(conn)

Queries and prepared statements

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
rows = Tables.rowtable(DBInterface.execute(conn, raw"SELECT $1::int AS val", (42,)))
@show rows[1].val
stmt = DBInterface.prepare(conn, raw"SELECT $1::int AS val")
rows = Tables.rowtable(DBInterface.execute(stmt, (7,)))
DBInterface.close!(stmt)
DBInterface.close!(conn)

Postgres.jl can also deserialize result rows directly into structs through StructUtils.jl. If column names match field names, pass the target type as the fourth DBInterface.execute argument.

using Postgres, DBInterface, StructUtils
struct CountRow
count::Intend
row = DBInterface.execute(conn, "SELECT count(*)::int AS count FROM users", (), CountRow)
@show row.count

Use StructUtils.@tags with the postgres namespace when table columns use a different naming convention than Julia fields.

using Dates, Postgres, DBInterface, StructUtils
StructUtils.@tagsstruct ProfileSummary
profileId::Int&(postgres=(name=:profile_id,),)
firstName::Union{Missing, String}&(postgres=(name=:first_name,),)
lastName::Union{Missing, String}&(postgres=(name=:last_name,),)
createdAt::DateTime&(postgres=(name=:created_at,),)
end
profile = DBInterface.execute(conn, raw""" SELECT profile_id, first_name, last_name, created_at FROM profiles WHERE profile_id = $1""", (profile_id,), ProfileSummary)
profiles = DBInterface.execute(conn, """ SELECT profile_id, first_name, last_name, created_at FROM profiles ORDER BY created_at DESC LIMIT 10""", (), Vector{ProfileSummary})

Postgres.command_tag(result) and Postgres.rows_affected(result) expose PostgreSQL command completion metadata.

Explicit named prepared statements use an LRU backend cache. Caller handles are independent. Set statement_cache_maxsize=0 to disable this cache.

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; statement_cache_maxsize=10)
Postgres.set_statement_cache_maxsize!(conn, 5)
cached = Postgres.get_cached_statements(conn)
Postgres.clear_statement_cache!(conn)
DBInterface.close!(conn)

Transactions

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.transaction(conn) do tx
DBInterface.execute(tx, "CREATE TEMP TABLE tx_demo (id int)")
DBInterface.execute(tx, "INSERT INTO tx_demo VALUES (1)")
end
Postgres.@transaction conn begin
DBInterface.execute(conn, "INSERT INTO tx_demo VALUES (2)")
end
DBInterface.close!(conn)

Nested transactions are implemented with savepoints.

COPY protocol

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TEMP TABLE copy_demo (id int, name text)")
Postgres.copy_from(conn, "COPY copy_demo (id, name) FROM STDIN", "1\talpha\n2\tbeta\n")
bytes = Postgres.copy_to(conn, "COPY copy_demo TO STDOUT (FORMAT BINARY)")
Postgres.copy_from(conn, "COPY copy_demo FROM STDIN (FORMAT BINARY)", bytes)
DBInterface.close!(conn)

LISTEN/NOTIFY

using Postgres, DBInterface
listener = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
notifier = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.listen!(listener, "events")
Postgres.notify!(notifier, "events", "hello")
notice = Postgres.wait_for_notification(listener; timeout=5.0)
@show notice.channel notice.payload
DBInterface.close!(notifier)
DBInterface.close!(listener)

Cursor streaming

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
cur = Postgres.cursor(conn, "SELECT generate_series(1, 5) AS n"; fetchsize=2)
for row in cur
@show row.n
end
DBInterface.close!(cur)
DBInterface.close!(conn)

Type registry

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')")
Postgres.register_enum!(conn, "mood")
row =only(Tables.rowtable(DBInterface.execute(conn, "SELECT 'happy'::mood AS mood")))
@show row.mood
DBInterface.close!(conn)

Numeric values are returned as Postgres.Numeric, interval values as Dates.Period or Dates.CompoundPeriod, and range types as Postgres.PostgresRange{T}. Custom enum, composite, and range registration controls result decoding. Those custom Julia values are not accepted as direct query parameters in 1.0; bind a PostgreSQL text representation with an explicit SQL cast instead.

Query logging and driver styles

Driver behavior — query logging, server notices, asynchronous notifications — is customized by defining a driver "style": subtype Postgres.AbstractPostgresStyle, overload the behavior hooks for it, and pass an instance via the style connection keyword.

using Postgres, DBInterface
struct LoggingStyle <:Postgres.AbstractPostgresStyleend
Postgres.query_logging_enabled(::LoggingStyle) =true
Postgres.query_logger(::LoggingStyle, event::Symbol, info::NamedTuple) =@info"query" event info.success info.duration_ns
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; style=LoggingStyle())
DBInterface.execute(conn, "SELECT 1")
DBInterface.close!(conn)

Connection pooling

using Postgres, DBInterface
pool = Postgres.ConnectionPool(Postgres.Connection, "127.0.0.1", "postgres", "postgres"; dbname="postgres", limit=5)
Postgres.with_connection(pool) do conn
DBInterface.execute(conn, "SELECT 1")
end
DBInterface.close!(pool)

Errors and cancellation

Postgres.Error represents server errors and includes SQLSTATE codes; Postgres.PostgresInterfaceError covers client-side failures. Use Postgres.cancel_query!(conn) to send a CancelRequest to the server.

Development disclosure

The 1.0 release preparation used Claude Code and OpenAI Codex for implementation assistance and adversarial review. Maintainer decisions, source history, review discussion, and validation results are recorded in pull request #5.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from quinnj/Example.jl
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - JuliaDatabases/Postgres.jl · GitHub
Skip to content

Repository files navigation

Postgres.jl

CIdocscodecov

Postgres.jl is a PostgreSQL client written in Julia that implements the v3 wire protocol with DBInterface and Tables integration.

Installation

import Pkg
Pkg.add("Postgres")

Quick start

using Postgres
DBInterface.connect(Postgres.Connection, "host=127.0.0.1;port=5432;user=postgres;password=postgres;dbname=postgres") do conn
row =only(DBInterface.execute(conn, "SELECT 1 AS a"))
@show row.a
end

Connections

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "postgresql://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable")
DBInterface.close!(conn)

Connection options support:

  • libpq-style keyword strings such as host=127.0.0.1 port=5432 user=postgres dbname=postgres.
  • PostgreSQL URIs such as postgresql://postgres:postgres@127.0.0.1:5432/postgres.
  • Environment defaults: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGAPPNAME, PGCONNECT_TIMEOUT, and TLS-related PGSSL* variables.
  • sslmode values: disable, prefer (the default), require, verify-full. Only verify-full verifies the server's certificate; require encrypts without authenticating the server, and the default prefer falls back to an unencrypted connection if the server declines TLS. Use verify-full with sslrootcert when the connection needs to be authenticated.
  • TLS files: sslrootcert, sslcert, sslkey, and sslcapath (sslcapath is a fallback CA bundle or directory, used only when sslrootcert is unset and ignored otherwise). sslservername overrides the TLS server name when connecting to a pre-resolved address; under verify-full it is also the name the certificate is verified against, so it must name the server you intend to authenticate.
  • connect_timeout (seconds) and statement_timeout (milliseconds).
  • application_name and statement_cache_maxsize.

See the 1.0 support policy for tested Julia and PostgreSQL versions, TLS limits, and transaction-pooler requirements.

You can also use ConnectionParams:

using Postgres, DBInterface
params = Postgres.ConnectionParams(host="127.0.0.1", user="postgres", password="postgres", dbname="postgres", sslmode="disable")
conn = DBInterface.connect(Postgres.Connection, params)
DBInterface.close!(conn)

Queries and prepared statements

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
rows = Tables.rowtable(DBInterface.execute(conn, raw"SELECT $1::int AS val", (42,)))
@show rows[1].val
stmt = DBInterface.prepare(conn, raw"SELECT $1::int AS val")
rows = Tables.rowtable(DBInterface.execute(stmt, (7,)))
DBInterface.close!(stmt)
DBInterface.close!(conn)

Postgres.jl can also deserialize result rows directly into structs through StructUtils.jl. If column names match field names, pass the target type as the fourth DBInterface.execute argument.

using Postgres, DBInterface, StructUtils
struct CountRow
count::Intend
row = DBInterface.execute(conn, "SELECT count(*)::int AS count FROM users", (), CountRow)
@show row.count

Use StructUtils.@tags with the postgres namespace when table columns use a different naming convention than Julia fields.

using Dates, Postgres, DBInterface, StructUtils
StructUtils.@tagsstruct ProfileSummary
profileId::Int&(postgres=(name=:profile_id,),)
firstName::Union{Missing, String}&(postgres=(name=:first_name,),)
lastName::Union{Missing, String}&(postgres=(name=:last_name,),)
createdAt::DateTime&(postgres=(name=:created_at,),)
end
profile = DBInterface.execute(conn, raw""" SELECT profile_id, first_name, last_name, created_at FROM profiles WHERE profile_id = $1""", (profile_id,), ProfileSummary)
profiles = DBInterface.execute(conn, """ SELECT profile_id, first_name, last_name, created_at FROM profiles ORDER BY created_at DESC LIMIT 10""", (), Vector{ProfileSummary})

Postgres.command_tag(result) and Postgres.rows_affected(result) expose PostgreSQL command completion metadata.

Explicit named prepared statements use an LRU backend cache. Caller handles are independent. Set statement_cache_maxsize=0 to disable this cache.

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; statement_cache_maxsize=10)
Postgres.set_statement_cache_maxsize!(conn, 5)
cached = Postgres.get_cached_statements(conn)
Postgres.clear_statement_cache!(conn)
DBInterface.close!(conn)

Transactions

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.transaction(conn) do tx
DBInterface.execute(tx, "CREATE TEMP TABLE tx_demo (id int)")
DBInterface.execute(tx, "INSERT INTO tx_demo VALUES (1)")
end
Postgres.@transaction conn begin
DBInterface.execute(conn, "INSERT INTO tx_demo VALUES (2)")
end
DBInterface.close!(conn)

Nested transactions are implemented with savepoints.

COPY protocol

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TEMP TABLE copy_demo (id int, name text)")
Postgres.copy_from(conn, "COPY copy_demo (id, name) FROM STDIN", "1\talpha\n2\tbeta\n")
bytes = Postgres.copy_to(conn, "COPY copy_demo TO STDOUT (FORMAT BINARY)")
Postgres.copy_from(conn, "COPY copy_demo FROM STDIN (FORMAT BINARY)", bytes)
DBInterface.close!(conn)

LISTEN/NOTIFY

using Postgres, DBInterface
listener = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
notifier = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.listen!(listener, "events")
Postgres.notify!(notifier, "events", "hello")
notice = Postgres.wait_for_notification(listener; timeout=5.0)
@show notice.channel notice.payload
DBInterface.close!(notifier)
DBInterface.close!(listener)

Cursor streaming

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
cur = Postgres.cursor(conn, "SELECT generate_series(1, 5) AS n"; fetchsize=2)
for row in cur
@show row.n
end
DBInterface.close!(cur)
DBInterface.close!(conn)

Type registry

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')")
Postgres.register_enum!(conn, "mood")
row =only(Tables.rowtable(DBInterface.execute(conn, "SELECT 'happy'::mood AS mood")))
@show row.mood
DBInterface.close!(conn)

Numeric values are returned as Postgres.Numeric, interval values as Dates.Period or Dates.CompoundPeriod, and range types as Postgres.PostgresRange{T}. Custom enum, composite, and range registration controls result decoding. Those custom Julia values are not accepted as direct query parameters in 1.0; bind a PostgreSQL text representation with an explicit SQL cast instead.

Query logging and driver styles

Driver behavior — query logging, server notices, asynchronous notifications — is customized by defining a driver "style": subtype Postgres.AbstractPostgresStyle, overload the behavior hooks for it, and pass an instance via the style connection keyword.

using Postgres, DBInterface
struct LoggingStyle <:Postgres.AbstractPostgresStyleend
Postgres.query_logging_enabled(::LoggingStyle) =true
Postgres.query_logger(::LoggingStyle, event::Symbol, info::NamedTuple) =@info"query" event info.success info.duration_ns
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; style=LoggingStyle())
DBInterface.execute(conn, "SELECT 1")
DBInterface.close!(conn)

Connection pooling

using Postgres, DBInterface
pool = Postgres.ConnectionPool(Postgres.Connection, "127.0.0.1", "postgres", "postgres"; dbname="postgres", limit=5)
Postgres.with_connection(pool) do conn
DBInterface.execute(conn, "SELECT 1")
end
DBInterface.close!(pool)

Errors and cancellation

Postgres.Error represents server errors and includes SQLSTATE codes; Postgres.PostgresInterfaceError covers client-side failures. Use Postgres.cancel_query!(conn) to send a CancelRequest to the server.

Development disclosure

The 1.0 release preparation used Claude Code and OpenAI Codex for implementation assistance and adversarial review. Maintainer decisions, source history, review discussion, and validation results are recorded in pull request #5.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from quinnj/Example.jl
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - JuliaDatabases/Postgres.jl · GitHub
Skip to content

Repository files navigation

Postgres.jl

CIdocscodecov

Postgres.jl is a PostgreSQL client written in Julia that implements the v3 wire protocol with DBInterface and Tables integration.

Installation

import Pkg
Pkg.add("Postgres")

Quick start

using Postgres
DBInterface.connect(Postgres.Connection, "host=127.0.0.1;port=5432;user=postgres;password=postgres;dbname=postgres") do conn
row =only(DBInterface.execute(conn, "SELECT 1 AS a"))
@show row.a
end

Connections

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "postgresql://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable")
DBInterface.close!(conn)

Connection options support:

  • libpq-style keyword strings such as host=127.0.0.1 port=5432 user=postgres dbname=postgres.
  • PostgreSQL URIs such as postgresql://postgres:postgres@127.0.0.1:5432/postgres.
  • Environment defaults: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGAPPNAME, PGCONNECT_TIMEOUT, and TLS-related PGSSL* variables.
  • sslmode values: disable, prefer (the default), require, verify-full. Only verify-full verifies the server's certificate; require encrypts without authenticating the server, and the default prefer falls back to an unencrypted connection if the server declines TLS. Use verify-full with sslrootcert when the connection needs to be authenticated.
  • TLS files: sslrootcert, sslcert, sslkey, and sslcapath (sslcapath is a fallback CA bundle or directory, used only when sslrootcert is unset and ignored otherwise). sslservername overrides the TLS server name when connecting to a pre-resolved address; under verify-full it is also the name the certificate is verified against, so it must name the server you intend to authenticate.
  • connect_timeout (seconds) and statement_timeout (milliseconds).
  • application_name and statement_cache_maxsize.

See the 1.0 support policy for tested Julia and PostgreSQL versions, TLS limits, and transaction-pooler requirements.

You can also use ConnectionParams:

using Postgres, DBInterface
params = Postgres.ConnectionParams(host="127.0.0.1", user="postgres", password="postgres", dbname="postgres", sslmode="disable")
conn = DBInterface.connect(Postgres.Connection, params)
DBInterface.close!(conn)

Queries and prepared statements

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
rows = Tables.rowtable(DBInterface.execute(conn, raw"SELECT $1::int AS val", (42,)))
@show rows[1].val
stmt = DBInterface.prepare(conn, raw"SELECT $1::int AS val")
rows = Tables.rowtable(DBInterface.execute(stmt, (7,)))
DBInterface.close!(stmt)
DBInterface.close!(conn)

Postgres.jl can also deserialize result rows directly into structs through StructUtils.jl. If column names match field names, pass the target type as the fourth DBInterface.execute argument.

using Postgres, DBInterface, StructUtils
struct CountRow
count::Intend
row = DBInterface.execute(conn, "SELECT count(*)::int AS count FROM users", (), CountRow)
@show row.count

Use StructUtils.@tags with the postgres namespace when table columns use a different naming convention than Julia fields.

using Dates, Postgres, DBInterface, StructUtils
StructUtils.@tagsstruct ProfileSummary
profileId::Int&(postgres=(name=:profile_id,),)
firstName::Union{Missing, String}&(postgres=(name=:first_name,),)
lastName::Union{Missing, String}&(postgres=(name=:last_name,),)
createdAt::DateTime&(postgres=(name=:created_at,),)
end
profile = DBInterface.execute(conn, raw""" SELECT profile_id, first_name, last_name, created_at FROM profiles WHERE profile_id = $1""", (profile_id,), ProfileSummary)
profiles = DBInterface.execute(conn, """ SELECT profile_id, first_name, last_name, created_at FROM profiles ORDER BY created_at DESC LIMIT 10""", (), Vector{ProfileSummary})

Postgres.command_tag(result) and Postgres.rows_affected(result) expose PostgreSQL command completion metadata.

Explicit named prepared statements use an LRU backend cache. Caller handles are independent. Set statement_cache_maxsize=0 to disable this cache.

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; statement_cache_maxsize=10)
Postgres.set_statement_cache_maxsize!(conn, 5)
cached = Postgres.get_cached_statements(conn)
Postgres.clear_statement_cache!(conn)
DBInterface.close!(conn)

Transactions

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.transaction(conn) do tx
DBInterface.execute(tx, "CREATE TEMP TABLE tx_demo (id int)")
DBInterface.execute(tx, "INSERT INTO tx_demo VALUES (1)")
end
Postgres.@transaction conn begin
DBInterface.execute(conn, "INSERT INTO tx_demo VALUES (2)")
end
DBInterface.close!(conn)

Nested transactions are implemented with savepoints.

COPY protocol

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TEMP TABLE copy_demo (id int, name text)")
Postgres.copy_from(conn, "COPY copy_demo (id, name) FROM STDIN", "1\talpha\n2\tbeta\n")
bytes = Postgres.copy_to(conn, "COPY copy_demo TO STDOUT (FORMAT BINARY)")
Postgres.copy_from(conn, "COPY copy_demo FROM STDIN (FORMAT BINARY)", bytes)
DBInterface.close!(conn)

LISTEN/NOTIFY

using Postgres, DBInterface
listener = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
notifier = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.listen!(listener, "events")
Postgres.notify!(notifier, "events", "hello")
notice = Postgres.wait_for_notification(listener; timeout=5.0)
@show notice.channel notice.payload
DBInterface.close!(notifier)
DBInterface.close!(listener)

Cursor streaming

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
cur = Postgres.cursor(conn, "SELECT generate_series(1, 5) AS n"; fetchsize=2)
for row in cur
@show row.n
end
DBInterface.close!(cur)
DBInterface.close!(conn)

Type registry

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')")
Postgres.register_enum!(conn, "mood")
row =only(Tables.rowtable(DBInterface.execute(conn, "SELECT 'happy'::mood AS mood")))
@show row.mood
DBInterface.close!(conn)

Numeric values are returned as Postgres.Numeric, interval values as Dates.Period or Dates.CompoundPeriod, and range types as Postgres.PostgresRange{T}. Custom enum, composite, and range registration controls result decoding. Those custom Julia values are not accepted as direct query parameters in 1.0; bind a PostgreSQL text representation with an explicit SQL cast instead.

Query logging and driver styles

Driver behavior — query logging, server notices, asynchronous notifications — is customized by defining a driver "style": subtype Postgres.AbstractPostgresStyle, overload the behavior hooks for it, and pass an instance via the style connection keyword.

using Postgres, DBInterface
struct LoggingStyle <:Postgres.AbstractPostgresStyleend
Postgres.query_logging_enabled(::LoggingStyle) =true
Postgres.query_logger(::LoggingStyle, event::Symbol, info::NamedTuple) =@info"query" event info.success info.duration_ns
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; style=LoggingStyle())
DBInterface.execute(conn, "SELECT 1")
DBInterface.close!(conn)

Connection pooling

using Postgres, DBInterface
pool = Postgres.ConnectionPool(Postgres.Connection, "127.0.0.1", "postgres", "postgres"; dbname="postgres", limit=5)
Postgres.with_connection(pool) do conn
DBInterface.execute(conn, "SELECT 1")
end
DBInterface.close!(pool)

Errors and cancellation

Postgres.Error represents server errors and includes SQLSTATE codes; Postgres.PostgresInterfaceError covers client-side failures. Use Postgres.cancel_query!(conn) to send a CancelRequest to the server.

Development disclosure

The 1.0 release preparation used Claude Code and OpenAI Codex for implementation assistance and adversarial review. Maintainer decisions, source history, review discussion, and validation results are recorded in pull request #5.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from quinnj/Example.jl
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - JuliaDatabases/Postgres.jl · GitHub
Skip to content

Repository files navigation

Postgres.jl

CIdocscodecov

Postgres.jl is a PostgreSQL client written in Julia that implements the v3 wire protocol with DBInterface and Tables integration.

Installation

import Pkg
Pkg.add("Postgres")

Quick start

using Postgres
DBInterface.connect(Postgres.Connection, "host=127.0.0.1;port=5432;user=postgres;password=postgres;dbname=postgres") do conn
row =only(DBInterface.execute(conn, "SELECT 1 AS a"))
@show row.a
end

Connections

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "postgresql://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable")
DBInterface.close!(conn)

Connection options support:

  • libpq-style keyword strings such as host=127.0.0.1 port=5432 user=postgres dbname=postgres.
  • PostgreSQL URIs such as postgresql://postgres:postgres@127.0.0.1:5432/postgres.
  • Environment defaults: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGAPPNAME, PGCONNECT_TIMEOUT, and TLS-related PGSSL* variables.
  • sslmode values: disable, prefer (the default), require, verify-full. Only verify-full verifies the server's certificate; require encrypts without authenticating the server, and the default prefer falls back to an unencrypted connection if the server declines TLS. Use verify-full with sslrootcert when the connection needs to be authenticated.
  • TLS files: sslrootcert, sslcert, sslkey, and sslcapath (sslcapath is a fallback CA bundle or directory, used only when sslrootcert is unset and ignored otherwise). sslservername overrides the TLS server name when connecting to a pre-resolved address; under verify-full it is also the name the certificate is verified against, so it must name the server you intend to authenticate.
  • connect_timeout (seconds) and statement_timeout (milliseconds).
  • application_name and statement_cache_maxsize.

See the 1.0 support policy for tested Julia and PostgreSQL versions, TLS limits, and transaction-pooler requirements.

You can also use ConnectionParams:

using Postgres, DBInterface
params = Postgres.ConnectionParams(host="127.0.0.1", user="postgres", password="postgres", dbname="postgres", sslmode="disable")
conn = DBInterface.connect(Postgres.Connection, params)
DBInterface.close!(conn)

Queries and prepared statements

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
rows = Tables.rowtable(DBInterface.execute(conn, raw"SELECT $1::int AS val", (42,)))
@show rows[1].val
stmt = DBInterface.prepare(conn, raw"SELECT $1::int AS val")
rows = Tables.rowtable(DBInterface.execute(stmt, (7,)))
DBInterface.close!(stmt)
DBInterface.close!(conn)

Postgres.jl can also deserialize result rows directly into structs through StructUtils.jl. If column names match field names, pass the target type as the fourth DBInterface.execute argument.

using Postgres, DBInterface, StructUtils
struct CountRow
count::Intend
row = DBInterface.execute(conn, "SELECT count(*)::int AS count FROM users", (), CountRow)
@show row.count

Use StructUtils.@tags with the postgres namespace when table columns use a different naming convention than Julia fields.

using Dates, Postgres, DBInterface, StructUtils
StructUtils.@tagsstruct ProfileSummary
profileId::Int&(postgres=(name=:profile_id,),)
firstName::Union{Missing, String}&(postgres=(name=:first_name,),)
lastName::Union{Missing, String}&(postgres=(name=:last_name,),)
createdAt::DateTime&(postgres=(name=:created_at,),)
end
profile = DBInterface.execute(conn, raw""" SELECT profile_id, first_name, last_name, created_at FROM profiles WHERE profile_id = $1""", (profile_id,), ProfileSummary)
profiles = DBInterface.execute(conn, """ SELECT profile_id, first_name, last_name, created_at FROM profiles ORDER BY created_at DESC LIMIT 10""", (), Vector{ProfileSummary})

Postgres.command_tag(result) and Postgres.rows_affected(result) expose PostgreSQL command completion metadata.

Explicit named prepared statements use an LRU backend cache. Caller handles are independent. Set statement_cache_maxsize=0 to disable this cache.

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; statement_cache_maxsize=10)
Postgres.set_statement_cache_maxsize!(conn, 5)
cached = Postgres.get_cached_statements(conn)
Postgres.clear_statement_cache!(conn)
DBInterface.close!(conn)

Transactions

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.transaction(conn) do tx
DBInterface.execute(tx, "CREATE TEMP TABLE tx_demo (id int)")
DBInterface.execute(tx, "INSERT INTO tx_demo VALUES (1)")
end
Postgres.@transaction conn begin
DBInterface.execute(conn, "INSERT INTO tx_demo VALUES (2)")
end
DBInterface.close!(conn)

Nested transactions are implemented with savepoints.

COPY protocol

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TEMP TABLE copy_demo (id int, name text)")
Postgres.copy_from(conn, "COPY copy_demo (id, name) FROM STDIN", "1\talpha\n2\tbeta\n")
bytes = Postgres.copy_to(conn, "COPY copy_demo TO STDOUT (FORMAT BINARY)")
Postgres.copy_from(conn, "COPY copy_demo FROM STDIN (FORMAT BINARY)", bytes)
DBInterface.close!(conn)

LISTEN/NOTIFY

using Postgres, DBInterface
listener = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
notifier = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.listen!(listener, "events")
Postgres.notify!(notifier, "events", "hello")
notice = Postgres.wait_for_notification(listener; timeout=5.0)
@show notice.channel notice.payload
DBInterface.close!(notifier)
DBInterface.close!(listener)

Cursor streaming

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
cur = Postgres.cursor(conn, "SELECT generate_series(1, 5) AS n"; fetchsize=2)
for row in cur
@show row.n
end
DBInterface.close!(cur)
DBInterface.close!(conn)

Type registry

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')")
Postgres.register_enum!(conn, "mood")
row =only(Tables.rowtable(DBInterface.execute(conn, "SELECT 'happy'::mood AS mood")))
@show row.mood
DBInterface.close!(conn)

Numeric values are returned as Postgres.Numeric, interval values as Dates.Period or Dates.CompoundPeriod, and range types as Postgres.PostgresRange{T}. Custom enum, composite, and range registration controls result decoding. Those custom Julia values are not accepted as direct query parameters in 1.0; bind a PostgreSQL text representation with an explicit SQL cast instead.

Query logging and driver styles

Driver behavior — query logging, server notices, asynchronous notifications — is customized by defining a driver "style": subtype Postgres.AbstractPostgresStyle, overload the behavior hooks for it, and pass an instance via the style connection keyword.

using Postgres, DBInterface
struct LoggingStyle <:Postgres.AbstractPostgresStyleend
Postgres.query_logging_enabled(::LoggingStyle) =true
Postgres.query_logger(::LoggingStyle, event::Symbol, info::NamedTuple) =@info"query" event info.success info.duration_ns
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; style=LoggingStyle())
DBInterface.execute(conn, "SELECT 1")
DBInterface.close!(conn)

Connection pooling

using Postgres, DBInterface
pool = Postgres.ConnectionPool(Postgres.Connection, "127.0.0.1", "postgres", "postgres"; dbname="postgres", limit=5)
Postgres.with_connection(pool) do conn
DBInterface.execute(conn, "SELECT 1")
end
DBInterface.close!(pool)

Errors and cancellation

Postgres.Error represents server errors and includes SQLSTATE codes; Postgres.PostgresInterfaceError covers client-side failures. Use Postgres.cancel_query!(conn) to send a CancelRequest to the server.

Development disclosure

The 1.0 release preparation used Claude Code and OpenAI Codex for implementation assistance and adversarial review. Maintainer decisions, source history, review discussion, and validation results are recorded in pull request #5.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from quinnj/Example.jl
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - JuliaDatabases/Postgres.jl · GitHub
Skip to content

Repository files navigation

Postgres.jl

CIdocscodecov

Postgres.jl is a PostgreSQL client written in Julia that implements the v3 wire protocol with DBInterface and Tables integration.

Installation

import Pkg
Pkg.add("Postgres")

Quick start

using Postgres
DBInterface.connect(Postgres.Connection, "host=127.0.0.1;port=5432;user=postgres;password=postgres;dbname=postgres") do conn
row =only(DBInterface.execute(conn, "SELECT 1 AS a"))
@show row.a
end

Connections

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "postgresql://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable")
DBInterface.close!(conn)

Connection options support:

  • libpq-style keyword strings such as host=127.0.0.1 port=5432 user=postgres dbname=postgres.
  • PostgreSQL URIs such as postgresql://postgres:postgres@127.0.0.1:5432/postgres.
  • Environment defaults: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGAPPNAME, PGCONNECT_TIMEOUT, and TLS-related PGSSL* variables.
  • sslmode values: disable, prefer (the default), require, verify-full. Only verify-full verifies the server's certificate; require encrypts without authenticating the server, and the default prefer falls back to an unencrypted connection if the server declines TLS. Use verify-full with sslrootcert when the connection needs to be authenticated.
  • TLS files: sslrootcert, sslcert, sslkey, and sslcapath (sslcapath is a fallback CA bundle or directory, used only when sslrootcert is unset and ignored otherwise). sslservername overrides the TLS server name when connecting to a pre-resolved address; under verify-full it is also the name the certificate is verified against, so it must name the server you intend to authenticate.
  • connect_timeout (seconds) and statement_timeout (milliseconds).
  • application_name and statement_cache_maxsize.

See the 1.0 support policy for tested Julia and PostgreSQL versions, TLS limits, and transaction-pooler requirements.

You can also use ConnectionParams:

using Postgres, DBInterface
params = Postgres.ConnectionParams(host="127.0.0.1", user="postgres", password="postgres", dbname="postgres", sslmode="disable")
conn = DBInterface.connect(Postgres.Connection, params)
DBInterface.close!(conn)

Queries and prepared statements

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
rows = Tables.rowtable(DBInterface.execute(conn, raw"SELECT $1::int AS val", (42,)))
@show rows[1].val
stmt = DBInterface.prepare(conn, raw"SELECT $1::int AS val")
rows = Tables.rowtable(DBInterface.execute(stmt, (7,)))
DBInterface.close!(stmt)
DBInterface.close!(conn)

Postgres.jl can also deserialize result rows directly into structs through StructUtils.jl. If column names match field names, pass the target type as the fourth DBInterface.execute argument.

using Postgres, DBInterface, StructUtils
struct CountRow
count::Intend
row = DBInterface.execute(conn, "SELECT count(*)::int AS count FROM users", (), CountRow)
@show row.count

Use StructUtils.@tags with the postgres namespace when table columns use a different naming convention than Julia fields.

using Dates, Postgres, DBInterface, StructUtils
StructUtils.@tagsstruct ProfileSummary
profileId::Int&(postgres=(name=:profile_id,),)
firstName::Union{Missing, String}&(postgres=(name=:first_name,),)
lastName::Union{Missing, String}&(postgres=(name=:last_name,),)
createdAt::DateTime&(postgres=(name=:created_at,),)
end
profile = DBInterface.execute(conn, raw""" SELECT profile_id, first_name, last_name, created_at FROM profiles WHERE profile_id = $1""", (profile_id,), ProfileSummary)
profiles = DBInterface.execute(conn, """ SELECT profile_id, first_name, last_name, created_at FROM profiles ORDER BY created_at DESC LIMIT 10""", (), Vector{ProfileSummary})

Postgres.command_tag(result) and Postgres.rows_affected(result) expose PostgreSQL command completion metadata.

Explicit named prepared statements use an LRU backend cache. Caller handles are independent. Set statement_cache_maxsize=0 to disable this cache.

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; statement_cache_maxsize=10)
Postgres.set_statement_cache_maxsize!(conn, 5)
cached = Postgres.get_cached_statements(conn)
Postgres.clear_statement_cache!(conn)
DBInterface.close!(conn)

Transactions

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.transaction(conn) do tx
DBInterface.execute(tx, "CREATE TEMP TABLE tx_demo (id int)")
DBInterface.execute(tx, "INSERT INTO tx_demo VALUES (1)")
end
Postgres.@transaction conn begin
DBInterface.execute(conn, "INSERT INTO tx_demo VALUES (2)")
end
DBInterface.close!(conn)

Nested transactions are implemented with savepoints.

COPY protocol

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TEMP TABLE copy_demo (id int, name text)")
Postgres.copy_from(conn, "COPY copy_demo (id, name) FROM STDIN", "1\talpha\n2\tbeta\n")
bytes = Postgres.copy_to(conn, "COPY copy_demo TO STDOUT (FORMAT BINARY)")
Postgres.copy_from(conn, "COPY copy_demo FROM STDIN (FORMAT BINARY)", bytes)
DBInterface.close!(conn)

LISTEN/NOTIFY

using Postgres, DBInterface
listener = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
notifier = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.listen!(listener, "events")
Postgres.notify!(notifier, "events", "hello")
notice = Postgres.wait_for_notification(listener; timeout=5.0)
@show notice.channel notice.payload
DBInterface.close!(notifier)
DBInterface.close!(listener)

Cursor streaming

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
cur = Postgres.cursor(conn, "SELECT generate_series(1, 5) AS n"; fetchsize=2)
for row in cur
@show row.n
end
DBInterface.close!(cur)
DBInterface.close!(conn)

Type registry

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')")
Postgres.register_enum!(conn, "mood")
row =only(Tables.rowtable(DBInterface.execute(conn, "SELECT 'happy'::mood AS mood")))
@show row.mood
DBInterface.close!(conn)

Numeric values are returned as Postgres.Numeric, interval values as Dates.Period or Dates.CompoundPeriod, and range types as Postgres.PostgresRange{T}. Custom enum, composite, and range registration controls result decoding. Those custom Julia values are not accepted as direct query parameters in 1.0; bind a PostgreSQL text representation with an explicit SQL cast instead.

Query logging and driver styles

Driver behavior — query logging, server notices, asynchronous notifications — is customized by defining a driver "style": subtype Postgres.AbstractPostgresStyle, overload the behavior hooks for it, and pass an instance via the style connection keyword.

using Postgres, DBInterface
struct LoggingStyle <:Postgres.AbstractPostgresStyleend
Postgres.query_logging_enabled(::LoggingStyle) =true
Postgres.query_logger(::LoggingStyle, event::Symbol, info::NamedTuple) =@info"query" event info.success info.duration_ns
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; style=LoggingStyle())
DBInterface.execute(conn, "SELECT 1")
DBInterface.close!(conn)

Connection pooling

using Postgres, DBInterface
pool = Postgres.ConnectionPool(Postgres.Connection, "127.0.0.1", "postgres", "postgres"; dbname="postgres", limit=5)
Postgres.with_connection(pool) do conn
DBInterface.execute(conn, "SELECT 1")
end
DBInterface.close!(pool)

Errors and cancellation

Postgres.Error represents server errors and includes SQLSTATE codes; Postgres.PostgresInterfaceError covers client-side failures. Use Postgres.cancel_query!(conn) to send a CancelRequest to the server.

Development disclosure

The 1.0 release preparation used Claude Code and OpenAI Codex for implementation assistance and adversarial review. Maintainer decisions, source history, review discussion, and validation results are recorded in pull request #5.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from quinnj/Example.jl
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - JuliaDatabases/Postgres.jl · GitHub
Skip to content

Repository files navigation

Postgres.jl

CIdocscodecov

Postgres.jl is a PostgreSQL client written in Julia that implements the v3 wire protocol with DBInterface and Tables integration.

Installation

import Pkg
Pkg.add("Postgres")

Quick start

using Postgres
DBInterface.connect(Postgres.Connection, "host=127.0.0.1;port=5432;user=postgres;password=postgres;dbname=postgres") do conn
row =only(DBInterface.execute(conn, "SELECT 1 AS a"))
@show row.a
end

Connections

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "postgresql://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable")
DBInterface.close!(conn)

Connection options support:

  • libpq-style keyword strings such as host=127.0.0.1 port=5432 user=postgres dbname=postgres.
  • PostgreSQL URIs such as postgresql://postgres:postgres@127.0.0.1:5432/postgres.
  • Environment defaults: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGAPPNAME, PGCONNECT_TIMEOUT, and TLS-related PGSSL* variables.
  • sslmode values: disable, prefer (the default), require, verify-full. Only verify-full verifies the server's certificate; require encrypts without authenticating the server, and the default prefer falls back to an unencrypted connection if the server declines TLS. Use verify-full with sslrootcert when the connection needs to be authenticated.
  • TLS files: sslrootcert, sslcert, sslkey, and sslcapath (sslcapath is a fallback CA bundle or directory, used only when sslrootcert is unset and ignored otherwise). sslservername overrides the TLS server name when connecting to a pre-resolved address; under verify-full it is also the name the certificate is verified against, so it must name the server you intend to authenticate.
  • connect_timeout (seconds) and statement_timeout (milliseconds).
  • application_name and statement_cache_maxsize.

See the 1.0 support policy for tested Julia and PostgreSQL versions, TLS limits, and transaction-pooler requirements.

You can also use ConnectionParams:

using Postgres, DBInterface
params = Postgres.ConnectionParams(host="127.0.0.1", user="postgres", password="postgres", dbname="postgres", sslmode="disable")
conn = DBInterface.connect(Postgres.Connection, params)
DBInterface.close!(conn)

Queries and prepared statements

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
rows = Tables.rowtable(DBInterface.execute(conn, raw"SELECT $1::int AS val", (42,)))
@show rows[1].val
stmt = DBInterface.prepare(conn, raw"SELECT $1::int AS val")
rows = Tables.rowtable(DBInterface.execute(stmt, (7,)))
DBInterface.close!(stmt)
DBInterface.close!(conn)

Postgres.jl can also deserialize result rows directly into structs through StructUtils.jl. If column names match field names, pass the target type as the fourth DBInterface.execute argument.

using Postgres, DBInterface, StructUtils
struct CountRow
count::Intend
row = DBInterface.execute(conn, "SELECT count(*)::int AS count FROM users", (), CountRow)
@show row.count

Use StructUtils.@tags with the postgres namespace when table columns use a different naming convention than Julia fields.

using Dates, Postgres, DBInterface, StructUtils
StructUtils.@tagsstruct ProfileSummary
profileId::Int&(postgres=(name=:profile_id,),)
firstName::Union{Missing, String}&(postgres=(name=:first_name,),)
lastName::Union{Missing, String}&(postgres=(name=:last_name,),)
createdAt::DateTime&(postgres=(name=:created_at,),)
end
profile = DBInterface.execute(conn, raw""" SELECT profile_id, first_name, last_name, created_at FROM profiles WHERE profile_id = $1""", (profile_id,), ProfileSummary)
profiles = DBInterface.execute(conn, """ SELECT profile_id, first_name, last_name, created_at FROM profiles ORDER BY created_at DESC LIMIT 10""", (), Vector{ProfileSummary})

Postgres.command_tag(result) and Postgres.rows_affected(result) expose PostgreSQL command completion metadata.

Explicit named prepared statements use an LRU backend cache. Caller handles are independent. Set statement_cache_maxsize=0 to disable this cache.

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; statement_cache_maxsize=10)
Postgres.set_statement_cache_maxsize!(conn, 5)
cached = Postgres.get_cached_statements(conn)
Postgres.clear_statement_cache!(conn)
DBInterface.close!(conn)

Transactions

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.transaction(conn) do tx
DBInterface.execute(tx, "CREATE TEMP TABLE tx_demo (id int)")
DBInterface.execute(tx, "INSERT INTO tx_demo VALUES (1)")
end
Postgres.@transaction conn begin
DBInterface.execute(conn, "INSERT INTO tx_demo VALUES (2)")
end
DBInterface.close!(conn)

Nested transactions are implemented with savepoints.

COPY protocol

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TEMP TABLE copy_demo (id int, name text)")
Postgres.copy_from(conn, "COPY copy_demo (id, name) FROM STDIN", "1\talpha\n2\tbeta\n")
bytes = Postgres.copy_to(conn, "COPY copy_demo TO STDOUT (FORMAT BINARY)")
Postgres.copy_from(conn, "COPY copy_demo FROM STDIN (FORMAT BINARY)", bytes)
DBInterface.close!(conn)

LISTEN/NOTIFY

using Postgres, DBInterface
listener = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
notifier = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.listen!(listener, "events")
Postgres.notify!(notifier, "events", "hello")
notice = Postgres.wait_for_notification(listener; timeout=5.0)
@show notice.channel notice.payload
DBInterface.close!(notifier)
DBInterface.close!(listener)

Cursor streaming

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
cur = Postgres.cursor(conn, "SELECT generate_series(1, 5) AS n"; fetchsize=2)
for row in cur
@show row.n
end
DBInterface.close!(cur)
DBInterface.close!(conn)

Type registry

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')")
Postgres.register_enum!(conn, "mood")
row =only(Tables.rowtable(DBInterface.execute(conn, "SELECT 'happy'::mood AS mood")))
@show row.mood
DBInterface.close!(conn)

Numeric values are returned as Postgres.Numeric, interval values as Dates.Period or Dates.CompoundPeriod, and range types as Postgres.PostgresRange{T}. Custom enum, composite, and range registration controls result decoding. Those custom Julia values are not accepted as direct query parameters in 1.0; bind a PostgreSQL text representation with an explicit SQL cast instead.

Query logging and driver styles

Driver behavior — query logging, server notices, asynchronous notifications — is customized by defining a driver "style": subtype Postgres.AbstractPostgresStyle, overload the behavior hooks for it, and pass an instance via the style connection keyword.

using Postgres, DBInterface
struct LoggingStyle <:Postgres.AbstractPostgresStyleend
Postgres.query_logging_enabled(::LoggingStyle) =true
Postgres.query_logger(::LoggingStyle, event::Symbol, info::NamedTuple) =@info"query" event info.success info.duration_ns
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; style=LoggingStyle())
DBInterface.execute(conn, "SELECT 1")
DBInterface.close!(conn)

Connection pooling

using Postgres, DBInterface
pool = Postgres.ConnectionPool(Postgres.Connection, "127.0.0.1", "postgres", "postgres"; dbname="postgres", limit=5)
Postgres.with_connection(pool) do conn
DBInterface.execute(conn, "SELECT 1")
end
DBInterface.close!(pool)

Errors and cancellation

Postgres.Error represents server errors and includes SQLSTATE codes; Postgres.PostgresInterfaceError covers client-side failures. Use Postgres.cancel_query!(conn) to send a CancelRequest to the server.

Development disclosure

The 1.0 release preparation used Claude Code and OpenAI Codex for implementation assistance and adversarial review. Maintainer decisions, source history, review discussion, and validation results are recorded in pull request #5.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from quinnj/Example.jl
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - JuliaDatabases/Postgres.jl · GitHub
Skip to content

Repository files navigation

Postgres.jl

CIdocscodecov

Postgres.jl is a PostgreSQL client written in Julia that implements the v3 wire protocol with DBInterface and Tables integration.

Installation

import Pkg
Pkg.add("Postgres")

Quick start

using Postgres
DBInterface.connect(Postgres.Connection, "host=127.0.0.1;port=5432;user=postgres;password=postgres;dbname=postgres") do conn
row =only(DBInterface.execute(conn, "SELECT 1 AS a"))
@show row.a
end

Connections

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "postgresql://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable")
DBInterface.close!(conn)

Connection options support:

  • libpq-style keyword strings such as host=127.0.0.1 port=5432 user=postgres dbname=postgres.
  • PostgreSQL URIs such as postgresql://postgres:postgres@127.0.0.1:5432/postgres.
  • Environment defaults: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGAPPNAME, PGCONNECT_TIMEOUT, and TLS-related PGSSL* variables.
  • sslmode values: disable, prefer (the default), require, verify-full. Only verify-full verifies the server's certificate; require encrypts without authenticating the server, and the default prefer falls back to an unencrypted connection if the server declines TLS. Use verify-full with sslrootcert when the connection needs to be authenticated.
  • TLS files: sslrootcert, sslcert, sslkey, and sslcapath (sslcapath is a fallback CA bundle or directory, used only when sslrootcert is unset and ignored otherwise). sslservername overrides the TLS server name when connecting to a pre-resolved address; under verify-full it is also the name the certificate is verified against, so it must name the server you intend to authenticate.
  • connect_timeout (seconds) and statement_timeout (milliseconds).
  • application_name and statement_cache_maxsize.

See the 1.0 support policy for tested Julia and PostgreSQL versions, TLS limits, and transaction-pooler requirements.

You can also use ConnectionParams:

using Postgres, DBInterface
params = Postgres.ConnectionParams(host="127.0.0.1", user="postgres", password="postgres", dbname="postgres", sslmode="disable")
conn = DBInterface.connect(Postgres.Connection, params)
DBInterface.close!(conn)

Queries and prepared statements

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
rows = Tables.rowtable(DBInterface.execute(conn, raw"SELECT $1::int AS val", (42,)))
@show rows[1].val
stmt = DBInterface.prepare(conn, raw"SELECT $1::int AS val")
rows = Tables.rowtable(DBInterface.execute(stmt, (7,)))
DBInterface.close!(stmt)
DBInterface.close!(conn)

Postgres.jl can also deserialize result rows directly into structs through StructUtils.jl. If column names match field names, pass the target type as the fourth DBInterface.execute argument.

using Postgres, DBInterface, StructUtils
struct CountRow
count::Intend
row = DBInterface.execute(conn, "SELECT count(*)::int AS count FROM users", (), CountRow)
@show row.count

Use StructUtils.@tags with the postgres namespace when table columns use a different naming convention than Julia fields.

using Dates, Postgres, DBInterface, StructUtils
StructUtils.@tagsstruct ProfileSummary
profileId::Int&(postgres=(name=:profile_id,),)
firstName::Union{Missing, String}&(postgres=(name=:first_name,),)
lastName::Union{Missing, String}&(postgres=(name=:last_name,),)
createdAt::DateTime&(postgres=(name=:created_at,),)
end
profile = DBInterface.execute(conn, raw""" SELECT profile_id, first_name, last_name, created_at FROM profiles WHERE profile_id = $1""", (profile_id,), ProfileSummary)
profiles = DBInterface.execute(conn, """ SELECT profile_id, first_name, last_name, created_at FROM profiles ORDER BY created_at DESC LIMIT 10""", (), Vector{ProfileSummary})

Postgres.command_tag(result) and Postgres.rows_affected(result) expose PostgreSQL command completion metadata.

Explicit named prepared statements use an LRU backend cache. Caller handles are independent. Set statement_cache_maxsize=0 to disable this cache.

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; statement_cache_maxsize=10)
Postgres.set_statement_cache_maxsize!(conn, 5)
cached = Postgres.get_cached_statements(conn)
Postgres.clear_statement_cache!(conn)
DBInterface.close!(conn)

Transactions

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.transaction(conn) do tx
DBInterface.execute(tx, "CREATE TEMP TABLE tx_demo (id int)")
DBInterface.execute(tx, "INSERT INTO tx_demo VALUES (1)")
end
Postgres.@transaction conn begin
DBInterface.execute(conn, "INSERT INTO tx_demo VALUES (2)")
end
DBInterface.close!(conn)

Nested transactions are implemented with savepoints.

COPY protocol

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TEMP TABLE copy_demo (id int, name text)")
Postgres.copy_from(conn, "COPY copy_demo (id, name) FROM STDIN", "1\talpha\n2\tbeta\n")
bytes = Postgres.copy_to(conn, "COPY copy_demo TO STDOUT (FORMAT BINARY)")
Postgres.copy_from(conn, "COPY copy_demo FROM STDIN (FORMAT BINARY)", bytes)
DBInterface.close!(conn)

LISTEN/NOTIFY

using Postgres, DBInterface
listener = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
notifier = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.listen!(listener, "events")
Postgres.notify!(notifier, "events", "hello")
notice = Postgres.wait_for_notification(listener; timeout=5.0)
@show notice.channel notice.payload
DBInterface.close!(notifier)
DBInterface.close!(listener)

Cursor streaming

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
cur = Postgres.cursor(conn, "SELECT generate_series(1, 5) AS n"; fetchsize=2)
for row in cur
@show row.n
end
DBInterface.close!(cur)
DBInterface.close!(conn)

Type registry

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')")
Postgres.register_enum!(conn, "mood")
row =only(Tables.rowtable(DBInterface.execute(conn, "SELECT 'happy'::mood AS mood")))
@show row.mood
DBInterface.close!(conn)

Numeric values are returned as Postgres.Numeric, interval values as Dates.Period or Dates.CompoundPeriod, and range types as Postgres.PostgresRange{T}. Custom enum, composite, and range registration controls result decoding. Those custom Julia values are not accepted as direct query parameters in 1.0; bind a PostgreSQL text representation with an explicit SQL cast instead.

Query logging and driver styles

Driver behavior — query logging, server notices, asynchronous notifications — is customized by defining a driver "style": subtype Postgres.AbstractPostgresStyle, overload the behavior hooks for it, and pass an instance via the style connection keyword.

using Postgres, DBInterface
struct LoggingStyle <:Postgres.AbstractPostgresStyleend
Postgres.query_logging_enabled(::LoggingStyle) =true
Postgres.query_logger(::LoggingStyle, event::Symbol, info::NamedTuple) =@info"query" event info.success info.duration_ns
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; style=LoggingStyle())
DBInterface.execute(conn, "SELECT 1")
DBInterface.close!(conn)

Connection pooling

using Postgres, DBInterface
pool = Postgres.ConnectionPool(Postgres.Connection, "127.0.0.1", "postgres", "postgres"; dbname="postgres", limit=5)
Postgres.with_connection(pool) do conn
DBInterface.execute(conn, "SELECT 1")
end
DBInterface.close!(pool)

Errors and cancellation

Postgres.Error represents server errors and includes SQLSTATE codes; Postgres.PostgresInterfaceError covers client-side failures. Use Postgres.cancel_query!(conn) to send a CancelRequest to the server.

Development disclosure

The 1.0 release preparation used Claude Code and OpenAI Codex for implementation assistance and adversarial review. Maintainer decisions, source history, review discussion, and validation results are recorded in pull request #5.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from quinnj/Example.jl
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - JuliaDatabases/Postgres.jl · GitHub
Skip to content

Repository files navigation

Postgres.jl

CIdocscodecov

Postgres.jl is a PostgreSQL client written in Julia that implements the v3 wire protocol with DBInterface and Tables integration.

Installation

import Pkg
Pkg.add("Postgres")

Quick start

using Postgres
DBInterface.connect(Postgres.Connection, "host=127.0.0.1;port=5432;user=postgres;password=postgres;dbname=postgres") do conn
row =only(DBInterface.execute(conn, "SELECT 1 AS a"))
@show row.a
end

Connections

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "postgresql://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable")
DBInterface.close!(conn)

Connection options support:

  • libpq-style keyword strings such as host=127.0.0.1 port=5432 user=postgres dbname=postgres.
  • PostgreSQL URIs such as postgresql://postgres:postgres@127.0.0.1:5432/postgres.
  • Environment defaults: PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, PGAPPNAME, PGCONNECT_TIMEOUT, and TLS-related PGSSL* variables.
  • sslmode values: disable, prefer (the default), require, verify-full. Only verify-full verifies the server's certificate; require encrypts without authenticating the server, and the default prefer falls back to an unencrypted connection if the server declines TLS. Use verify-full with sslrootcert when the connection needs to be authenticated.
  • TLS files: sslrootcert, sslcert, sslkey, and sslcapath (sslcapath is a fallback CA bundle or directory, used only when sslrootcert is unset and ignored otherwise). sslservername overrides the TLS server name when connecting to a pre-resolved address; under verify-full it is also the name the certificate is verified against, so it must name the server you intend to authenticate.
  • connect_timeout (seconds) and statement_timeout (milliseconds).
  • application_name and statement_cache_maxsize.

See the 1.0 support policy for tested Julia and PostgreSQL versions, TLS limits, and transaction-pooler requirements.

You can also use ConnectionParams:

using Postgres, DBInterface
params = Postgres.ConnectionParams(host="127.0.0.1", user="postgres", password="postgres", dbname="postgres", sslmode="disable")
conn = DBInterface.connect(Postgres.Connection, params)
DBInterface.close!(conn)

Queries and prepared statements

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
rows = Tables.rowtable(DBInterface.execute(conn, raw"SELECT $1::int AS val", (42,)))
@show rows[1].val
stmt = DBInterface.prepare(conn, raw"SELECT $1::int AS val")
rows = Tables.rowtable(DBInterface.execute(stmt, (7,)))
DBInterface.close!(stmt)
DBInterface.close!(conn)

Postgres.jl can also deserialize result rows directly into structs through StructUtils.jl. If column names match field names, pass the target type as the fourth DBInterface.execute argument.

using Postgres, DBInterface, StructUtils
struct CountRow
count::Intend
row = DBInterface.execute(conn, "SELECT count(*)::int AS count FROM users", (), CountRow)
@show row.count

Use StructUtils.@tags with the postgres namespace when table columns use a different naming convention than Julia fields.

using Dates, Postgres, DBInterface, StructUtils
StructUtils.@tagsstruct ProfileSummary
profileId::Int&(postgres=(name=:profile_id,),)
firstName::Union{Missing, String}&(postgres=(name=:first_name,),)
lastName::Union{Missing, String}&(postgres=(name=:last_name,),)
createdAt::DateTime&(postgres=(name=:created_at,),)
end
profile = DBInterface.execute(conn, raw""" SELECT profile_id, first_name, last_name, created_at FROM profiles WHERE profile_id = $1""", (profile_id,), ProfileSummary)
profiles = DBInterface.execute(conn, """ SELECT profile_id, first_name, last_name, created_at FROM profiles ORDER BY created_at DESC LIMIT 10""", (), Vector{ProfileSummary})

Postgres.command_tag(result) and Postgres.rows_affected(result) expose PostgreSQL command completion metadata.

Explicit named prepared statements use an LRU backend cache. Caller handles are independent. Set statement_cache_maxsize=0 to disable this cache.

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; statement_cache_maxsize=10)
Postgres.set_statement_cache_maxsize!(conn, 5)
cached = Postgres.get_cached_statements(conn)
Postgres.clear_statement_cache!(conn)
DBInterface.close!(conn)

Transactions

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.transaction(conn) do tx
DBInterface.execute(tx, "CREATE TEMP TABLE tx_demo (id int)")
DBInterface.execute(tx, "INSERT INTO tx_demo VALUES (1)")
end
Postgres.@transaction conn begin
DBInterface.execute(conn, "INSERT INTO tx_demo VALUES (2)")
end
DBInterface.close!(conn)

Nested transactions are implemented with savepoints.

COPY protocol

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TEMP TABLE copy_demo (id int, name text)")
Postgres.copy_from(conn, "COPY copy_demo (id, name) FROM STDIN", "1\talpha\n2\tbeta\n")
bytes = Postgres.copy_to(conn, "COPY copy_demo TO STDOUT (FORMAT BINARY)")
Postgres.copy_from(conn, "COPY copy_demo FROM STDIN (FORMAT BINARY)", bytes)
DBInterface.close!(conn)

LISTEN/NOTIFY

using Postgres, DBInterface
listener = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
notifier = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
Postgres.listen!(listener, "events")
Postgres.notify!(notifier, "events", "hello")
notice = Postgres.wait_for_notification(listener; timeout=5.0)
@show notice.channel notice.payload
DBInterface.close!(notifier)
DBInterface.close!(listener)

Cursor streaming

using Postgres, DBInterface
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
cur = Postgres.cursor(conn, "SELECT generate_series(1, 5) AS n"; fetchsize=2)
for row in cur
@show row.n
end
DBInterface.close!(cur)
DBInterface.close!(conn)

Type registry

using Postgres, DBInterface, Tables
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres")
DBInterface.execute(conn, "CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')")
Postgres.register_enum!(conn, "mood")
row =only(Tables.rowtable(DBInterface.execute(conn, "SELECT 'happy'::mood AS mood")))
@show row.mood
DBInterface.close!(conn)

Numeric values are returned as Postgres.Numeric, interval values as Dates.Period or Dates.CompoundPeriod, and range types as Postgres.PostgresRange{T}. Custom enum, composite, and range registration controls result decoding. Those custom Julia values are not accepted as direct query parameters in 1.0; bind a PostgreSQL text representation with an explicit SQL cast instead.

Query logging and driver styles

Driver behavior — query logging, server notices, asynchronous notifications — is customized by defining a driver "style": subtype Postgres.AbstractPostgresStyle, overload the behavior hooks for it, and pass an instance via the style connection keyword.

using Postgres, DBInterface
struct LoggingStyle <:Postgres.AbstractPostgresStyleend
Postgres.query_logging_enabled(::LoggingStyle) =true
Postgres.query_logger(::LoggingStyle, event::Symbol, info::NamedTuple) =@info"query" event info.success info.duration_ns
conn = DBInterface.connect(Postgres.Connection, "host=127.0.0.1;user=postgres;password=postgres;dbname=postgres"; style=LoggingStyle())
DBInterface.execute(conn, "SELECT 1")
DBInterface.close!(conn)

Connection pooling

using Postgres, DBInterface
pool = Postgres.ConnectionPool(Postgres.Connection, "127.0.0.1", "postgres", "postgres"; dbname="postgres", limit=5)
Postgres.with_connection(pool) do conn
DBInterface.execute(conn, "SELECT 1")
end
DBInterface.close!(pool)

Errors and cancellation

Postgres.Error represents server errors and includes SQLSTATE codes; Postgres.PostgresInterfaceError covers client-side failures. Use Postgres.cancel_query!(conn) to send a CancelRequest to the server.

Development disclosure

The 1.0 release preparation used Claude Code and OpenAI Codex for implementation assistance and adversarial review. Maintainer decisions, source history, review discussion, and validation results are recorded in pull request #5.

About

No description, website, or topics provided.

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

Generated from quinnj/Example.jl