pgcrab 0.1.0

Linting and documentation generation tool for Postgres database schemas
Documentation
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
// SPDX-FileCopyrightText: 2025 Olivier 'reivilibre'
//
// SPDX-License-Identifier: GPL-3.0-or-later

//! Module to gather comments alongside tables and columns from SQL migration
//! files.
//!
//! # LLMs
//!
//! A substantial portion of this was generated with LLM.
//! It's considered 'good enough' but is not very robust,
//! given regular expressions are used for parsing.

use std::{
    collections::{btree_map, BTreeMap},
    path::PathBuf,
    sync::Arc,
};

use eyre::Context;
use maplit::btreemap;
use regex::Regex;
use serde::Serialize;
use walkdir::WalkDir;

#[derive(Debug, Clone, Serialize)]
pub struct DocComment {
    pub comment: String,
    pub line_number: usize,
}

#[derive(Debug, Serialize)]
pub struct TableInfo {
    #[serde(skip)]
    pub file_path: Arc<String>,
    pub name: String,
    pub doc_comment: Option<DocComment>,
    pub columns: BTreeMap<String, ColumnInfo>,
}

#[derive(Debug, Serialize)]
pub struct ColumnInfo {
    #[serde(skip)]
    pub file_path: Arc<String>,
    pub name: String,
    pub doc_comment: Option<DocComment>,
    pub table_name: String,
}

#[derive(Debug, Serialize)]
pub struct HarvestedFile {
    #[serde(skip)]
    pub file_path: Arc<String>,
    pub tables: Vec<TableInfo>,
    pub alter_columns: Vec<ColumnInfo>,
}

#[derive(Debug, Serialize)]
pub struct TotalHarvest {
    pub tables: BTreeMap<String, TableInfo>,
}

pub fn harvest_from_paths(paths: &Vec<PathBuf>) -> eyre::Result<TotalHarvest> {
    fn harvest(paths: &Vec<PathBuf>) -> eyre::Result<BTreeMap<Arc<String>, HarvestedFile>> {
        let mut out = BTreeMap::new();
        for path in paths {
            for entry in WalkDir::new(&path) {
                let entry = entry.with_context(|| format!("failed to walk {path:?}"))?;
                let Some(path_str) = entry.path().to_str() else {
                    continue;
                };
                if !(path_str.ends_with(".sql")
                    || path_str.ends_with(".sql.postgres")
                    || path_str.ends_with(".sql.postgresql"))
                {
                    continue;
                }

                let content = std::fs::read_to_string(entry.path())
                    .with_context(|| format!("could not read {path_str}"))?;
                let path_str = Arc::new(path_str.to_owned());
                out.insert(path_str.clone(), harvest_sql_file(&content, path_str));
            }
        }
        Ok(out)
    }

    let all = harvest(paths)?;

    let mut combined = TotalHarvest {
        tables: BTreeMap::new(),
    };

    // We rely on BTreeMap ordering here to make it so that
    // lexicographically-later migrations override earlier
    // ones.
    for (filename, file) in all {
        for table in file.tables {
            combined.tables.insert(table.name.clone(), table);
        }

        for column in file.alter_columns {
            match combined.tables.entry(column.table_name.clone()) {
                btree_map::Entry::Vacant(ve) => {
                    ve.insert(TableInfo {
                        file_path: filename.clone(),
                        name: column.table_name.clone(),
                        doc_comment: None,
                        columns: btreemap![column.name.clone() => column],
                    });
                }
                btree_map::Entry::Occupied(mut oe) => {
                    oe.get_mut().columns.insert(column.name.to_owned(), column);
                }
            }
        }
    }

    Ok(combined)
}

// fn main() -> Result<(), Box<dyn std::error::Error>> {
//     let directory = std::env::args().nth(1).unwrap_or_else(|| ".".to_string());

//     let results = parse_sql_directory(&directory)?;

//     for result in results {
//         println!("File: {}", result.file_path);
//         println!("===========================================");

//         for table in result.tables {
//             if let Some(doc) = &table.doc_comment {
//                 println!(
//                     "Table '{}' (line {}): {}",
//                     table.name, doc.line_number, doc.comment
//                 );
//             } else {
//                 println!("Table '{}': No documentation", table.name);
//             }

//             for column in table.columns {
//                 if let Some(doc) = &column.doc_comment {
//                     println!(
//                         "  Column '{}' (line {}): {}",
//                         column.name, doc.line_number, doc.comment
//                     );
//                 } else {
//                     println!("  Column '{}': No documentation", column.name);
//                 }
//             }
//             println!();
//         }

