Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
I wrote this as prep for a talk about JSON datatype and PLV8: https://speakerdeck.com/selenamarie/schema-liberation-with-json-and-plv8-and-postgres
CREATE SCHEMA liberated;
CREATE OR REPLACE FUNCTION public.liberate()
RETURNS boolean
LANGUAGE plv8
AS $function$
var tables = plv8.execute(
"select relname FROM pg_catalog.pg_class"
+ " c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
+ " where relkind = 'r' and n.nspname = 'public'");
var tablesLength = tables.length;
for (var i = 0; i < tablesLength; i++) {
plv8.elog(NOTICE, tables[i]['relname']);
var code = "create table liberated."
+ tables[i]['relname']
+ " as ( select row_to_json("
+ tables[i]['relname']
+ ") as liberated_json "
+ "from select * from "
+ tables[i]['relname']
+ ")" ;
plv8.execute(code);
}
return 1;
$function$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment