Package: meltanolabs-tap-postgres
tap-postgresSinger tap for Postgres.Built with theMeltano Singer SDK.Capabilitiescatalogstatediscoveraboutstream-mapsschema-flatteningSettingsSettingRequiredDefaultDescriptionhostFalseNoneHostname for postgres instance. Note if sqlalchemy_url is set this will be ignored.portFalse5432The port on which postgres is awaiting connection. Note if sqlalchemy_url is set this will be ignored.userFalseNoneUser name used to authenticate. Note if sqlalchemy_url is set this will be ignored.passwordFalseNonePassword used to authenticate. Note if sqlalchemy_url is set this will be ignored.databaseFalseNoneDatabase name. Note if sqlalchemy_url is set this will be ignored.sqlalchemy_urlFalseNoneExample postgresql://[username]:[password]@localhost:5432/[db_name]filter_schemasFalseNoneIf an array of schema names is provided, the tap will only process the specified Postgres schemas and ignore others. If left blank, the tap automatically determines ALL available Postgres schemas.dates_as_stringFalse0Defaults to false, if true, date, and timestamp fields will be Strings. If you see ValueError: Year is out of range, try setting this to True.More Informationssh_tunnelFalseNoneSSH Tunnel Configuration, this is a json objectssh_tunnel.enableTrue (if ssh_tunnel set)FalseEnable an ssh tunnel (also known as bastion server), see the other ssh_tunnel.* properties for more details.ssh_tunnel.hostTrue (if ssh_tunnel set)FalseHost of the bastion server, this is the host we'll connect to via sshssh_tunnel.usernameTrue (if ssh_tunnel set)FalseUsername to connect to bastion serverssh_tunnel.portTrue (if ssh_tunnel set)22Port to connect to bastion serverssh_tunnel.private_keyTrue (if ssh_tunnel set)NonePrivate Key for authentication to the bastion serverssh_tunnel.private_key_passwordFalseNonePrivate Key Password, leave None if no password is setssl_enableFalse0Whether or not to use ssl to verify the server's identity. Use ssl_certificate_authority and ssl_mode for further customization. To use a client certificate to authenticate yourself to the server, use ssl_client_certificate_enable instead. Note if sqlalchemy_url is set this will be ignored.ssl_client_certificate_enableFalse0Whether or not to provide client-side certificates as a method of authentication to the server. Use ssl_client_certificate and ssl_client_private_key for further customization. To use SSL to verify the server's identity, use ssl_enable instead. Note if sqlalchemy_url is set this will be ignored.ssl_modeFalseverify-fullSSL Protection method, seepostgres documentationfor more information. Must be one of disable, allow, prefer, require, verify-ca, or verify-full. Note if sqlalchemy_url is set this will be ignored.ssl_certificate_authorityFalse~/.postgresql/root.crlThe certificate authority that should be used to verify the server's identity. Can be provided either as the certificate itself (in .env) or as a filepath to the certificate. Note if sqlalchemy_url is set this will be ignored.ssl_client_certificateFalse~/.postgresql/postgresql.crtThe certificate that should be used to verify your identity to the server. Can be provided either as the certificate itself (in .env) or as a filepath to the certificate. Note if sqlalchemy_url is set this will be ignored.ssl_client_private_keyFalse~/.postgresql/postgresql.keyThe private key for the certificate you provided. Can be provided either as the certificate itself (in .env) or as a filepath to the certificate. Note if sqlalchemy_url is set this will be ignored.ssl_storage_directoryFalse.secretsThe folder in which to store SSL certificates provided as raw values. When a certificate/key is provided as a raw value instead of as a filepath, it must be written to a file before it can be used. This configuration option determines where that file is created.stream_mapsFalseNoneConfig object for stream maps capability. For more information check outStream Maps.stream_map_configFalseNoneUser-defined config values to be used within map expressions.flattening_enabledFalseNone'True' to enable schema flattening and automatically expand nested properties.flattening_max_depthFalseNoneThe max depth to flatten schemas.batch_configFalseNoneJSON object containing information on data batching.batch_config.encoding.compressionFalseNoneCompression format to use for batch files.batch_config.encoding.formatFalseNoneFormat to use for batch files.batch_config.storage.prefixFalseNonePrefix to use when writing batch files.batch_config.storage.rootFalseNoneRoot path to use when writing batch files.A full list of supported settings and capabilities is available by running:tap-postgres --aboutConfigure using environment variablesThis Singer tap will automatically import any environment variables within the working directory's.envif the--config=ENVis provided, such that config values will be considered if a matching
environment variable is set either in the terminal context or in the.envfile.Installationpipxinstallmeltanolabs-tap-postgresUsageYou can easily runtap-postgresby itself or in a pipeline usingMeltano.Executing the Tap Directlytap-postgres--version
tap-postgres--help
tap-postgres--configCONFIG--discover>./catalog.jsonDeveloper ResourcesInitialize your Development Environmentpipxinstallpoetrypre-commit
poetryinstall
pre-commitinstallCreate and Run TestsCreate tests within thetap_postgres/testssubfolder and
then run:poetryrunpytestYou can also test thetap-postgresCLI interface directly usingpoetry run:poetryruntap-postgres--helpTesting withMeltanoNote:This tap will work in any Singer environment and does not require Meltano.
Examples here are for convenience and to streamline end-to-end orchestration scenarios.Your project comes with a custommeltano.ymlproject file already created.Next, install Meltano (if you haven't already) and any needed plugins:# Install meltanopipxinstallmeltano# Initialize meltano within this directorycdtap-postgres
meltanoinstallNow you can test and orchestrate using Meltano:# Test invocation:meltanoinvoketap-postgres--version# OR run a test `elt` pipeline:meltanoelttap-postgrestarget-jsonlSDK Dev GuideSee thedev guidefor more instructions on how to use the SDK to
develop your own taps and targets.SSH TunnelsThis tap supports connecting to a Postgres database via an SSH tunnel (also known as a bastion server). This is useful if you need to connect to a database that is not publicly accessible. This is the same as usingssh -L, but this is done inside the tap itself.What is an SSH Tunnel?An SSH tunnel is a method to securely forward network traffic. It uses the SSH protocol to encapsulate other protocols like HTTP, MySQL, Postgres, etc. This is particularly useful in scenarios where you need to access a service that is behind a firewall or in a network that you can't reach directly. In the context of this tap, you can use an SSH tunnel to access a Postgres database that's not accessible to the wider internet.Here's a basic illustration of how an SSH tunnel works:+-------------+             +-------------+             +-------------+
|    Local    | SSH tunnel  |   Bastion   |   Direct    |  Postgres   |
|   Machine   | <=========> |   Server    | <=========> |     DB      |
+-------------+ (encrypted) +-------------+ (unsecured) +-------------+Local Machine: This is wherever this tap is running from, where you initiate the SSH tunnel. It's also referred to as the SSH client.Bastion Server: This is a secure server that you have SSH access to, and that can connect to the remote server. All traffic in the SSH tunnel between your local machine and the bastion server is encrypted.Remote Server: This is the server you want to connect to, in this case a PostgreSQL server. The connection between the bastion server and the remote server is a normal, potentially unsecured connection. However, because the bastion server is trusted, and because all traffic between your local machine and the bastion server is encrypted, you can safely transmit data to and from the remote server.Obtaining KeysSetupEnsure your bastion server is online.Ensure you bastion server can access your Postgres database.Have some method of accessing your bastion server. This could either be through password-based SSH authentication or through a hardwired connection to the server.Installssh-keygenon your client machine if it is not already installed.Creating KeysRun the commandssh-keygen.Enter the directory where you would like to save your key. If you're in doubt, the default directory is probably fine.If you get a message similar to the one below asking if you wish to overwrite a previous key, entern, then rerunssh-keygenand manually specify the output_keyfile using the-fflag./root/.ssh/id_rsa already exists.
Overwrite (y/n)?If you wish, enter a passphrase to provide additional protection to your private key. SSH-based authentication is generally considered secure even without a passphrase, but a passphrase can provide an additional layer of security.You should now be presented with a message similar to the following, as well as a key fingerprint and ascii randomart image.Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pubNavigate to the indicated directory and find the two keys that were just generated. The file namedid_rsais your private key. Keep it safe. The file namedid_rsa.pubis your public key, and needs to be transferred to your bastion server for your private key to be used.Copying KeysNow that you have a pair of keys, the public key needs to be transferred to your bastion server.If you already have password-based SSH authentication configured, you can use the commandssh-copy-id [user]@[host]to copy your public key to the bastion server. Then you can move on tousing your keysIf not, you'll need some other way to access your bastion server. Once you've accessed it, copy theid_rsa.pubfile onto the bastion server in the~/.ssh/authorized_keysfile. You could do this using a tool such asrsyncor with a cloud-based service.Keep in mind: it's okay if your public key is exposed to the internet through a file-share or something similar. It is useless without your private key.Using Your KeysTo connect through SSH, you will need to determine the following pieces of information. If you're missing something, go back tothe section on Obtaining Keysto gather all the relevant information.The connection details for your Postgres database, the same as any other tap-postgres run. This includes host, port, username, password and database.Alternatively, provide an sqlalchemy url. Keep in mind that many other configuration options are ignored when an sqlalchemy url is set, and ideally you should be able to accomplish everything through other configuration options. Consider making an issue in thetap-postrges repositoryif you find a reasonable use-case that is unsupported by current configuration options.Note that when your connection details are used, it will be from the perspective of the bastion server. This could change the meaning of local IP address or keywords such as "localhost".The hostname or ip address of the bastion server, provided in thessh.hostconfiguration option.The port for use with the bastion server, provided in thessh.portconfiguration option.The username for authentication with the bastion server, provided in thessh.usernameconfiguration option. This will require you to have setup an SSH login with the bastion server.The private key you use for authentication with the bastion server, provided in thessh.private_keyconfiguration option. If your private key is protected by a password (alternatively called a "private key passphrase"), provide it in thessh.private_key_passwordconfiguration option. If your private key doesn't have a password, you can safely leave this field blank.After everything has been configured, be sure to indicate your use of an ssh tunnel to the tap by configuring thessh.enableconfiguration option to beTrue. Then, you should be able to connect to your privately accessible Postgres database through the bastion server.Log-Based ReplicationLog-based replication is an alternative to full-table and incremental syncs and syncs all changes tot he database, including deletes. This feature is built based onpostgres replication slots.Negatives of Log Based ReplicationManaging replication slots - Log-based replication has to be set up and maintained on the database. This tap attempts to abstract away as much complexity as possible, but there's still potentially manual effort neededLog Files - When a replication slot is setup the file that holds these logs will continue to grow until consumed, this can cause issues if the tap doesn't ingest these quickly enough due to outages, etc.If and when someone finds more please add them to this list!Implementation DetailsLog-based replication will modify the schemas output by the tap. Specifically, all fields will be made nullable and non-required. The reason for this is that when the tap sends a message indicating that a record has been deleted, that message will leave all fields for that record (except primary keys) as null. The stream's schema must be capable of accomodating these messages, even if a source field in the database is not nullable. As a result, log-based schemas will have all fields nullable.Note that changing what streams are selected after already beginning log-based replication can have unexpected consequences. To ensure consistent output, it is best to keep selected streams the same across invocations of the tap.Note also that using log-based replication will cause the replication key for all streams to be set to "_sdc_lsn", which is the Postgres LSN for the record in question.How to Set Up Log-Based ReplicationEnsure you are using  PostgresSQL 9.4 or higher.Need to access the master postgres instanceInstall the wal2json plugin for your database. Example instructions are given below for a Postgres 15.0 database running on Ubuntu 22.04. For more information, or for alternative versions/operating systems, refer to thewal2json documentationUpdate and upgrade apt if necessary.sudoaptupdate
sudoaptupgrade-yPrepare by making prerequisite installations.sudoaptinstallcurlca-certificates
sudoinstall-d/usr/share/postgresql-common/pgdgImport the repository keys for the Postgres Apt repositorysudocurl-o/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc--failhttps://www.postgresql.org/media/keys/ACCC4CF8.ascCreate the pgdg.list file.sudosh-c'echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt bookworm-pgdg main" > /etc/apt/sources.list.d/pgdg.list'Use the Postgres Apt repository to install wal2jsonsudoaptupdate
sudoapt-getinstallpostgresql-server-dev-15exportPATH=/usr/lib/postgresql/15/bin:$PATHsudoapt-getinstallpostgresql-15-wal2jsonConfigure your database with wal2json enabled.Edit yourpostgresql.confconfiguration file so the following parameters are appropriately set.wal_level = logical
max_replication_slots = 10
max_wal_senders = 10Restart PostgresSQLCreate a replication slot for tap-postgres.SELECT*FROMpg_create_logical_replication_slot('tappostgres','wal2json');Ensure your configuration for tap-postgres specifies host, port, user, password, and database manually, without relying on an sqlalchemy url.Use the following metadata modification in yourmeltano.ymlfor the streams you wish to have as log-based. Note that during log-based replication, we do not support any replication key other than_sdc_lsn.metadata:
"*":
  replication_method: LOG_BASED
  replication_key: _sdc_lsn