//         if !result.alter_columns.is_empty() {
//             println!("ALTER TABLE ADD COLUMN statements:");
//             for column in result.alter_columns {
//                 if let Some(doc) = &column.doc_comment {
//                     println!(
//                         "  Column '{}' in table '{}' (line {}): {}",
//                         column.name, column.table_name, doc.line_number, doc.comment
//                     );
//                 } else {
//                     println!(
//                         "  Column '{}' in table '{}': No documentation",
//                         column.name, column.table_name
//                     );
//                 }
//             }
//             println!();
//         }

//         println!();
//     }

//     Ok(())
// }

// fn parse_sql_directory(dir_path: &str) -> Result<Vec<ParseResult>, Box<dyn std::error::Error>> {
//     let mut results = Vec::new();

//     for entry in fs::read_dir(dir_path)? {
//         let entry = entry?;
//         let path = entry.path();

//         if path.is_file() && path.extension().map_or(false, |ext| ext == "sql") {
//             let content = fs::read_to_string(&path)?;
//             let file_path = path.to_string_lossy().to_string();

//             let result = parse_sql_file(&content, &file_path);
//             results.push(result);
//         }
//     }

//     Ok(results)
// }

/// Harvests commentable items from a SQL migration file.
///
/// Handles DDL statements `CREATE TABLE` and `ALTER TABLE ... ADD COLUMN`.
///
/// The parser is not robust at all, so only common formattings of code will work.
/// Should probably use `sqlparser`.
pub fn harvest_sql_file(content: &str, file_path: Arc<String>) -> HarvestedFile {
    let lines: Vec<&str> = content.lines().collect();
    let mut tables = Vec::new();
    let mut alter_columns = Vec::new();

    // Regex patterns
    let doc_comment_re = Regex::new(r"^\s*--\s*(.*)$").unwrap();
    let create_table_re = Regex::new(r"(?i)^\s*CREATE\s+TABLE\s+(\w+)").unwrap();
    let alter_table_re = Regex::new(r"(?i)^\s*ALTER\s+TABLE\s+(\w+)").unwrap();
    let add_column_re = Regex::new(r"(?i)^\s*ADD\s+COLUMN\s+(\w+)").unwrap();
    let column_re = Regex::new(r"^\s*(\w+)\s+").unwrap();

    let mut i = 0;
    while i < lines.len() {
        let line = lines[i];

        // Check for CREATE TABLE
        if let Some(captures) = create_table_re.captures(line) {
            let table_name = captures.get(1).unwrap().as_str().to_string();

            // Look for doc comment before CREATE TABLE
            let table_doc = find_preceding_doc_comment(&lines, i, &doc_comment_re);

            // Parse columns within the CREATE TABLE
            let (columns, end_idx) = parse_create_table_columns(
                &lines,
                i + 1,
                &doc_comment_re,
                &column_re,
                &table_name,
                file_path.clone(),
            );

            tables.push(TableInfo {
                file_path: file_path.clone(),
                name: table_name,
                doc_comment: table_doc,
                columns,
            });

            i = end_idx;
        }
        // Check for single-line ALTER TABLE ADD COLUMN first
        else if line.to_uppercase().contains("ALTER TABLE")
            && line.to_uppercase().contains("ADD COLUMN")
        {
            // Use a more comprehensive regex for single-line format
            let single_line_alter_re =
                Regex::new(r"(?i)^\s*ALTER\s+TABLE\s+(\w+)\s+ADD\s+COLUMN\s+(\w+)").unwrap();
            if let Some(captures) = single_line_alter_re.captures(line) {
                let table_name = captures.get(1).unwrap().as_str().to_string();
                let column_name = captures.get(2).unwrap().as_str().to_string();

                // Look for doc comment before this ALTER TABLE line
                let column_doc = find_preceding_doc_comment(&lines, i, &doc_comment_re);

                alter_columns.push(ColumnInfo {
                    file_path: file_path.clone(),
                    name: column_name,
                    doc_comment: column_doc,
                    table_name,
                });
            }
            i += 1;
        }
        // Check for multi-line ALTER TABLE format
        else if let Some(captures) = alter_table_re.captures(line) {
            let table_name = captures.get(1).unwrap().as_str().to_string();

            // Look for ADD COLUMN in subsequent lines
            let mut j = i + 1;
            while j < lines.len() {
                let next_line = lines[j];

                if let Some(add_captures) = add_column_re.captures(next_line) {
                    let column_name = add_captures.get(1).unwrap().as_str().to_string();

                    // Look for doc comment before ADD COLUMN line
                    let column_doc = find_preceding_doc_comment(&lines, j, &doc_comment_re);

                    alter_columns.push(ColumnInfo {
                        file_path: file_path.clone(),
                        name: column_name,
                        doc_comment: column_doc,
                        table_name: table_name.clone(),
                    });

                    i = j;
                    break;
                }

                // Skip empty lines and comments, but stop at non-empty SQL lines
                let trimmed = next_line.trim();
                if !trimmed.is_empty() && !doc_comment_re.is_match(trimmed) {
                    break;
                }

                j += 1;
            }

            i += 1;
        } else {
            i += 1;
        }
    }

    HarvestedFile {
        file_path: file_path.clone(),
        tables,
        alter_columns,
    }
}

