@@ -19,19 +19,13 @@ type SqlVisitor() =
1919 let rec childrenToText ( x : Tree.IParseTree ) =
2020 seq {
2121 if x.ChildCount = 0 then
22+
2223 yield x.GetText()
2324 else
2425 for n in { 0 .. x.ChildCount - 1 } do
25- yield ! childrenToText ( x.GetChild( n ))
26+ yield ! n |> x.GetChild |> childrenToText
2627 }
2728
28- let selectDependencies ( context : SQLiteParser.Select_stmtContext ) =
29- context.select_ core ()
30- |> Seq.head
31- |> _. table_ or_ subquery()
32- |> Seq.map ( fun t -> t.table_ name() .GetText())
33- |> Seq.toList
34-
3529 override this.VisitSql_stmt_list ( context : SQLiteParser.Sql_stmt_listContext ) =
3630 context.sql_ stmt ()
3731 |> Array.choose ( this.Visit >> Option.ofObj)
@@ -131,18 +125,38 @@ type SqlVisitor() =
131125 constraints = constraints } //TODO parse table constraints
132126
133127
134- override this.VisitCreate_view_stmt ( context : SQLiteParser.Create_view_stmtContext ) =
128+ override _.VisitCreate_view_stmt ( context : SQLiteParser.Create_view_stmtContext ) =
129+ let selectDependencies ( context : SQLiteParser.Select_stmtContext ) =
130+ context.select_ core ()
131+ |> Seq.head
132+ |> _. table_ or_ subquery()
133+ |> Seq.map ( fun t -> t.table_ name() .GetText())
134+ |> Seq.toList
135+
136+ // FIXME it's possible the remaining UNION clauses are ignored because of a bug in the grammar
135137 let sql = context.children |> Seq.map childrenToText |> Seq.concat
136138
137139 let name = context.view_ name() .GetText() .Trim '"'
138140
139141 // FIXME assumes a query in the form `FROM table0, table1, …`
140142 let tables = context.select_ stmt () |> selectDependencies
141143
144+ let withTables , withDeps =
145+ match context.select_ stmt() .common_ table_ stmt () with
146+ | null -> [], []
147+ | ct ->
148+ ct.common_ table_ expression ()
149+ |> Array.map ( fun x -> x.table_ name() .GetText(), selectDependencies ( x.select_ stmt ()))
150+ |> Array.unzip
151+ |> fun ( xs , yss ) -> Array.toList xs, yss |> Array.toList |> List.concat
152+
153+ // FIXME for WITH statements inside WITH statements this trick might not work
154+ let topLevelTables = set tables + set withDeps - set withTables |> Set.toList
155+
142156 View
143157 { name = name
144158 sqlTokens = sql
145- dependencies = tables }
159+ dependencies = topLevelTables }
146160
147161 override this.VisitCreate_index_stmt ( context : SQLiteParser.Create_index_stmtContext ) =
148162 let name = context.index_ name() .GetText() .Trim '"'
@@ -197,6 +211,6 @@ let parse (_file: string, sql: string) =
197211 triggers = t :: acc.triggers }
198212 | StatList ys -> failwith $" unexpected statement list {ys}" )
199213 emptyFile
200- |> Ok
201- | Some expr -> Error $" expecting statement list, got {expr}"
202- | None -> Ok emptyFile
214+ |> Result. Ok
215+ | Some expr -> Result. Error $" expecting statement list, got {expr}"
216+ | None -> Result. Ok emptyFile
0 commit comments