summaryrefslogtreecommitdiff
path: root/ar/.local/bin/ddb
blob: e0384adb2f95968243d5d95d102667b692d424c1 (plain)
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#!/bin/sh
# Simple Docker Database Query Tool

set -e

# Check docker is available and accessible
if ! docker ps >/dev/null 2>&1; then
    echo "[ERROR] Cannot access Docker daemon" >&2
    echo "[WARNING] Make sure you are in the 'docker' group or run: newgrp docker" >&2
    exit 1
fi

# Detect database type from image name
detect_db_type() {
    case "$1" in
        *postgres*|*postgresql*) echo "postgres" ;;
        *mysql*|*mariadb*) echo "mysql" ;;
        *mongo*) echo "mongo" ;;
        *redis*) echo "redis" ;;
        *) echo "unknown" ;;
    esac
}

# Parse drizzle config to find migration output directory
find_migration_dir_from_config() {
    config_file="$1"

    # Try to find 'out' field in config file
    # Supports both single and double quotes: out: './drizzle', out: "./migrations"
    out_dir=$(grep "out:" "$config_file" | \
              sed -E "s/.*['\"]([^'\"]+)['\"].*/\1/" | \
              head -1)

    if [ -n "$out_dir" ]; then
        echo "$out_dir"
        return 0
    fi
    return 1
}

# Find drizzle migration files
find_drizzle_migrations() {
    # Try to find git root first
    git_root=$(git rev-parse --show-toplevel 2>/dev/null)

    if [ -n "$git_root" ]; then
        search_base="$git_root"
        echo "[INFO] Found git root: $git_root" >&2
    else
        search_base="."
        echo "[INFO] Not in git repo, using current directory" >&2
    fi

    # Try to find drizzle config file
    for config_name in drizzle.config.ts drizzle.config.js drizzle.config.mjs drizzle.config.json; do
        config_path="$search_base/$config_name"
        if [ -f "$config_path" ]; then
            echo "[INFO] Found config: $config_name" >&2
            migration_dir=$(find_migration_dir_from_config "$config_path")

            if [ -n "$migration_dir" ]; then
                # Remove leading ./ if present
                migration_dir=$(echo "$migration_dir" | sed 's|^\./||')
                full_path="$search_base/$migration_dir"

                echo "[INFO] Using migration directory from config: $migration_dir" >&2

                if [ -d "$full_path" ]; then
                    find "$full_path" -name "*.sql" -type f 2>/dev/null | sort -r
                    return 0
                else
                    echo "[WARNING] Config specifies '$migration_dir' but directory not found" >&2
                fi
            fi
        fi
    done

    echo "[INFO] No drizzle config found, searching default locations..." >&2

    # Fallback: Search for common drizzle migration folders
    for dir in drizzle migrations db/migrations src/db/migrations; do
        full_path="$search_base/$dir"
        if [ -d "$full_path" ]; then
            find "$full_path" -name "*.sql" -type f 2>/dev/null | sort -r
            return 0
        fi
    done
    return 1
}

# Parse command line arguments
MIGRATE_MODE=0
GENERATE_MODE=0

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    echo "Usage: $(basename "$0") [OPTIONS]"
    echo ""
    echo "Interactive script to query Docker database containers"
    echo ""
    echo "Options:"
    echo "  -h, --help              Show this help message"
    echo "  -g, --generate          Run drizzle-kit generate to create migration files"
    echo "  -m, --migrate           Run drizzle migration SQL file"
    echo "  -gm, --generate-migrate Run drizzle-kit generate then immediately migrate"
    echo ""
    echo "Supported databases:"
    echo "  - PostgreSQL"
    echo "  - MySQL/MariaDB"
    echo "  - MongoDB"
    echo "  - Redis"
    exit 0
elif [ "$1" = "-g" ] || [ "$1" = "--generate" ]; then
    GENERATE_MODE=1
elif [ "$1" = "-m" ] || [ "$1" = "--migrate" ]; then
    MIGRATE_MODE=1
elif [ "$1" = "-gm" ] || [ "$1" = "--generate-migrate" ]; then
    GENERATE_MODE=1
    MIGRATE_MODE=1
fi

# Handle generate step (runs before container selection)
if [ "$GENERATE_MODE" = 1 ]; then
    git_root=$(git rev-parse --show-toplevel 2>/dev/null)
    if [ -n "$git_root" ]; then
        project_dir="$git_root"
        echo "[INFO] Found git root: $git_root"
    else
        project_dir="$(pwd)"
        echo "[INFO] Using current directory: $project_dir"
    fi

    echo "[INFO] Running drizzle-kit generate..."
    echo ""

    if (cd "$project_dir" && npx drizzle-kit generate); then
        echo ""
        echo "[SUCCESS] Migration files generated successfully"
    else
        echo ""
        echo "[ERROR] drizzle-kit generate failed" >&2
        exit 1
    fi

    if [ "$MIGRATE_MODE" = 0 ]; then
        exit 0
    fi

    echo ""
fi

# Get database containers and save to temp file
TMP_FILE="/tmp/ddb_$$.tmp"
trap 'rm -f "$TMP_FILE"' EXIT

docker ps --format "{{.ID}}|{{.Names}}|{{.Image}}|{{.Status}}" | \
while IFS='|' read -r id name image status; do
    db_type=$(detect_db_type "$image")
    if [ "$db_type" != "unknown" ]; then
        echo "$id|$name|$image|$db_type|$status"
    fi
done > "$TMP_FILE"

# Check if any database containers found
if [ ! -s "$TMP_FILE" ]; then
    echo "[ERROR] No running database containers found" >&2
    exit 1
fi

# Display menu
echo ""
echo "=== Running Database Containers ==="
echo ""

i=1
while IFS='|' read -r id name image db_type status; do
    echo "  $i) $name [$db_type] - $id"
    i=$((i + 1))
done < "$TMP_FILE"

# Get selection
echo ""
total=$(wc -l < "$TMP_FILE")
if [ "$total" -eq 1 ]; then
    echo -n "Select container [1]: "
    read selection
    selection="${selection:-1}"
else
    echo -n "Select container (1-$total): "
    read selection
fi

# Validate selection
case "$selection" in
    ''|*[!0-9]*)
        echo "[ERROR] Invalid selection" >&2
        exit 1
        ;;
esac

if [ "$selection" -lt 1 ] || [ "$selection" -gt "$total" ]; then
    echo "[ERROR] Selection out of range" >&2
    exit 1
fi

# Get selected container info
container_info=$(sed -n "${selection}p" "$TMP_FILE")
container_id=$(echo "$container_info" | cut -d'|' -f1)
container_name=$(echo "$container_info" | cut -d'|' -f2)
db_type=$(echo "$container_info" | cut -d'|' -f4)

echo ""
echo "[INFO] Selected: $container_name ($db_type)"
echo ""

# Handle migrate mode or interactive query mode
if [ "$MIGRATE_MODE" = 1 ]; then
    # Migrate mode - find and select SQL file
    echo "[INFO] Searching for drizzle migration files..."
    echo ""

    SQL_FILES_TMP="/tmp/ddb_sql_files_$$.tmp"
    trap 'rm -f "$TMP_FILE" "$SQL_FILES_TMP"' EXIT

    if ! find_drizzle_migrations > "$SQL_FILES_TMP"; then
        echo "[ERROR] No drizzle migration folder found" >&2
        echo "[INFO] Searched in: drizzle/, migrations/, db/migrations/, src/db/migrations/" >&2
        exit 1
    fi

    if [ ! -s "$SQL_FILES_TMP" ]; then
        echo "[ERROR] No SQL files found in migration folders" >&2
        exit 1
    fi

    echo "=== Available Migration Files ==="
    echo ""

    i=1
    while IFS= read -r sql_file; do
        echo "  $i) $(basename "$sql_file")"
        i=$((i + 1))
    done < "$SQL_FILES_TMP"

    echo ""
    sql_total=$(wc -l < "$SQL_FILES_TMP")
    echo -n "Select SQL file(s) to execute (e.g. 3 or 3,5,7 or 3-7) [1-$sql_total]: "
    read sql_selection

    if [ -z "$sql_selection" ]; then
        echo "[ERROR] No selection provided" >&2
        exit 1
    fi

    # Parse selection into reverse-sorted list (highest number first = oldest file first)
    SELECTED_TMP="/tmp/ddb_selected_$$.tmp"
    trap 'rm -f "$TMP_FILE" "$SQL_FILES_TMP" "$SELECTED_TMP"' EXIT

    # Split by comma and expand ranges
    echo "$sql_selection" | tr ',' '\n' | while IFS= read -r part; do
        part=$(echo "$part" | tr -d ' ')
        case "$part" in
            *-*)
                range_start=$(echo "$part" | cut -d'-' -f1)
                range_end=$(echo "$part" | cut -d'-' -f2)
                # Validate range parts are numbers
                case "$range_start" in ''|*[!0-9]*) echo "[ERROR] Invalid range: $part" >&2; exit 1;; esac
                case "$range_end" in ''|*[!0-9]*) echo "[ERROR] Invalid range: $part" >&2; exit 1;; esac
                n=$range_start
                while [ "$n" -le "$range_end" ]; do
                    echo "$n"
                    n=$((n + 1))
                done
                ;;
            *)
                case "$part" in ''|*[!0-9]*) echo "[ERROR] Invalid selection: $part" >&2; exit 1;; esac
                echo "$part"
                ;;
        esac
    done | sort -rn -u > "$SELECTED_TMP"

    if [ ! -s "$SELECTED_TMP" ]; then
        echo "[ERROR] Invalid selection" >&2
        exit 1
    fi

    # Validate all selections are in range
    while IFS= read -r num; do
        if [ "$num" -lt 1 ] || [ "$num" -gt "$sql_total" ]; then
            echo "[ERROR] Selection $num out of range (1-$sql_total)" >&2
            exit 1
        fi
    done < "$SELECTED_TMP"

    selected_count=$(wc -l < "$SELECTED_TMP")

    # Show selected files (in execution order: ascending = oldest first)
    echo ""
    echo "=== Selected Migration Files (execution order) ==="
    echo ""
    while IFS= read -r num; do
        sql_file_path=$(sed -n "${num}p" "$SQL_FILES_TMP")
        echo "  $num) $(basename "$sql_file_path")"
    done < "$SELECTED_TMP"

    # Preview if single file
    if [ "$selected_count" -eq 1 ]; then
        sql_file_path=$(sed -n "$(cat "$SELECTED_TMP")p" "$SQL_FILES_TMP")
        echo ""
        echo "=== SQL Content Preview ==="
        head -20 "$sql_file_path"

        if [ "$(wc -l < "$sql_file_path")" -gt 20 ]; then
            echo "..."
            echo "(showing first 20 lines)"
        fi
    fi

    echo ""
    if [ "$selected_count" -gt 1 ]; then
        echo -n "Execute $selected_count migrations? (y/N): "
    else
        echo -n "Execute this migration? (y/N): "
    fi
    read confirm

    case "$confirm" in
        y|Y|yes|YES)
            # Build per-file SQL temps for sequential execution
            QUERY_TMP_DIR="/tmp/ddb_queries_$$"
            mkdir -p "$QUERY_TMP_DIR"
            trap 'rm -f "$TMP_FILE" "$SQL_FILES_TMP" "$SELECTED_TMP"; rm -rf "$QUERY_TMP_DIR"' EXIT

            migrate_seq=0
            while IFS= read -r num; do
                sql_file_path=$(sed -n "${num}p" "$SQL_FILES_TMP")
                migrate_seq=$((migrate_seq + 1))
                { printf 'BEGIN;\n'; cat "$sql_file_path"; printf '\nCOMMIT;\n'; } > "$QUERY_TMP_DIR/${migrate_seq}_$(basename "$sql_file_path")"
            done < "$SELECTED_TMP"

            query="__MIGRATE__"
            ;;
        *)
            echo "[INFO] Migration cancelled"
            exit 0
            ;;
    esac
else
    # Normal mode - ask for query or interactive shell
    echo -n "Enter query (or press Enter for interactive shell): "
    read query
fi

if [ -z "$query" ]; then
    # Interactive shell
    echo "[INFO] Starting interactive shell for $container_name ($db_type)..."
    echo ""

    case "$db_type" in
        postgres)
            db_name=$(docker exec "$container_id" sh -c 'echo $POSTGRES_DB' 2>/dev/null || echo "postgres")
            user=$(docker exec "$container_id" sh -c 'echo $POSTGRES_USER' 2>/dev/null || echo "postgres")
            docker exec -it "$container_id" psql -U "$user" -d "$db_name"
            ;;
        mysql)
            db_name=$(docker exec "$container_id" sh -c 'echo $MYSQL_DATABASE' 2>/dev/null || echo "")
            user=$(docker exec "$container_id" sh -c 'echo $MYSQL_USER' 2>/dev/null || echo "root")
            password=$(docker exec "$container_id" sh -c 'echo $MYSQL_ROOT_PASSWORD' 2>/dev/null || echo "")

            if [ -n "$password" ]; then
                docker exec -it "$container_id" mysql -u"$user" -p"$password" ${db_name:+-D "$db_name"}
            else
                docker exec -it "$container_id" mysql -u"$user" ${db_name:+-D "$db_name"}
            fi
            ;;
        mongo)
            db_name=$(docker exec "$container_id" sh -c 'echo $MONGO_INITDB_DATABASE' 2>/dev/null || echo "test")
            docker exec -it "$container_id" mongosh "$db_name"
            ;;
        redis)
            docker exec -it "$container_id" redis-cli
            ;;
        *)
            echo "[ERROR] Unsupported database type: $db_type" >&2
            exit 1
            ;;
    esac
else
    # Execute query
    echo "[INFO] Executing query on $container_name ($db_type)..."
    echo ""

    case "$db_type" in
        postgres)
            db_name=$(docker exec "$container_id" sh -c 'echo $POSTGRES_DB' 2>/dev/null || echo "postgres")
            user=$(docker exec "$container_id" sh -c 'echo $POSTGRES_USER' 2>/dev/null || echo "postgres")

            if [ "$MIGRATE_MODE" = 1 ]; then
                migrate_failed=0
                for qfile in $(ls "$QUERY_TMP_DIR"/*.sql | sort -n); do
                    fname=$(basename "$qfile" | sed 's/^[0-9]*_//')
                    echo "[INFO] Executing: $fname"
                    docker exec -i "$container_id" psql -v ON_ERROR_STOP=1 -U "$user" -d "$db_name" < "$qfile"
                    if [ $? -ne 0 ]; then
                        echo ""
                        echo "[ERROR] Migration failed: $fname" >&2
                        migrate_failed=1
                        break
                    fi
                    echo "[SUCCESS] Applied: $fname"
                    echo ""
                done
                if [ "$migrate_failed" -eq 1 ]; then
                    exit 1
                fi
                echo "[SUCCESS] All migrations executed successfully"
            else
                docker exec -it "$container_id" psql -U "$user" -d "$db_name" -c "$query"
                psql_exit=$?

                if [ "$psql_exit" -eq 0 ]; then
                    echo ""
                    echo "[SUCCESS] Query executed successfully"
                else
                    echo ""
                    echo "[ERROR] Query execution failed" >&2
                    exit 1
                fi
            fi
            ;;
        mysql)
            db_name=$(docker exec "$container_id" sh -c 'echo $MYSQL_DATABASE' 2>/dev/null || echo "")
            user=$(docker exec "$container_id" sh -c 'echo $MYSQL_USER' 2>/dev/null || echo "root")
            password=$(docker exec "$container_id" sh -c 'echo $MYSQL_ROOT_PASSWORD' 2>/dev/null || echo "")

            if [ "$MIGRATE_MODE" = 1 ]; then
                migrate_failed=0
                for qfile in $(ls "$QUERY_TMP_DIR"/*.sql | sort -n); do
                    fname=$(basename "$qfile" | sed 's/^[0-9]*_//')
                    echo "[INFO] Executing: $fname"
                    if [ -n "$password" ]; then
                        docker exec -i "$container_id" mysql -u"$user" -p"$password" ${db_name:+-D "$db_name"} < "$qfile"
                    else
                        docker exec -i "$container_id" mysql -u"$user" ${db_name:+-D "$db_name"} < "$qfile"
                    fi
                    if [ $? -ne 0 ]; then
                        echo ""
                        echo "[ERROR] Migration failed: $fname" >&2
                        migrate_failed=1
                        break
                    fi
                    echo "[SUCCESS] Applied: $fname"
                    echo ""
                done
                if [ "$migrate_failed" -eq 1 ]; then
                    exit 1
                fi
                echo "[SUCCESS] All migrations executed successfully"
            else
                if [ -n "$password" ]; then
                    docker exec -it "$container_id" mysql -u"$user" -p"$password" ${db_name:+-D "$db_name"} -e "$query"
                else
                    docker exec -it "$container_id" mysql -u"$user" ${db_name:+-D "$db_name"} -e "$query"
                fi

                if [ $? -eq 0 ]; then
                    echo ""
                    echo "[SUCCESS] Query executed successfully"
                else
                    echo ""
                    echo "[ERROR] Query execution failed" >&2
                    exit 1
                fi
            fi
            ;;
        mongo)
            db_name=$(docker exec "$container_id" sh -c 'echo $MONGO_INITDB_DATABASE' 2>/dev/null || echo "test")

            if [ "$MIGRATE_MODE" = 1 ]; then
                migrate_failed=0
                for qfile in $(ls "$QUERY_TMP_DIR"/*.sql | sort -n); do
                    fname=$(basename "$qfile" | sed 's/^[0-9]*_//')
                    echo "[INFO] Executing: $fname"
                    docker exec -i "$container_id" mongosh "$db_name" < "$qfile"
                    if [ $? -ne 0 ]; then
                        echo ""
                        echo "[ERROR] Migration failed: $fname" >&2
                        migrate_failed=1
                        break
                    fi
                    echo "[SUCCESS] Applied: $fname"
                    echo ""
                done
                if [ "$migrate_failed" -eq 1 ]; then
                    exit 1
                fi
                echo "[SUCCESS] All migrations executed successfully"
            else
                docker exec -it "$container_id" mongosh "$db_name" --eval "$query"

                if [ $? -eq 0 ]; then
                    echo ""
                    echo "[SUCCESS] Query executed successfully"
                else
                    echo ""
                    echo "[ERROR] Query execution failed" >&2
                    exit 1
                fi
            fi
            ;;
        redis)
            if docker exec -it "$container_id" redis-cli "$query"; then
                echo ""
                echo "[SUCCESS] Command executed successfully"
            else
                echo ""
                echo "[ERROR] Command execution failed" >&2
                exit 1
            fi
            ;;
        *)
            echo "[ERROR] Unsupported database type: $db_type" >&2
            exit 1
            ;;
    esac
fi