Skip to content

pg: read the default user from the environment on first access, not at module load - #3864

Open
proggeramlug wants to merge 1 commit into
brianc:masterfrom
proggeramlug:lazy-default-user
Open

proggeramlug wants to merge 1 commit into
brianc:masterfrom
proggeramlug:lazy-default-user

Conversation

@proggeramlug

Copy link
Copy Markdown

Motivation

lib/defaults.js copies process.env.USER (USERNAME on Windows) into the exported defaults object while the module loads. Requiring pg therefore reads the environment even when no connection is ever made, and the value is fixed at require time. Some tools prefer libraries that do no environment reads at module load (bundlers that evaluate module bodies ahead of time, startup snapshots, sandboxed runtimes that gate environment access).

Change

user on the defaults object becomes a getter/setter pair in the same position of the object literal. The first read runs the same expression as before (inside the same try/catch) and then replaces itself with a plain data property { writable: true, enumerable: true, configurable: true } holding that value; an assignment replaces it with a data property holding the assigned value. So:

  • defaults.user, pg.defaults.user and ConnectionParameters (user, and database defaulting to user) see the same values as before.
  • defaults.user = 'x' and delete defaults.user behave as before.
  • Object.keys(defaults) order, { ...defaults } and JSON.stringify(defaults) are unchanged.
  • After the first read or write, the property descriptor is identical to today's.

The only difference: the environment is read when user is first needed rather than when pg is required. A program that changes process.env.USER after requiring pg and before any connection now gets the changed value. Before the first access, Object.getOwnPropertyDescriptor(defaults, 'user') reports an accessor.

Tests

Adds packages/pg/test/unit/defaults-tests.js: loading lib/defaults.js with a recording process.env reads nothing until defaults.user is accessed; the value and descriptor after first access; key order; assignment and delete before the first read; an unreadable environment yields undefined. The first test fails on the old code and passes with the change. The existing unit tests pass (connection/error-tests.js fails locally on a busy port, with or without this change).

…dule load

defaults.user becomes a lazy accessor that turns into a plain data property on first read or write, so requiring pg no longer reads process.env.USER.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant