Skip to content

Instantly share code, notes, and snippets.

@marcaddeo
Created January 23, 2012 23:37
Show Gist options
  • Save marcaddeo/1666424 to your computer and use it in GitHub Desktop.
Save marcaddeo/1666424 to your computer and use it in GitHub Desktop.
DB Migration tool to migrate from a JSON datastore to postgres
pg = require 'pg'
fs = require 'fs'
conString = "tcp://user:password@localhost/tv";
client = new pg.Client(conString);
client.connect();
mediaList = JSON.parse(fs.readFileSync('media-list/media.json'))
numbers =
one: 1
two: 2
three: 3
four: 4
five: 5
six: 6
seven: 7
eight: 8
nine: 9
ten: 10
addMovies = ->
mediaList.map (entry) ->
if !entry?.type?
path = if entry.path instanceof Array then entry.path else new Array entry.path
path = '{' + path.join(',') + '}'
notes = if entry?.notes instanceof Array then '{' + entry.notes.join(',') + '}' else null
duration = entry.duration.split('.')[0]
query = client.query
name: 'insert movie'
text: 'INSERT INTO videos(name, year, duration, path, notes) values($1, $2, $3, $4, $5)'
values: [
entry.name,
entry.year,
duration,
path,
notes
]
query.on 'error', (error) ->
console.log error
addSeries = ->
mediaList.map (entry) ->
if entry?.type?
query = client.query
name: 'insert series'
text: 'INSERT INTO series(name) values($1) RETURNING id'
values: [entry.name]
query.on 'error', (error) ->
console.log error
query.on 'row', (row) ->
series_id = row.id
entry.children.map (season) ->
sQuery = client.query
name: 'insert season'
text: 'INSERT INTO seasons(series, season) values($1, $2) RETURNING id'
values: [series_id, numbers[season.name.split(' ')[1].toLowerCase()]]
sQuery.on 'error', (error) ->
console.log error
sQuery.on 'row', (row) ->
season_id = row.id
season.children.map (episode) ->
duration = episode.duration.split('.')[0]
eNumber = Number(episode.name.split('x')[1])
path = if episode.path instanceof Array then episode.path else new Array episode.path
path = '{' + path.join(',') + '}'
eQuery = client.query
name: 'insert video'
text: 'INSERT INTO videos(year, duration, episode, season, path) values($1, $2, $3, $4, $5)'
values: [
episode.year,
duration,
eNumber,
season_id,
path
]
eQuery.on 'error', (error) ->
console.log error
addMovies()
addSeries()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment