Detail: userlinux db migration (python)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
userlinux.py - Helper script to migrate userlinux.net database to
a new django-driven application.
"""

import MySQLdb

conn = MySQLdb.connect (host="localhost", user="userlinux", passwd="userlinux",
                        db = "userlinux")

cursor = conn.cursor()


"""
blog_post (id, title, slug, text, tags(uno, dos, tres), hits,
creation_date(2011-04-19), user_id(1), status)
"""

cursor.execute("""SELECT p.id, pl.title, pl.slug, pl.content, p.hits,
p.date_created FROM posts p, posts_languages pl WHERE p.id=pl.post_id""")

for i in cursor.fetchall():
    # traducido, lo que hace esta linea:
    print "INSERT INTO blog_post VALUES (%s, '%s', '%s', '--', '%s', '%s')" \
          % (i[0], i[1], i[2], i[4], i[5])
    # es:
    #
    # "INSERT INTO blog_post VALUES (p.id, 'p.title', 'p.slug', '--', 'p.hits',
    # 'p.date_creadted')"
    # por que cada elemento i es una fila que devuelve la db y MySQLdb pone
    # cada campo del select en su posición dentro de la tupla que contiene
    # los datos de la fila. Esto es realmente FEO, el driver de postgresql
    # (pgsql) devuelve los datos en un diccionario, asi puedes hacer:
    # i['id'] o i['title'] en lugar de i[0] o i[1] (mucho mas legible)

    
    """
    Seleccionamos los tags, hay que agregarlos de la forma (tag1, tag2, tag3)
    como string al campo tags de blog_post
    """
    tags_cursor = conn.cursor() # no se si es necesario, pero por si las moscas ;P
    tags_cursor.execute ("""SELECT * FROM posts_tags, tags WHERE posts_tags.post_id='%s'
    AND posts_tags.tag_id=tags.id""" % i[0])
    for tag in tags_cursor.fetchall():
        print "UPDATE blog_post SET tags='' WHERE p.id=%s" % (i[0])
    tags_cursor.close()
    
cursor.close ()
conn.close ()

[raw] - Pasted by: Wu on python on May 3, 2011