Skip to content

Instantly share code, notes, and snippets.

@bruno-
Last active March 12, 2020 11:22
Show Gist options
  • Save bruno-/089d37dc70dbc4c14a59 to your computer and use it in GitHub Desktop.
Save bruno-/089d37dc70dbc4c14a59 to your computer and use it in GitHub Desktop.
Demo of PostgreSQL FDW wrapping a CSV file + ActiveRecord
# This is a demo of creating a Postgres FDW (foreign database wrapper)
# that encapsulates a CSV file.
# A CSV file can be manually updated and the PG table data will update too.
# Required steps in PostgreSQL
#
# 1. create a new database
# CREATE DATABASE foobar;
#
# 2. add required extension
# CREATE EXTENSION file_fdw;
#
# 3. create server
# CREATE SERVER my_server FOREIGN DATA WRAPPER file_fdw;
#
# 4. creating table that wraps a CSV file
# CREATE FOREIGN TABLE books (
# id VARCHAR(255),
# cat VARCHAR(255),
# name VARCHAR(255),
# price DECIMAL(5, 2),
# inStock BOOLEAN,
# author VARCHAR(255),
# series VARCHAR(255),
# sequence INTEGER,
# genre VARCHAR(255)
# )
# SERVER my_server
# OPTIONS (
# format 'csv', header 'true', filename 'path_to_file.csv', delimiter ',', null ''
# );
require "active_record"
require "pg"
ActiveRecord::Base.establish_connection(
adapter: "postgresql",
database: "csv_file_fdw",
username: "<username>",
password: "<pass>",
host: "localhost",
port: "5432",
)
# this model "consumes" the above defined wrapper table
class Book < ActiveRecord::Base
end
@smknstd
Copy link

smknstd commented Mar 12, 2020

this postgres feature is amazing ! Thanx for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment