File size: 9,763 Bytes
e3b3619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd0f3d7
e3b3619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b67799b
e3b3619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b67799b
e3b3619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
947dcfb
dd0f3d7
b67799b
e3b3619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecb2b8b
e3b3619
 
 
 
 
 
 
 
 
 
 
 
947dcfb
dd0f3d7
b67799b
e3b3619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import google.generativeai as genai
import gradio as gr
import yaml
from datetime import datetime
import uuid
import sys
import traceback

# Print version info for debugging
print(f"Python version: {sys.version}")
print(f"Gradio version: {gr.__version__}")

# Set up the model
generation_config = {
    "temperature": 0.2,
    "top_p": 1,
    "top_k": 32,
    "max_output_tokens": 8192,
}

safety_settings = [
    {
        "category": "HARM_CATEGORY_HARASSMENT",
        "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
    {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    }
]

# Note: Replace with your actual API key
genai.configure(api_key="AIzaSyBF8c8pxDa8Y6pUWcU-V9vvlFBDER4bY2E")
model = genai.GenerativeModel(
    model_name="gemini-2.0-flash",
    generation_config=generation_config,
    safety_settings=safety_settings
)

def generate_changeset_id():
    """Generate a unique changeset ID with timestamp"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"changeset_{timestamp}_{str(uuid.uuid4())[:8]}"

def generate_liquibase_changeset(user_prompt, existing_changelog, author_name, context_env):
    """Generate a new changeset based on user description"""
    
    changeset_id = generate_changeset_id()
    
    input_prompt = f"""
You are a Liquibase expert. Generate a new changeset in YAML format based on the user's description.

USER REQUEST: {user_prompt}

EXISTING CHANGELOG:
{existing_changelog if existing_changelog and existing_changelog.strip() else "No existing changelog provided."}

AUTHOR: {author_name}
CONTEXT: {context_env}

Please generate a complete Liquibase changeset that:
1. Has a unique changeset ID: {changeset_id}
2. Includes proper rollback statements
3. Uses appropriate data types for the database
4. Includes proper constraints and indexes where needed
5. Follows Liquibase best practices
6. Is properly formatted YAML

Respond with ONLY the changeset YAML (not the full databaseChangeLog wrapper), starting with:

- changeSet:
    id: {changeset_id}
    author: {author_name}
    context: {context_env}
    comment: [Generated comment describing the change]
    changes:
      [Your generated changes here]
    rollback:
      [Your rollback statements here]

Examples of common operations:
- Add column: Use addColumn with proper type and constraints
- Drop column: Use dropColumn with rollback addColumn
- Create table: Use createTable with all columns and constraints
- Add index: Use createIndex with rollback dropIndex
- Modify column: Use modifyDataType or addNotNullConstraint
- Add foreign key: Use addForeignKeyConstraint

Make sure the changeset is production-ready and includes appropriate error handling.
"""

    try:
        response = model.generate_content(input_prompt)
        return response.text
    except Exception as e:
        return f"Error generating changeset: {str(e)}"

def process_changeset_request(user_prompt, existing_changelog, author_name, context_env):
    """Main function to process user request and generate changeset"""
    
    try:
        if not user_prompt or not user_prompt.strip():
            return "Please provide a description of the database change you want to make."
        
        # Set defaults
        if not author_name or not author_name.strip():
            author_name = "harness"
        if not context_env or not context_env.strip():
            context_env = "dev"
        
        # Generate the changeset
        response = generate_liquibase_changeset(user_prompt, existing_changelog, author_name, context_env)
        
        return response
        
    except Exception as e:
        print(f"Error in process_changeset_request: {e}")
        traceback.print_exc()
        return f"Error processing request: {str(e)}"

# Alternative interface creation with explicit types
def create_interface_alternative():
    """Alternative interface creation method"""
    try:
        # Create inputs with explicit typing
        inputs = [
            gr.components.Textbox(
                placeholder="e.g., 'Add a column named email to the users table'",
                label="Describe Your Database Change",
                lines=3
            ),
            gr.components.Textbox(
                placeholder="Paste your current changelog.yml content here (optional)",
                label="Existing Changelog Content (Optional)",
                lines=5
            ),
            gr.components.Textbox(
                placeholder="your-username",
                label="Author Name",
                value="harness"
            ),
            gr.components.Textbox(
                placeholder="dev, test, prod",
                label="Context/Environment",
                value="dev"
            ),
        ]
        
        outputs = gr.components.Textbox(
            label="Generated Changeset",
            lines=20,
            show_copy_button=True
        )
        
        interface = gr.Interface(
            fn=process_changeset_request,
            inputs=inputs,
            outputs=outputs,
            title="🔄 Harness Database DevOps Changelog Generator",
            description="Describe your database change in plain English, and get a production-ready changelog",
            article="⚡ Powered by <div style='text-align: center; margin-top: 20px; padding: 10px; border-top: 1px solid #e0e0e0;'><a href='https://developer.harness.io/docs/category/get-started-with-database-devops' target='_blank' style='color: #0066cc; text-decoration: none; font-weight: 500;'>Harness Database DevOps</a></div>",
            examples=[
                [
                    "Add a column named 'email' of type VARCHAR(255) to the users table",
                    "",
                    "developer",
                    "dev"
                ],
                [
                    "Create a new table called 'orders' with id, user_id, product_id, and created_at columns",
                    "",
                    "developer",
                    "dev"
                ],
                [
                    "Create an index on the email column in the users table",
                    "",
                    "developer",
                    "dev"
                ],
            ],
            allow_flagging="never"
        )
        return interface
    except Exception as e:
        print(f"Error creating alternative interface: {e}")
        traceback.print_exc()
        return None

def create_interface():
    """Original interface creation method with error handling"""
    try:
        interface = gr.Interface(
            fn=process_changeset_request,
            inputs=[
                gr.Textbox(
                    placeholder="e.g., 'Add a column named email to the users table'",
                    label="Describe Your Database Change",
                    lines=3
                ),
                gr.Textbox(
                    placeholder="Paste your current changelog.yml content here (optional)",
                    label="Existing Changelog Content (Optional)",
                    lines=5
                ),
                gr.Textbox(
                    placeholder="your-username",
                    label="Author Name",
                    value="harness dbops"
                ),
                gr.Textbox(
                    placeholder="dev, test, prod",
                    label="Context/Environment",
                    value="dev"
                ),
            ],
            outputs=gr.Textbox(
                label="Generated Changeset",
                lines=20,
                show_copy_button=True
            ),
            title="🔄 Harness Database DevOps Changelog Generator",
            description="Describe your database change in plain English, and get a production-ready changelog",
            article="⚡ Powered by <div style='text-align: center; margin-top: 20px; padding: 10px; border-top: 1px solid #e0e0e0;'><a href='https://developer.harness.io/docs/category/get-started-with-database-devops' target='_blank' style='color: #0066cc; text-decoration: none; font-weight: 500;'>Harness Database DevOps</a></div>",
            examples=[
                [
                    "Add a column named 'email' of type VARCHAR(255) to the users table",
                    "",
                    "developer",
                    "dev"
                ],
                [
                    "Create a new table called 'orders' with id, user_id, product_id, and created_at columns",
                    "",
                    "developer",
                    "dev"
                ],
                [
                    "Create an index on the email column in the users table",
                    "",
                    "harness",
                    "dev"
                ],
            ],
            allow_flagging="never"
        )
        return interface
    except Exception as e:
        print(f"Error creating original interface: {e}")
        traceback.print_exc()
        return create_interface_alternative()

if __name__ == "__main__":
    try:
        demo = create_interface()
        if demo is not None:
            demo.launch(
                debug=True,
                share=True,
                server_name="0.0.0.0",
                server_port=7860
            )
        else:
            print("Failed to create interface")
    except Exception as e:
        print(f"Error launching application: {e}")
        traceback.print_exc()