File size: 3,942 Bytes
d2df13f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"""

Script de migración: reemplaza referencias con `Texture_wpc_deck` por `Texture_WPC_DECK`

Uso:

  - Configura `MONGODB_URI` como variable de entorno o edita la constante abajo.

  - Ejecuta: `python backend/scripts/migrate_textures_case.py`



Qué hace:

  - Actualiza campos `textura` y `url_preview` dentro de documentos en la colección `catalog`.

  - Busca y reemplaza tanto la ruta dentro de strings como partes de arrays/objetos anidados.

  - Muestra un resumen de documentos inspeccionados y modificados.

"""

import os
import re
import sys
import certifi
from pymongo import MongoClient

MONGODB_URI = os.getenv("MONGODB_URI", "mongodb://127.0.0.1:27017")
DB_NAME = os.getenv("MONGODB_DB", "hyper_reality")
COL_NAME = os.getenv("MONGODB_COLLECTION", "catalog")

# Allow passing the MongoDB URI as a first command-line argument for
# environments where setting environment variables is inconvenient.
if len(sys.argv) > 1 and sys.argv[1].strip():
    MONGODB_URI = sys.argv[1].strip()

OLD = "Texture_wpc_deck"
NEW = "Texture_WPC_DECK"

regex_old = re.compile(re.escape(OLD), flags=re.IGNORECASE)

# Use certifi bundle to verify Atlas TLS certificates on systems without
# a proper CA store configured (common in some Windows Python installs).
client = MongoClient(MONGODB_URI, tls=True, tlsCAFile=certifi.where())
db = client[DB_NAME]
col = db[COL_NAME]

def replace_in_value(val):
    if isinstance(val, str):
        if regex_old.search(val):
            return regex_old.sub(NEW, val)
        return val
    if isinstance(val, list):
        changed = False
        out = []
        for v in val:
            nv = replace_in_value(v)
            if nv != v:
                changed = True
            out.append(nv)
        return out if changed else val
    if isinstance(val, dict):
        changed = False
        out = {}
        for k, v in val.items():
            nv = replace_in_value(v)
            if nv != v:
                changed = True
            out[k] = nv
        return out if changed else val
    return val


def migrate_batch(batch_size=200):
    total = col.count_documents({})
    print(f"Documentos totales en {DB_NAME}.{COL_NAME}: {total}")
    cursor = col.find({})
    modified = 0
    inspected = 0
    for doc in cursor:
        inspected += 1
        doc_id = doc.get("_id")
        new_doc = False
        updates = {}
        # Revisa productos list si existe
        productos = doc.get("productos")
        if productos:
            new_productos = []
            changed_any = False
            for p in productos:
                new_p = dict(p)
                for field in ["textura", "url_preview"]:
                    if field in new_p and isinstance(new_p[field], str) and regex_old.search(new_p[field]):
                        new_p[field] = regex_old.sub(NEW, new_p[field])
                        changed_any = True
                new_productos.append(new_p)
            if changed_any:
                updates["productos"] = new_productos
                new_doc = True

        # Revisa cualquier otro campo a nivel superior (por si hay url_preview fuera de productos)
        for key, value in doc.items():
            if key in ["productos", "_id"]:
                continue
            new_val = replace_in_value(value)
            if new_val != value:
                updates[key] = new_val
                new_doc = True

        if new_doc and updates:
            res = col.update_one({"_id": doc_id}, {"$set": updates})
            if res.modified_count:
                modified += 1
                print(f"Modificado doc _id={doc_id}: campos actualizados: {list(updates.keys())}")

    print(f"Inspeccionados: {inspected}, Modificados: {modified}")


if __name__ == "__main__":
    print("Conectando a:", MONGODB_URI)
    migrate_batch()
    client.close()