fn find_preceding_doc_comment(
    lines: &[&str],
    current_idx: usize,
    doc_comment_re: &Regex,
) -> Option<DocComment> {
    if current_idx == 0 {
        return None;
    }

    let mut comment_lines = Vec::new();
    let mut first_comment_line = None;

    // Look backwards for consecutive doc comments (skip empty lines)
    for i in (0..current_idx).rev() {
        let line = lines[i].trim();

        if line.is_empty() {
            continue;
        }

        if let Some(captures) = doc_comment_re.captures(line) {
            let comment_text = captures.get(1).unwrap().as_str().trim().to_string();
            comment_lines.push(comment_text);
            first_comment_line = Some(i + 1); // Store line number (1-indexed)
        } else {
            // If we hit a non-empty, non-doc-comment line, stop looking
            break;
        }
    }

    if comment_lines.is_empty() {
        return None;
    }

    // Reverse the comment lines since we collected them backwards
    comment_lines.reverse();

    // Join multiple comment lines with newlines
    let combined_comment = comment_lines.join("\n");

    Some(DocComment {
        comment: combined_comment,
        line_number: first_comment_line.unwrap(),
    })
}

fn parse_create_table_columns(
    lines: &[&str],
    start_idx: usize,
    doc_comment_re: &Regex,
    column_re: &Regex,
    table_name: &str,
    file_path: Arc<String>,
) -> (BTreeMap<String, ColumnInfo>, usize) {
    let mut columns = BTreeMap::new();
    let mut i = start_idx;

    while i < lines.len() {
        let line = lines[i].trim();

        // End of CREATE TABLE statement
        if line.ends_with(");") {
            break;
        }

        // Skip empty lines and lines that start with constraints
        if line.is_empty()
            || line.to_uppercase().starts_with("PRIMARY KEY")
            || line.to_uppercase().starts_with("FOREIGN KEY")
            || line.to_uppercase().starts_with("UNIQUE")
            || line.to_uppercase().starts_with("CHECK")
            || line.to_uppercase().starts_with("CONSTRAINT")
        {
            i += 1;
            continue;
        }

        // Check if this looks like a column definition
        if let Some(captures) = column_re.captures(line) {
            let column_name = captures.get(1).unwrap().as_str().to_string();

            // Look for doc comment before this column
            let column_doc = find_preceding_doc_comment(lines, i, doc_comment_re);

            columns.insert(
                column_name.clone(),
                ColumnInfo {
                    file_path: file_path.clone(),
                    name: column_name,
                    doc_comment: column_doc,
                    table_name: table_name.to_string(),
                },
            );
        }

        i += 1;
    }

    (columns, i)
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use insta::assert_yaml_snapshot;

    use super::HarvestedFile;

    fn harvest_sql(sql: &str) -> HarvestedFile {
        super::harvest_sql_file(sql, Arc::new("test.sql".to_owned()))
    }

    #[test]
    fn test_harvest() {
        let h = harvest_sql(
            r#"
-- Stores users
-- Does not include magic users.
CREATE TABLE users (
    -- ID from the auth system
    sub_id UUID NOT NULL,

    -- Hash of user's password,
    -- or null if no password is set.
    -- We use Argon2 in the PHC format
    password_hash TEXT
);

ALTER TABLE users
    -- whether the user is barred from logging in
    ADD COLUMN locked BOOLEAN DEFAULT FALSE;

-- whether the user is all powerful
-- and able to do anything they want
ALTER TABLE users ADD COLUMN admin BOOLEAN DEFAULT FALSE;
        "#,
        );

        assert_yaml_snapshot!(h, @r#"
        tables:
          - name: users
            doc_comment:
              comment: "Stores users\nDoes not include magic users."
              line_number: 2
            columns:
              password_hash:
                name: password_hash
                doc_comment:
                  comment: "Hash of user's password,\nor null if no password is set.\nWe use Argon2 in the PHC format"
                  line_number: 8
                table_name: users
              sub_id:
                name: sub_id
                doc_comment:
                  comment: ID from the auth system
                  line_number: 5
                table_name: users
        alter_columns:
          - name: locked
            doc_comment:
              comment: whether the user is barred from logging in
              line_number: 15
            table_name: users
          - name: admin
            doc_comment:
              comment: "whether the user is all powerful\nand able to do anything they want"
              line_number: 18
            table_name: users
        "#);
    }
}