sqlingo 0.12.2 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/chunk-2IDNLTQG.cjs +2 -0
  3. package/dist/{chunk-IU7ARLOI.cjs.map → chunk-2IDNLTQG.cjs.map} +1 -1
  4. package/dist/{chunk-V5MU576A.js → chunk-4UJWN7AG.js} +2 -2
  5. package/dist/chunk-5YRYCTSB.cjs +2 -0
  6. package/dist/{chunk-EZ3T7JOU.cjs.map → chunk-5YRYCTSB.cjs.map} +1 -1
  7. package/dist/chunk-7SURY7NK.cjs +2 -0
  8. package/dist/{chunk-BLIL2VJH.cjs.map → chunk-7SURY7NK.cjs.map} +1 -1
  9. package/dist/chunk-ABH3VZG7.cjs +2 -0
  10. package/dist/chunk-ABH3VZG7.cjs.map +1 -0
  11. package/dist/chunk-AOD6F6HV.cjs +2 -0
  12. package/dist/{chunk-E4JORBQC.cjs.map → chunk-AOD6F6HV.cjs.map} +1 -1
  13. package/dist/chunk-ARZB6LLO.cjs +4 -0
  14. package/dist/{chunk-EORCZG7N.cjs.map → chunk-ARZB6LLO.cjs.map} +1 -1
  15. package/dist/{chunk-VRCV3F7C.js → chunk-AZNXXBMF.js} +2 -2
  16. package/dist/chunk-C72OQ3YO.cjs +19 -0
  17. package/dist/chunk-C72OQ3YO.cjs.map +1 -0
  18. package/dist/{chunk-EHG67C2E.js → chunk-CELHDVUC.js} +2 -2
  19. package/dist/chunk-D62XDRDA.cjs +3 -0
  20. package/dist/{chunk-B7N6EHLE.cjs.map → chunk-D62XDRDA.cjs.map} +1 -1
  21. package/dist/chunk-F4H5GNAS.cjs +2 -0
  22. package/dist/{chunk-5KXX2V4Z.cjs.map → chunk-F4H5GNAS.cjs.map} +1 -1
  23. package/dist/{chunk-C7U65H24.js → chunk-FHZLNMGS.js} +2 -2
  24. package/dist/chunk-FZMXAQA2.js +2 -0
  25. package/dist/chunk-FZMXAQA2.js.map +1 -0
  26. package/dist/{chunk-QNLO56AB.js → chunk-GEM5ED3Q.js} +2 -2
  27. package/dist/{chunk-7TTPXT4I.js → chunk-GXH2FNJU.js} +2 -2
  28. package/dist/chunk-HMVTAVD4.cjs +2 -0
  29. package/dist/{chunk-YXYX47FI.cjs.map → chunk-HMVTAVD4.cjs.map} +1 -1
  30. package/dist/chunk-IBAFRN67.cjs +2 -0
  31. package/dist/{chunk-DZMQJTOW.cjs.map → chunk-IBAFRN67.cjs.map} +1 -1
  32. package/dist/chunk-J73GN7VK.cjs +2 -0
  33. package/dist/{chunk-M7ZUQUKY.cjs.map → chunk-J73GN7VK.cjs.map} +1 -1
  34. package/dist/chunk-KKH43SVW.cjs +2 -0
  35. package/dist/{chunk-ECZY464Q.cjs.map → chunk-KKH43SVW.cjs.map} +1 -1
  36. package/dist/chunk-LD7YHVMH.cjs +2 -0
  37. package/dist/{chunk-QPNGTJFR.cjs.map → chunk-LD7YHVMH.cjs.map} +1 -1
  38. package/dist/{chunk-URCSQQVV.js → chunk-MBDFVUXG.js} +2 -2
  39. package/dist/chunk-NNPDC7K7.js +19 -0
  40. package/dist/chunk-NNPDC7K7.js.map +1 -0
  41. package/dist/chunk-O2VXK4BJ.cjs +2 -0
  42. package/dist/{chunk-SKM7EQRC.cjs.map → chunk-O2VXK4BJ.cjs.map} +1 -1
  43. package/dist/chunk-OE3QVFQR.cjs +2 -0
  44. package/dist/{chunk-2QXHITDN.cjs.map → chunk-OE3QVFQR.cjs.map} +1 -1
  45. package/dist/{chunk-JEHNXPMK.js → chunk-P6YCSUUX.js} +2 -2
  46. package/dist/{chunk-BHLEG7OQ.js → chunk-PIPS5SYM.js} +2 -2
  47. package/dist/{chunk-EQEBW7I7.js → chunk-PKVBRYCO.js} +2 -2
  48. package/dist/{chunk-4SJH7BAM.js → chunk-SR5T64DP.js} +2 -2
  49. package/dist/{chunk-J23KF5VM.js → chunk-T3LZIXXV.js} +2 -2
  50. package/dist/chunk-UJEHXXRU.cjs +2 -0
  51. package/dist/{chunk-WIH4AIQW.cjs.map → chunk-UJEHXXRU.cjs.map} +1 -1
  52. package/dist/chunk-UXK7PGJ3.cjs +2 -0
  53. package/dist/{chunk-NNURLPOI.cjs.map → chunk-UXK7PGJ3.cjs.map} +1 -1
  54. package/dist/{chunk-FX6GWDYQ.js → chunk-XV77F2MB.js} +2 -2
  55. package/dist/{chunk-WBJAWBJL.js → chunk-YIVRRRRB.js} +2 -2
  56. package/dist/chunk-YODZ2FBS.cjs +2 -0
  57. package/dist/{chunk-SBI55X4V.cjs.map → chunk-YODZ2FBS.cjs.map} +1 -1
  58. package/dist/{chunk-3KAAHRSY.js → chunk-YOTDZ46J.js} +2 -2
  59. package/dist/chunk-YQ22ZDIZ.js +2 -0
  60. package/dist/chunk-YQ22ZDIZ.js.map +1 -0
  61. package/dist/{chunk-4Q4K7G2O.js → chunk-ZZAKTBZ2.js} +2 -2
  62. package/dist/dialects/athena.cjs +1 -1
  63. package/dist/dialects/athena.d.cts +1 -1
  64. package/dist/dialects/athena.d.ts +1 -1
  65. package/dist/dialects/athena.js +1 -1
  66. package/dist/dialects/bigquery.cjs +1 -1
  67. package/dist/dialects/bigquery.d.cts +1 -1
  68. package/dist/dialects/bigquery.d.ts +1 -1
  69. package/dist/dialects/bigquery.js +1 -1
  70. package/dist/dialects/clickhouse.cjs +1 -1
  71. package/dist/dialects/clickhouse.d.cts +1 -1
  72. package/dist/dialects/clickhouse.d.ts +1 -1
  73. package/dist/dialects/clickhouse.js +1 -1
  74. package/dist/dialects/databricks.cjs +1 -1
  75. package/dist/dialects/databricks.d.cts +1 -1
  76. package/dist/dialects/databricks.d.ts +1 -1
  77. package/dist/dialects/databricks.js +1 -1
  78. package/dist/dialects/doris.cjs +1 -1
  79. package/dist/dialects/doris.d.cts +1 -1
  80. package/dist/dialects/doris.d.ts +1 -1
  81. package/dist/dialects/doris.js +1 -1
  82. package/dist/dialects/dremio.cjs +1 -1
  83. package/dist/dialects/dremio.d.cts +1 -1
  84. package/dist/dialects/dremio.d.ts +1 -1
  85. package/dist/dialects/dremio.js +1 -1
  86. package/dist/dialects/drill.cjs +1 -1
  87. package/dist/dialects/drill.d.cts +1 -1
  88. package/dist/dialects/drill.d.ts +1 -1
  89. package/dist/dialects/drill.js +1 -1
  90. package/dist/dialects/druid.cjs +1 -1
  91. package/dist/dialects/druid.d.cts +1 -1
  92. package/dist/dialects/druid.d.ts +1 -1
  93. package/dist/dialects/druid.js +1 -1
  94. package/dist/dialects/duckdb.cjs +13 -13
  95. package/dist/dialects/duckdb.d.cts +1 -1
  96. package/dist/dialects/duckdb.d.ts +1 -1
  97. package/dist/dialects/duckdb.js +1 -1
  98. package/dist/dialects/dune.cjs +1 -1
  99. package/dist/dialects/dune.d.cts +1 -1
  100. package/dist/dialects/dune.d.ts +1 -1
  101. package/dist/dialects/dune.js +1 -1
  102. package/dist/dialects/exasol.cjs +1 -1
  103. package/dist/dialects/exasol.d.cts +1 -1
  104. package/dist/dialects/exasol.d.ts +1 -1
  105. package/dist/dialects/exasol.js +1 -1
  106. package/dist/dialects/fabric.cjs +1 -1
  107. package/dist/dialects/fabric.d.cts +1 -1
  108. package/dist/dialects/fabric.d.ts +1 -1
  109. package/dist/dialects/fabric.js +1 -1
  110. package/dist/dialects/hive.cjs +1 -1
  111. package/dist/dialects/hive.d.cts +1 -1
  112. package/dist/dialects/hive.d.ts +1 -1
  113. package/dist/dialects/hive.js +1 -1
  114. package/dist/dialects/materialize.cjs +1 -1
  115. package/dist/dialects/materialize.d.cts +1 -1
  116. package/dist/dialects/materialize.d.ts +1 -1
  117. package/dist/dialects/materialize.js +1 -1
  118. package/dist/dialects/mysql.cjs +1 -1
  119. package/dist/dialects/mysql.d.cts +2 -1
  120. package/dist/dialects/mysql.d.ts +2 -1
  121. package/dist/dialects/mysql.js +1 -1
  122. package/dist/dialects/oracle.cjs +1 -1
  123. package/dist/dialects/oracle.cjs.map +1 -1
  124. package/dist/dialects/oracle.d.cts +12 -1
  125. package/dist/dialects/oracle.d.ts +12 -1
  126. package/dist/dialects/oracle.js +1 -1
  127. package/dist/dialects/oracle.js.map +1 -1
  128. package/dist/dialects/postgres.cjs +1 -1
  129. package/dist/dialects/postgres.d.cts +5 -1
  130. package/dist/dialects/postgres.d.ts +5 -1
  131. package/dist/dialects/postgres.js +1 -1
  132. package/dist/dialects/presto.cjs +1 -1
  133. package/dist/dialects/presto.d.cts +1 -1
  134. package/dist/dialects/presto.d.ts +1 -1
  135. package/dist/dialects/presto.js +1 -1
  136. package/dist/dialects/prql.cjs +1 -1
  137. package/dist/dialects/prql.d.cts +1 -1
  138. package/dist/dialects/prql.d.ts +1 -1
  139. package/dist/dialects/prql.js +1 -1
  140. package/dist/dialects/redshift.cjs +1 -1
  141. package/dist/dialects/redshift.d.cts +1 -1
  142. package/dist/dialects/redshift.d.ts +1 -1
  143. package/dist/dialects/redshift.js +1 -1
  144. package/dist/dialects/risingwave.cjs +1 -1
  145. package/dist/dialects/risingwave.d.cts +1 -1
  146. package/dist/dialects/risingwave.d.ts +1 -1
  147. package/dist/dialects/risingwave.js +1 -1
  148. package/dist/dialects/singlestore.cjs +1 -1
  149. package/dist/dialects/singlestore.d.cts +1 -1
  150. package/dist/dialects/singlestore.d.ts +1 -1
  151. package/dist/dialects/singlestore.js +1 -1
  152. package/dist/dialects/snowflake.cjs +1 -1
  153. package/dist/dialects/snowflake.d.cts +1 -1
  154. package/dist/dialects/snowflake.d.ts +1 -1
  155. package/dist/dialects/snowflake.js +1 -1
  156. package/dist/dialects/solr.cjs +1 -1
  157. package/dist/dialects/solr.d.cts +1 -1
  158. package/dist/dialects/solr.d.ts +1 -1
  159. package/dist/dialects/solr.js +1 -1
  160. package/dist/dialects/spark.cjs +1 -1
  161. package/dist/dialects/spark.d.cts +1 -1
  162. package/dist/dialects/spark.d.ts +1 -1
  163. package/dist/dialects/spark.js +1 -1
  164. package/dist/dialects/spark2.cjs +1 -1
  165. package/dist/dialects/spark2.d.cts +1 -1
  166. package/dist/dialects/spark2.d.ts +1 -1
  167. package/dist/dialects/spark2.js +1 -1
  168. package/dist/dialects/sqlite.cjs +1 -1
  169. package/dist/dialects/sqlite.d.cts +1 -1
  170. package/dist/dialects/sqlite.d.ts +1 -1
  171. package/dist/dialects/sqlite.js +1 -1
  172. package/dist/dialects/starrocks.cjs +1 -1
  173. package/dist/dialects/starrocks.d.cts +1 -1
  174. package/dist/dialects/starrocks.d.ts +1 -1
  175. package/dist/dialects/starrocks.js +1 -1
  176. package/dist/dialects/tableau.cjs +1 -1
  177. package/dist/dialects/tableau.d.cts +1 -1
  178. package/dist/dialects/tableau.d.ts +1 -1
  179. package/dist/dialects/tableau.js +1 -1
  180. package/dist/dialects/teradata.cjs +1 -1
  181. package/dist/dialects/teradata.d.cts +1 -1
  182. package/dist/dialects/teradata.d.ts +1 -1
  183. package/dist/dialects/teradata.js +1 -1
  184. package/dist/dialects/trino.cjs +1 -1
  185. package/dist/dialects/trino.d.cts +1 -1
  186. package/dist/dialects/trino.d.ts +1 -1
  187. package/dist/dialects/trino.js +1 -1
  188. package/dist/dialects/tsql.cjs +1 -1
  189. package/dist/dialects/tsql.d.cts +1 -1
  190. package/dist/dialects/tsql.d.ts +1 -1
  191. package/dist/dialects/tsql.js +1 -1
  192. package/dist/index.cjs +5 -5
  193. package/dist/index.cjs.map +1 -1
  194. package/dist/index.d.cts +2 -2
  195. package/dist/index.d.ts +2 -2
  196. package/dist/index.js +1 -1
  197. package/dist/index.js.map +1 -1
  198. package/dist/{tokens-BTiJDoZO.d.ts → tokens-DQmh7u9L.d.cts} +10 -7
  199. package/dist/{tokens-BTiJDoZO.d.cts → tokens-DQmh7u9L.d.ts} +10 -7
  200. package/package.json +1 -1
  201. package/dist/chunk-2QXHITDN.cjs +0 -2
  202. package/dist/chunk-3OH4CQPZ.js +0 -2
  203. package/dist/chunk-3OH4CQPZ.js.map +0 -1
  204. package/dist/chunk-5KXX2V4Z.cjs +0 -2
  205. package/dist/chunk-5LK25AVT.js +0 -2
  206. package/dist/chunk-5LK25AVT.js.map +0 -1
  207. package/dist/chunk-B7N6EHLE.cjs +0 -3
  208. package/dist/chunk-BLIL2VJH.cjs +0 -2
  209. package/dist/chunk-CFQXU5IS.js +0 -19
  210. package/dist/chunk-CFQXU5IS.js.map +0 -1
  211. package/dist/chunk-DZMQJTOW.cjs +0 -2
  212. package/dist/chunk-E4JORBQC.cjs +0 -2
  213. package/dist/chunk-ECZY464Q.cjs +0 -2
  214. package/dist/chunk-EORCZG7N.cjs +0 -4
  215. package/dist/chunk-EZ3T7JOU.cjs +0 -2
  216. package/dist/chunk-IU7ARLOI.cjs +0 -2
  217. package/dist/chunk-M7ZUQUKY.cjs +0 -2
  218. package/dist/chunk-NNURLPOI.cjs +0 -2
  219. package/dist/chunk-QPNGTJFR.cjs +0 -2
  220. package/dist/chunk-SBI55X4V.cjs +0 -2
  221. package/dist/chunk-SKM7EQRC.cjs +0 -2
  222. package/dist/chunk-T6FUUZUR.cjs +0 -19
  223. package/dist/chunk-T6FUUZUR.cjs.map +0 -1
  224. package/dist/chunk-V2VRKBFH.cjs +0 -2
  225. package/dist/chunk-V2VRKBFH.cjs.map +0 -1
  226. package/dist/chunk-WIH4AIQW.cjs +0 -2
  227. package/dist/chunk-YXYX47FI.cjs +0 -2
  228. /package/dist/{chunk-V5MU576A.js.map → chunk-4UJWN7AG.js.map} +0 -0
  229. /package/dist/{chunk-VRCV3F7C.js.map → chunk-AZNXXBMF.js.map} +0 -0
  230. /package/dist/{chunk-EHG67C2E.js.map → chunk-CELHDVUC.js.map} +0 -0
  231. /package/dist/{chunk-C7U65H24.js.map → chunk-FHZLNMGS.js.map} +0 -0
  232. /package/dist/{chunk-QNLO56AB.js.map → chunk-GEM5ED3Q.js.map} +0 -0
  233. /package/dist/{chunk-7TTPXT4I.js.map → chunk-GXH2FNJU.js.map} +0 -0
  234. /package/dist/{chunk-URCSQQVV.js.map → chunk-MBDFVUXG.js.map} +0 -0
  235. /package/dist/{chunk-JEHNXPMK.js.map → chunk-P6YCSUUX.js.map} +0 -0
  236. /package/dist/{chunk-BHLEG7OQ.js.map → chunk-PIPS5SYM.js.map} +0 -0
  237. /package/dist/{chunk-EQEBW7I7.js.map → chunk-PKVBRYCO.js.map} +0 -0
  238. /package/dist/{chunk-4SJH7BAM.js.map → chunk-SR5T64DP.js.map} +0 -0
  239. /package/dist/{chunk-J23KF5VM.js.map → chunk-T3LZIXXV.js.map} +0 -0
  240. /package/dist/{chunk-FX6GWDYQ.js.map → chunk-XV77F2MB.js.map} +0 -0
  241. /package/dist/{chunk-WBJAWBJL.js.map → chunk-YIVRRRRB.js.map} +0 -0
  242. /package/dist/{chunk-3KAAHRSY.js.map → chunk-YOTDZ46J.js.map} +0 -0
  243. /package/dist/{chunk-4Q4K7G2O.js.map → chunk-ZZAKTBZ2.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/huydna/projects/sqlingo.js/packages/sqlingo/dist/index.cjs","../package.json","../src/diff.ts","../src/lineage.ts","../src/planner.ts","../src/executor/table.ts","../src/index.ts"],"names":["package_default","_Insert","expression","__name","Insert","_Remove","Remove","_Move","source","target","Move","_Update","Update","_Keep","Keep","diff","options","matchings","deltaOnly","kwargs","computeNodeMappings","oldNodes","newNodes","nodeMapping","i","oldNode","newNode","sourceNodes","targetNodes","sourceSet","targetSet","copy","n","sourceCopy","targetCopy","sourceMapping","targetMapping","s","t","node","ChangeDistiller","UPDATABLE_EXPRESSION_TYPES","AliasExpr","BooleanExpr","ColumnExpr","DataTypeExpr","LambdaExpr","LiteralExpr","TableExpr","WindowExpr","IGNORED_LEAF_EXPRESSION_TYPES","IdentifierExpr","_ChangeDistiller","f","dialect","Dialect","preMatchedNodes","type","isPreMatched","targetMatch","computedMatchings","v","k","editScript","targetNode","sourceNode","identicalNodes","sParent","tParent","sourceLeaves","getNonExpressionLeaves","targetLeaves","sourceArgs","expressionOnlyArgs","targetArgs","lcsResult","lcs","l","r","argsLcs","moveEdits","a","leavesMatchingSet","matchingSet","orderedUnmatchedSource","orderedUnmatchedTarget","isSameType","sourceLeafIds","getExpressionLeaves","targetLeafIds","maxLeavesNum","leafSimilarityScore","commonLeavesNum","sLeaf","tLeaf","adjustedT","sourceHisto","targetHisto","sourceTotal","targetTotal","totalGrams","overlapLen","count","gram","gramCount","candidateMatchings","sourceExpressionLeaves","targetExpressionLeaves","sourceLeaf","targetLeaf","similarityScore","parentSimilarityScore","b","candidate","cached","str","histo","hasChildExprs","arg","value","Expression","JoinExpr","AnonymousExpr","sThis","tThis","_seqA","_seqB","equal","seqA","seqB","lenA","lenB","j","top","left","_Node","d","opts","nodes","edges","label","title","group"],"mappings":"AAAA,yuBAAyD,wDAAyyU,ICAl2UA,EAAAA,CAAA,CACC,OAAA,CAAW,2CAAA,CACX,IAAA,CAAQ,SAAA,CACR,OAAA,CAAW,CACV,MAAA,CAAU,0CAAA,CACV,OAAA,CAAW,QAAA,CACX,GAAA,CAAO,oCACR,CAAA,CACA,OAAA,CAAW,QAAA,CACX,IAAA,CAAQ,QAAA,CACR,WAAA,CAAe,CAAA,CAAA,CACf,WAAA,CAAe,oKAAA,CACf,IAAA,CAAQ,gBAAA,CACR,MAAA,CAAU,eAAA,CACV,KAAA,CAAS,iBAAA,CACT,OAAA,CAAW,CACV,GAAA,CAAK,CACJ,KAAA,CAAS,mBAAA,CACT,MAAA,CAAU,iBAAA,CACV,OAAA,CAAW,kBACZ,CAAA,CACA,UAAA,CAAY,CACX,KAAA,CAAS,6BAAA,CACT,MAAA,CAAU,2BAAA,CACV,OAAA,CAAW,4BACZ,CAAA,CACA,YAAA,CAAc,CACb,KAAA,CAAS,+BAAA,CACT,MAAA,CAAU,6BAAA,CACV,OAAA,CAAW,8BACZ,CAAA,CACA,cAAA,CAAgB,CACf,KAAA,CAAS,iCAAA,CACT,MAAA,CAAU,+BAAA,CACV,OAAA,CAAW,gCACZ,CAAA,CACA,cAAA,CAAgB,CACf,KAAA,CAAS,iCAAA,CACT,M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CAAAA,CACAC,CAAAA,CAEAvG,CAAAA,CAAK,WAAA,WAAsBS,oBAAAA,CAAAA,CAC7B4F,CAAAA,CAAQ,CAAA,KAAA,EAAQrG,CAAAA,CAAK,UAAA,CAAW,IAAA,CAAK,IAAI,CAAA,CAAA;AAmftC;AALH,EAAA;AAAA;AAOO,2GAAA;AAAA;AAE4B,gCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASG,mCAAA;AAAA;AAEzB,QAAA;AAAA;AAAA;AC1fV,MAAA;AAAA;AAmWW;ACvUA;ACZN","file":"/home/huydna/projects/sqlingo.js/packages/sqlingo/dist/index.cjs","sourcesContent":[null,"{\n\t\"$schema\": \"https://json.schemastore.org/package.json\",\n\t\"name\": \"sqlingo\",\n\t\"sqlglot\": {\n\t\t\"commit\": \"872625011c6a601d80dc61fdedf5d7356c836de0\",\n\t\t\"version\": \"30.1.0\",\n\t\t\"url\": \"https://github.com/tobymao/sqlglot\"\n\t},\n\t\"version\": \"0.12.2\",\n\t\"type\": \"module\",\n\t\"sideEffects\": false,\n\t\"description\": \"SQL parser, transpiler, optimizer, and engine for JavaScript/TypeScript - 32 dialects (Postgres, MySQL, BigQuery, Snowflake, DuckDB, etc). Port of Python SQLGlot.\",\n\t\"main\": \"dist/index.cjs\",\n\t\"module\": \"dist/index.js\",\n\t\"types\": \"dist/index.d.ts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"types\": \"./dist/index.d.ts\",\n\t\t\t\"import\": \"./dist/index.js\",\n\t\t\t\"require\": \"./dist/index.cjs\"\n\t\t},\n\t\t\"./athena\": {\n\t\t\t\"types\": \"./dist/dialects/athena.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/athena.js\",\n\t\t\t\"require\": \"./dist/dialects/athena.cjs\"\n\t\t},\n\t\t\"./bigquery\": {\n\t\t\t\"types\": \"./dist/dialects/bigquery.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/bigquery.js\",\n\t\t\t\"require\": \"./dist/dialects/bigquery.cjs\"\n\t\t},\n\t\t\"./clickhouse\": {\n\t\t\t\"types\": \"./dist/dialects/clickhouse.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/clickhouse.js\",\n\t\t\t\"require\": \"./dist/dialects/clickhouse.cjs\"\n\t\t},\n\t\t\"./databricks\": {\n\t\t\t\"types\": \"./dist/dialects/databricks.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/databricks.js\",\n\t\t\t\"require\": \"./dist/dialects/databricks.cjs\"\n\t\t},\n\t\t\"./doris\": {\n\t\t\t\"types\": \"./dist/dialects/doris.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/doris.js\",\n\t\t\t\"require\": \"./dist/dialects/doris.cjs\"\n\t\t},\n\t\t\"./dremio\": {\n\t\t\t\"types\": \"./dist/dialects/dremio.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/dremio.js\",\n\t\t\t\"require\": \"./dist/dialects/dremio.cjs\"\n\t\t},\n\t\t\"./drill\": {\n\t\t\t\"types\": \"./dist/dialects/drill.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/drill.js\",\n\t\t\t\"require\": \"./dist/dialects/drill.cjs\"\n\t\t},\n\t\t\"./druid\": {\n\t\t\t\"types\": \"./dist/dialects/druid.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/druid.js\",\n\t\t\t\"require\": \"./dist/dialects/druid.cjs\"\n\t\t},\n\t\t\"./duckdb\": {\n\t\t\t\"types\": \"./dist/dialects/duckdb.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/duckdb.js\",\n\t\t\t\"require\": \"./dist/dialects/duckdb.cjs\"\n\t\t},\n\t\t\"./dune\": {\n\t\t\t\"types\": \"./dist/dialects/dune.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/dune.js\",\n\t\t\t\"require\": \"./dist/dialects/dune.cjs\"\n\t\t},\n\t\t\"./exasol\": {\n\t\t\t\"types\": \"./dist/dialects/exasol.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/exasol.js\",\n\t\t\t\"require\": \"./dist/dialects/exasol.cjs\"\n\t\t},\n\t\t\"./fabric\": {\n\t\t\t\"types\": \"./dist/dialects/fabric.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/fabric.js\",\n\t\t\t\"require\": \"./dist/dialects/fabric.cjs\"\n\t\t},\n\t\t\"./hive\": {\n\t\t\t\"types\": \"./dist/dialects/hive.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/hive.js\",\n\t\t\t\"require\": \"./dist/dialects/hive.cjs\"\n\t\t},\n\t\t\"./materialize\": {\n\t\t\t\"types\": \"./dist/dialects/materialize.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/materialize.js\",\n\t\t\t\"require\": \"./dist/dialects/materialize.cjs\"\n\t\t},\n\t\t\"./mysql\": {\n\t\t\t\"types\": \"./dist/dialects/mysql.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/mysql.js\",\n\t\t\t\"require\": \"./dist/dialects/mysql.cjs\"\n\t\t},\n\t\t\"./mssql\": {\n\t\t\t\"types\": \"./dist/dialects/tsql.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/tsql.js\",\n\t\t\t\"require\": \"./dist/dialects/tsql.cjs\"\n\t\t},\n\t\t\"./oracle\": {\n\t\t\t\"types\": \"./dist/dialects/oracle.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/oracle.js\",\n\t\t\t\"require\": \"./dist/dialects/oracle.cjs\"\n\t\t},\n\t\t\"./postgres\": {\n\t\t\t\"types\": \"./dist/dialects/postgres.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/postgres.js\",\n\t\t\t\"require\": \"./dist/dialects/postgres.cjs\"\n\t\t},\n\t\t\"./presto\": {\n\t\t\t\"types\": \"./dist/dialects/presto.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/presto.js\",\n\t\t\t\"require\": \"./dist/dialects/presto.cjs\"\n\t\t},\n\t\t\"./prql\": {\n\t\t\t\"types\": \"./dist/dialects/prql.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/prql.js\",\n\t\t\t\"require\": \"./dist/dialects/prql.cjs\"\n\t\t},\n\t\t\"./redshift\": {\n\t\t\t\"types\": \"./dist/dialects/redshift.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/redshift.js\",\n\t\t\t\"require\": \"./dist/dialects/redshift.cjs\"\n\t\t},\n\t\t\"./risingwave\": {\n\t\t\t\"types\": \"./dist/dialects/risingwave.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/risingwave.js\",\n\t\t\t\"require\": \"./dist/dialects/risingwave.cjs\"\n\t\t},\n\t\t\"./singlestore\": {\n\t\t\t\"types\": \"./dist/dialects/singlestore.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/singlestore.js\",\n\t\t\t\"require\": \"./dist/dialects/singlestore.cjs\"\n\t\t},\n\t\t\"./snowflake\": {\n\t\t\t\"types\": \"./dist/dialects/snowflake.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/snowflake.js\",\n\t\t\t\"require\": \"./dist/dialects/snowflake.cjs\"\n\t\t},\n\t\t\"./solr\": {\n\t\t\t\"types\": \"./dist/dialects/solr.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/solr.js\",\n\t\t\t\"require\": \"./dist/dialects/solr.cjs\"\n\t\t},\n\t\t\"./spark\": {\n\t\t\t\"types\": \"./dist/dialects/spark.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/spark.js\",\n\t\t\t\"require\": \"./dist/dialects/spark.cjs\"\n\t\t},\n\t\t\"./spark2\": {\n\t\t\t\"types\": \"./dist/dialects/spark2.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/spark2.js\",\n\t\t\t\"require\": \"./dist/dialects/spark2.cjs\"\n\t\t},\n\t\t\"./sqlite\": {\n\t\t\t\"types\": \"./dist/dialects/sqlite.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/sqlite.js\",\n\t\t\t\"require\": \"./dist/dialects/sqlite.cjs\"\n\t\t},\n\t\t\"./starrocks\": {\n\t\t\t\"types\": \"./dist/dialects/starrocks.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/starrocks.js\",\n\t\t\t\"require\": \"./dist/dialects/starrocks.cjs\"\n\t\t},\n\t\t\"./tableau\": {\n\t\t\t\"types\": \"./dist/dialects/tableau.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/tableau.js\",\n\t\t\t\"require\": \"./dist/dialects/tableau.cjs\"\n\t\t},\n\t\t\"./teradata\": {\n\t\t\t\"types\": \"./dist/dialects/teradata.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/teradata.js\",\n\t\t\t\"require\": \"./dist/dialects/teradata.cjs\"\n\t\t},\n\t\t\"./trino\": {\n\t\t\t\"types\": \"./dist/dialects/trino.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/trino.js\",\n\t\t\t\"require\": \"./dist/dialects/trino.cjs\"\n\t\t},\n\t\t\"./tsql\": {\n\t\t\t\"types\": \"./dist/dialects/tsql.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/tsql.js\",\n\t\t\t\"require\": \"./dist/dialects/tsql.cjs\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"test\": \"vitest\",\n\t\t\"test:ui\": \"vitest --ui\",\n\t\t\"test:coverage\": \"vitest --coverage\",\n\t\t\"build\": \"tsup\",\n\t\t\"dev\": \"tsup --watch\",\n\t\t\"lint\": \"eslint .\",\n\t\t\"lint:fix\": \"eslint . --fix\",\n\t\t\"typecheck\": \"tsc --noEmit\",\n\t\t\"prepublishOnly\": \"cp README.md README.repo.md && cp README.npm.md README.md\",\n\t\t\"postpublish\": \"mv README.repo.md README.md\"\n\t},\n\t\"keywords\": [\n\t\t\"sql\",\n\t\t\"sqlingo\",\n\t\t\"sqlingo.js\",\n\t\t\"tokenizer\",\n\t\t\"parser\",\n\t\t\"transpiler\",\n\t\t\"optimizer\",\n\t\t\"sqlingo\",\n\t\t\"sqlglot\",\n\t\t\"sql-parser\",\n\t\t\"sql-transpiler\",\n\t\t\"sql-optimizer\",\n\t\t\"sql-engine\",\n\t\t\"sql-builder\",\n\t\t\"query-builder\",\n\t\t\"sql-to-sql\",\n\t\t\"sql-converter\",\n\t\t\"sql-formatter\",\n\t\t\"ast\",\n\t\t\"abstract-syntax-tree\",\n\t\t\"column-lineage\",\n\t\t\"dialect\",\n\t\t\"mysql\",\n\t\t\"postgres\",\n\t\t\"bigquery\",\n\t\t\"snowflake\",\n\t\t\"duckdb\",\n\t\t\"clickhouse\",\n\t\t\"redshift\",\n\t\t\"athena\",\n\t\t\"hive\",\n\t\t\"spark\",\n\t\t\"oracle\",\n\t\t\"tsql\",\n\t\t\"sqlite\",\n\t\t\"presto\",\n\t\t\"trino\",\n\t\t\"javascript\",\n\t\t\"typescript\"\n\t],\n\t\"author\": \"Huy DNA\",\n\t\"license\": \"MIT\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"https://github.com/huydo862003/sqlingo.git\"\n\t},\n\t\"bugs\": {\n\t\t\"url\": \"https://github.com/huydo862003/sqlingo/issues\"\n\t},\n\t\"homepage\": \"https://huydo862003.github.io/sqlingo\",\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\",\n\t\t\"README.md\",\n\t\t\"COPYRIGHT_NOTICE\",\n\t\t\"CHANGELOG.md\"\n\t],\n\t\"devDependencies\": {\n\t\t\"@types/luxon\": \"^3.7.5\",\n\t\t\"@types/node\": \"^26.6.3\",\n\t\t\"tsup\": \"^8.5.1\",\n\t\t\"typescript\": \"^5.9.3\",\n\t\t\"vite\": \"^7.3.6\",\n\t\t\"vitest\": \"5.0.1\"\n\t},\n\t\"peerDependencies\": {\n\t\t\"luxon\": \"^3.7.2\"\n\t}\n}\n","import {\n Dialect,\n} from './dialects/dialect';\nimport {\n AliasExpr, AnonymousExpr, BooleanExpr, ColumnExpr, DataTypeExpr, Expression, IdentifierExpr, JoinExpr, LambdaExpr, LiteralExpr, TableExpr, WindowExpr,\n} from './expressions';\nimport type {\n Generator as SqlGenerator,\n} from './generator';\n\n/**\n * Indicates that a new node has been inserted\n */\nexport class Insert {\n constructor (public readonly expression: Expression) {}\n toJSON () {\n return {\n type: 'Insert',\n expression: this.expression.sql(),\n };\n }\n}\n\n/**\n * Indicates that an existing node has been removed\n */\nexport class Remove {\n constructor (public readonly expression: Expression) {}\n toJSON () {\n return {\n type: 'Remove',\n expression: this.expression.sql(),\n };\n }\n}\n\n/**\n * Indicates that an existing node's position within the tree has changed\n */\nexport class Move {\n constructor (\n public readonly source: Expression,\n public readonly target: Expression,\n ) {}\n\n toJSON () {\n return {\n type: 'Move',\n source: this.source.sql(),\n target: this.target.sql(),\n };\n }\n}\n\n/**\n * Indicates that an existing node has been updated\n */\nexport class Update {\n constructor (\n public readonly source: Expression,\n public readonly target: Expression,\n ) {}\n\n toJSON () {\n return {\n type: 'Update',\n source: this.source.sql(),\n target: this.target.sql(),\n };\n }\n}\n\n/**\n * Indicates that an existing node hasn't been changed\n */\nexport class Keep {\n constructor (\n public readonly source: Expression,\n public readonly target: Expression,\n ) {}\n\n toJSON () {\n return {\n type: 'Keep',\n source: this.source.sql(),\n target: this.target.sql(),\n };\n }\n}\n\n/**\n * Union type representing any possible tree edit operation\n */\nexport type Edit = Insert | Remove | Move | Update | Keep;\n\ntype MatchingPair = [Expression, Expression];\n\nexport function diff (\n source: Expression,\n target: Expression,\n options: {\n matchings?: MatchingPair[];\n deltaOnly?: boolean;\n [key: string]: unknown;\n } = {},\n): Edit[] {\n let {\n matchings = [],\n\n deltaOnly = false,\n\n ...kwargs\n } = options;\n\n function computeNodeMappings (\n oldNodes: Expression[],\n newNodes: Expression[],\n ): Map<Expression, Expression> {\n const nodeMapping = new Map<Expression, Expression>();\n\n // Zip reversed arrays\n for (let i = 0; i < oldNodes.length; i++) {\n const oldNode = oldNodes[oldNodes.length - 1 - i];\n const newNode = newNodes[newNodes.length - 1 - i];\n\n newNode.computeHash();\n nodeMapping.set(oldNode, newNode);\n }\n\n return nodeMapping;\n }\n\n const sourceNodes = Array.from(source.walk());\n const targetNodes = Array.from(target.walk());\n\n const sourceSet = new Set(sourceNodes);\n const targetSet = new Set(targetNodes);\n\n const copy = (\n sourceNodes.length !== sourceSet.size\n || targetNodes.length !== targetSet.size\n || sourceNodes.some((n) => targetSet.has(n))\n );\n\n const sourceCopy = copy ? source.copy() : source;\n const targetCopy = copy ? target.copy() : target;\n\n try {\n if (copy && 0 < matchings.length) {\n const sourceMapping = computeNodeMappings(sourceNodes, Array.from(sourceCopy.walk()));\n const targetMapping = computeNodeMappings(targetNodes, Array.from(targetCopy.walk()));\n\n matchings = matchings.map(([\n s,\n t,\n ]) => [\n sourceMapping.get(s)!,\n targetMapping.get(t)!,\n ]);\n } else {\n [\n ...sourceNodes,\n ...targetNodes,\n ].reverse().forEach((node) => {\n node.computeHash();\n });\n }\n\n return new ChangeDistiller(kwargs).diff(\n sourceCopy,\n targetCopy,\n {\n deltaOnly,\n matchings,\n },\n );\n } finally {\n if (!copy) {\n [\n ...sourceNodes,\n ...targetNodes,\n ].forEach((node) => {\n node.resetHash();\n });\n }\n }\n}\n\nconst UPDATABLE_EXPRESSION_TYPES = [\n AliasExpr,\n BooleanExpr,\n ColumnExpr,\n DataTypeExpr,\n LambdaExpr,\n LiteralExpr,\n TableExpr,\n WindowExpr,\n];\n\nconst IGNORED_LEAF_EXPRESSION_TYPES = [IdentifierExpr];\n\nclass ChangeDistiller {\n private f: number;\n private t: number;\n private sqlGenerator: SqlGenerator;\n private bigramHistoCache = new Map<Expression, Map<string, number>>();\n private unmatchedSourceNodes = new Set<Expression>();\n private unmatchedTargetNodes = new Set<Expression>();\n private source?: Expression;\n private sourceIndex = new Map<Expression, Expression>();\n private target?: Expression;\n private targetIndex = new Map<Expression, Expression>();\n\n constructor (options: {\n f?: number;\n t?: number;\n dialect?: string;\n } = {}) {\n const {\n f = 0.6,\n t = 0.6,\n dialect,\n } = options;\n\n this.f = f;\n this.t = t;\n this.sqlGenerator = Dialect.getOrRaise(dialect).generator({\n comments: false,\n });\n }\n\n diff (\n source: Expression,\n target: Expression,\n options: {\n deltaOnly?: boolean;\n matchings?: MatchingPair[];\n } = {},\n ): Edit[] {\n const {\n deltaOnly = false,\n matchings = [],\n } = options;\n\n const preMatchedNodes = new Map<Expression, Expression>(matchings);\n\n this.source = source;\n this.target = target;\n\n for (const n of source.bfs()) {\n if (!IGNORED_LEAF_EXPRESSION_TYPES.some((type) => n instanceof type)) {\n this.sourceIndex.set(n, n);\n if (!preMatchedNodes.has(n)) this.unmatchedSourceNodes.add(n);\n }\n }\n\n for (const n of target.bfs()) {\n if (!IGNORED_LEAF_EXPRESSION_TYPES.some((type) => n instanceof type)) {\n this.targetIndex.set(n, n);\n // Check if n is a target in preMatchedNodes\n let isPreMatched = false;\n\n for (const targetMatch of preMatchedNodes.values()) {\n if (targetMatch === n) {\n isPreMatched = true;\n break;\n }\n }\n if (!isPreMatched) this.unmatchedTargetNodes.add(n);\n }\n }\n\n this.bigramHistoCache.clear();\n\n const computedMatchings = this.computeMatchingSet();\n\n preMatchedNodes.forEach((v, k) => computedMatchings.set(k, v));\n\n return this.generateEditScript(computedMatchings, {\n deltaOnly,\n });\n }\n\n private generateEditScript (\n matchings: Map<Expression, Expression>,\n options: {\n deltaOnly: boolean;\n },\n ): Edit[] {\n const {\n deltaOnly,\n } = options;\n const editScript: Edit[] = [];\n\n this.unmatchedSourceNodes.forEach((node) => editScript.push(new Remove(node)));\n this.unmatchedTargetNodes.forEach((node) => editScript.push(new Insert(node)));\n\n matchings.forEach((targetNode, sourceNode) => {\n const identicalNodes = sourceNode.equals(targetNode);\n\n if (!UPDATABLE_EXPRESSION_TYPES.some((type) => sourceNode instanceof type) || identicalNodes) {\n if (identicalNodes) {\n const sParent = sourceNode.parent;\n const tParent = targetNode.parent;\n\n if (\n (!sParent && tParent)\n || (sParent && !tParent)\n || (sParent && tParent && matchings.get(sParent) !== tParent)\n ) {\n editScript.push(new Move(sourceNode, targetNode));\n }\n } else {\n editScript.push(...this.generateMoveEdits(sourceNode, targetNode, matchings));\n }\n\n // Check non-expression leaves (attributes)\n const sourceLeaves = Object.fromEntries(getNonExpressionLeaves(sourceNode));\n const targetLeaves = Object.fromEntries(getNonExpressionLeaves(targetNode));\n\n if (JSON.stringify(sourceLeaves) !== JSON.stringify(targetLeaves)) {\n editScript.push(new Update(sourceNode, targetNode));\n } else if (!deltaOnly) {\n editScript.push(new Keep(sourceNode, targetNode));\n }\n } else {\n editScript.push(new Update(sourceNode, targetNode));\n }\n });\n\n return editScript;\n }\n\n private generateMoveEdits (\n source: Expression,\n target: Expression,\n matchings: Map<Expression, Expression>,\n ): Move[] {\n const sourceArgs = [...expressionOnlyArgs(source)];\n const targetArgs = [...expressionOnlyArgs(target)];\n\n // LCS expects a comparator that returns true if source element matches target element\n const lcsResult = lcs(\n sourceArgs,\n targetArgs,\n (l, r) => matchings.get(l) === r,\n );\n const argsLcs = new Set(lcsResult);\n\n const moveEdits: Move[] = [];\n\n for (const a of sourceArgs) {\n // If the node is matched but its position in the arg list changed (not in LCS), it's a Move\n if (!argsLcs.has(a) && !this.unmatchedSourceNodes.has(a)) {\n const targetNode = matchings.get(a)!;\n\n moveEdits.push(new Move(this.sourceIndex.get(a)!, this.targetIndex.get(targetNode)!));\n }\n }\n\n return moveEdits;\n }\n\n private computeMatchingSet (): Map<Expression, Expression> {\n const leavesMatchingSet = this.computeLeafMatchingSet();\n const matchingSet = new Map<Expression, Expression>(leavesMatchingSet);\n\n // Maintain BFS order for unmatched nodes\n const orderedUnmatchedSource: Expression[] = [];\n\n for (const n of this.source?.bfs() ?? []) {\n if (this.unmatchedSourceNodes.has(n)) orderedUnmatchedSource.push(n);\n }\n\n const orderedUnmatchedTarget: Expression[] = [];\n\n for (const n of this.target?.bfs() ?? []) {\n if (this.unmatchedTargetNodes.has(n)) orderedUnmatchedTarget.push(n);\n };\n\n for (const sourceNode of orderedUnmatchedSource) {\n for (const targetNode of orderedUnmatchedTarget) {\n if (isSameType(sourceNode, targetNode)) {\n const sourceLeafIds = new Set(getExpressionLeaves(sourceNode));\n const targetLeafIds = new Set(getExpressionLeaves(targetNode));\n\n const maxLeavesNum = Math.max(sourceLeafIds.size, targetLeafIds.size);\n let leafSimilarityScore = 0.0;\n\n if (0 < maxLeavesNum) {\n let commonLeavesNum = 0;\n\n for (const [\n sLeaf,\n tLeaf,\n ] of leavesMatchingSet) {\n if (sourceLeafIds.has(sLeaf) && targetLeafIds.has(tLeaf)) {\n commonLeavesNum++;\n }\n }\n leafSimilarityScore = commonLeavesNum / maxLeavesNum;\n }\n\n const adjustedT = 4 < Math.min(sourceLeafIds.size, targetLeafIds.size) ? this.t : 0.4;\n\n if (\n 0.8 <= leafSimilarityScore\n || (adjustedT <= leafSimilarityScore && this.f <= this.diceCoefficient(sourceNode, targetNode))\n ) {\n matchingSet.set(sourceNode, targetNode);\n this.unmatchedSourceNodes.delete(sourceNode);\n this.unmatchedTargetNodes.delete(targetNode);\n orderedUnmatchedTarget.splice(orderedUnmatchedTarget.indexOf(targetNode), 1);\n break;\n }\n }\n }\n }\n\n return matchingSet;\n }\n\n private diceCoefficient (source: Expression, target: Expression): number {\n const sourceHisto = this.getBigramHisto(source);\n const targetHisto = this.getBigramHisto(target);\n\n let sourceTotal = 0;\n\n sourceHisto.forEach((v) => {\n sourceTotal += v;\n });\n let targetTotal = 0;\n\n targetHisto.forEach((v) => {\n targetTotal += v;\n });\n\n const totalGrams = sourceTotal + targetTotal;\n\n if (totalGrams === 0) return source.equals(target) ? 1.0 : 0.0;\n\n let overlapLen = 0;\n\n sourceHisto.forEach((count, gram) => {\n const gramCount = targetHisto.get(gram);\n\n if (gramCount !== undefined) {\n overlapLen += Math.min(count, gramCount);\n }\n });\n\n return (2 * overlapLen) / totalGrams;\n }\n\n private computeLeafMatchingSet (): Map<Expression, Expression> {\n const candidateMatchings: Array<{\n similarity: number;\n parentSimilarity: number;\n index: number;\n sourceLeaf: Expression;\n targetLeaf: Expression;\n }> = [];\n\n const sourceExpressionLeaves = this.source\n ? [...getExpressionLeaves(this.source)]\n : [];\n const targetExpressionLeaves = this.target\n ? [...getExpressionLeaves(this.target)]\n : [];\n\n for (const sourceLeaf of sourceExpressionLeaves) {\n for (const targetLeaf of targetExpressionLeaves) {\n if (isSameType(sourceLeaf, targetLeaf)) {\n const similarityScore = this.diceCoefficient(sourceLeaf, targetLeaf);\n\n if (this.f <= similarityScore) {\n candidateMatchings.push({\n similarity: -similarityScore, // Negative for min-priority behavior\n parentSimilarity: -parentSimilarityScore(sourceLeaf, targetLeaf),\n index: candidateMatchings.length,\n sourceLeaf,\n targetLeaf,\n });\n }\n }\n }\n }\n\n // Sort to simulate heappop (highest similarity first)\n candidateMatchings.sort((a, b) => {\n if (a.similarity !== b.similarity) return a.similarity - b.similarity;\n if (a.parentSimilarity !== b.parentSimilarity) return a.parentSimilarity - b.parentSimilarity;\n\n return a.index - b.index;\n });\n\n const matchingSet = new Map<Expression, Expression>();\n\n for (const candidate of candidateMatchings) {\n const {\n sourceLeaf, targetLeaf,\n } = candidate;\n\n if (\n this.unmatchedSourceNodes.has(sourceLeaf)\n && this.unmatchedTargetNodes.has(targetLeaf)\n ) {\n matchingSet.set(sourceLeaf, targetLeaf);\n this.unmatchedSourceNodes.delete(sourceLeaf);\n this.unmatchedTargetNodes.delete(targetLeaf);\n }\n }\n\n return matchingSet;\n }\n\n private getBigramHisto (expression: Expression): Map<string, number> {\n const cached = this.bigramHistoCache.get(expression);\n\n if (cached !== undefined) return cached;\n\n const str = this.sqlGenerator.generate(expression);\n const histo = new Map<string, number>();\n\n for (let i = 0; i < str.length - 1; i++) {\n const gram = str.substring(i, i + 2);\n\n histo.set(gram, (histo.get(gram) || 0) + 1);\n }\n this.bigramHistoCache.set(expression, histo);\n\n return histo;\n }\n}\n\n/**\n * Recursively finds all leaf nodes in an expression tree\n */\nexport function* getExpressionLeaves (expression: Expression): Generator<Expression> {\n let hasChildExprs = false;\n\n for (const node of expression.iterExpressions()) {\n if (!IGNORED_LEAF_EXPRESSION_TYPES.some((type) => node instanceof type)) {\n hasChildExprs = true;\n yield* getExpressionLeaves(node);\n }\n }\n\n if (!hasChildExprs) {\n yield expression;\n }\n}\n\n/**\n * Yields non-expression attributes (metadata) of a node for Update detection\n */\nexport function* getNonExpressionLeaves (expression: Expression): Generator<[string, unknown]> {\n for (const [\n arg,\n value,\n ] of Object.entries(expression.args)) {\n if (\n value === null\n || value === undefined\n || value instanceof Expression\n || (Array.isArray(value) && value[0] instanceof Expression)\n ) {\n continue;\n }\n\n yield [\n arg,\n value,\n ];\n }\n}\n\n/**\n * Determines if two nodes are of the same semantic type\n */\nexport function isSameType (source: Expression, target: Expression): boolean {\n if (source.constructor === target.constructor) {\n if (source instanceof JoinExpr && target instanceof JoinExpr) {\n return source.args.side === target.args.side;\n }\n\n if (source instanceof AnonymousExpr && target instanceof AnonymousExpr) {\n const sThis = source.args.this;\n const tThis = target.args.this;\n\n if (sThis instanceof Expression && tThis instanceof Expression) {\n return sThis.equals(tThis);\n }\n\n return sThis === tThis;\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * Calculates a similarity score based on the depth of matching parent types\n */\nexport function parentSimilarityScore (\n source: Expression | undefined,\n target: Expression | undefined,\n): number {\n if (!source || !target || source.constructor !== target.constructor) {\n return 0;\n }\n\n return 1 + parentSimilarityScore(source.parent, target.parent);\n}\n\n/**\n * Yields only child expressions, filtering out ignored leaf types (like Identifiers)\n */\nexport function* expressionOnlyArgs (expression: Expression): Generator<Expression> {\n for (const arg of expression.iterExpressions()) {\n if (!IGNORED_LEAF_EXPRESSION_TYPES.some((type) => arg instanceof type)) {\n yield arg;\n }\n }\n}\n\n/**\n * Calculates the longest common subsequence between two sequences.\n * * This is used to detect \"Move\" edits by determining which nodes\n * maintained their relative order\n */\nexport function lcs<T> (\n _seqA: Iterable<T>,\n _seqB: Iterable<T>,\n equal: (a: T, b: T) => boolean,\n): T[] {\n const seqA = [..._seqA];\n const seqB = [..._seqB];\n const lenA = seqA.length;\n const lenB = seqB.length;\n\n // Initialize a 2D array for DP\n const lcsResult: T[][][] = Array.from({\n length: lenA + 1,\n }, () =>\n Array.from({\n length: lenB + 1,\n }, () => []));\n\n for (let i = 1; i <= lenA; i++) {\n for (let j = 1; j <= lenB; j++) {\n if (equal(seqA[i - 1], seqB[j - 1])) {\n // If equal, take the diagonal result and add current element\n lcsResult[i][j] = [\n ...lcsResult[i - 1][j - 1],\n seqA[i - 1],\n ];\n } else {\n // Otherwise, take the maximum of top or left\n const top = lcsResult[i - 1][j];\n const left = lcsResult[i][j - 1];\n\n lcsResult[i][j] = left.length < top.length ? top : left;\n }\n }\n }\n\n return lcsResult[lenA][lenB];\n}\n","import type {\n Expression, QueryExpr,\n} from './expressions';\nimport {\n TableExpr, TagExpr,\n SelectExpr,\n StarExpr,\n SubqueryExpr,\n SetOperationExpr,\n ColumnExpr,\n UdtfExpr,\n PlaceholderExpr,\n UNWRAPPED_QUERIES,\n maybeParse,\n expand,\n} from './expressions';\nimport {\n SqlglotError,\n} from './errors';\nimport {\n normalizeIdentifiers,\n} from './optimizer/normalize_identifiers';\nimport {\n qualify,\n} from './optimizer/qualify';\nimport {\n buildScope,\n Scope, ScopeType, findAllInScope,\n} from './optimizer/scope';\nimport type {\n DialectType,\n} from './dialects/dialect';\nimport type {\n Schema,\n} from './schema';\nimport {\n id,\n} from './port_internals';\n\nexport interface NodeOptions {\n name: string;\n expression: Expression;\n source: Expression;\n downstream?: Node[];\n sourceName?: string;\n referenceNodeName?: string;\n}\n\nexport class Node {\n public name: string;\n public expression: Expression;\n public source: Expression;\n public downstream: Node[];\n public sourceName: string;\n public referenceNodeName: string;\n\n constructor (options: NodeOptions) {\n this.name = options.name;\n this.expression = options.expression;\n this.source = options.source;\n this.downstream = options.downstream || [];\n this.sourceName = options.sourceName || '';\n this.referenceNodeName = options.referenceNodeName || '';\n }\n\n * walk (): Generator<Node> {\n yield this;\n for (const d of this.downstream) {\n yield* d.walk();\n }\n }\n\n toHtml (dialect?: DialectType, opts: Record<string, unknown> = {}): GraphHTML {\n const nodes: Record<string, unknown> = {};\n const edges: unknown[] = [];\n\n for (const node of this.walk()) {\n let label: string;\n let title: string;\n let group: number;\n\n if (node.expression instanceof TableExpr) {\n label = `FROM ${node.expression.args.this}`;\n title = `<pre>SELECT ${node.name} FROM ${node.expression.args.this}</pre>`;\n group = 1;\n } else {\n label = node.expression.sql({\n pretty: true,\n dialect,\n });\n\n const sourceSql = node.source.transform((n: Expression) => {\n return n === node.expression\n ? new TagExpr({\n this: n,\n prefix: '<b>',\n postfix: '</b>',\n })\n : n;\n }, {\n copy: false,\n }).sql({\n pretty: true,\n dialect,\n });\n\n title = `<pre>${sourceSql}</pre>`;\n group = 0;\n }\n\n const nodeId = id(node);\n\n nodes[nodeId] = {\n id: nodeId,\n label,\n title,\n group,\n };\n\n for (const d of node.downstream) {\n edges.push({\n from: nodeId,\n to: id(d),\n });\n }\n }\n\n return new GraphHTML(nodes, edges, opts);\n }\n}\n\nexport interface LineageOptions {\n schema?: Record<string, unknown> | Schema;\n sources?: Record<string, string | QueryExpr>;\n dialect?: DialectType;\n scope?: Scope;\n trimSelects?: boolean;\n copy?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Build the lineage graph for a column of a SQL query.\n *\n * @param column The column to build the lineage for.\n * @param sql The SQL string or expression.\n * @param options Additional options like schema, dialect, scope, etc.\n * @returns A lineage node\n */\nexport function lineage (\n column: string | ColumnExpr,\n sql: string | Expression,\n options: LineageOptions = {},\n): Node {\n const {\n schema,\n sources,\n dialect,\n scope: providedScope,\n trimSelects = true,\n copy = true,\n ...kwargs\n } = options;\n\n let expression = maybeParse(sql, {\n copy,\n dialect,\n });\n const normalizedColumn = normalizeIdentifiers(column, {\n dialect,\n }).name;\n\n if (sources) {\n const parsedSources: Record<string, QueryExpr> = {};\n\n for (const [\n k,\n v,\n ] of Object.entries(sources)) {\n parsedSources[k] = maybeParse(v, {\n copy,\n dialect,\n }) as QueryExpr;\n }\n\n expression = expand(expression, parsedSources, {\n dialect,\n copy,\n });\n }\n\n let scope = providedScope;\n\n if (!scope) {\n expression = qualify(expression, {\n dialect,\n schema,\n validateQualifyColumns: false,\n identify: false,\n ...kwargs,\n });\n\n scope = buildScope(expression);\n }\n\n if (!scope) {\n throw new SqlglotError('Cannot build lineage, sql must be SELECT');\n }\n\n // Assuming scope.expression is a Select expression containing `selects`\n const hasColumn = scope.expression.selects.some(\n (select) => select.aliasOrName === normalizedColumn,\n );\n\n if (!hasColumn) {\n throw new SqlglotError(`Cannot find column '${normalizedColumn}' in query.`);\n }\n\n return toNode(normalizedColumn, scope, dialect, {\n trimSelects,\n });\n}\n\nexport interface ToNodeOptions {\n scopeName?: string;\n upstream?: Node;\n sourceName?: string;\n referenceNodeName?: string;\n trimSelects?: boolean;\n}\n\nexport function toNode (\n column: string | number,\n scope: Scope,\n dialect: DialectType | undefined,\n options: ToNodeOptions = {},\n): Node {\n let {\n\n scopeName = undefined,\n upstream = undefined,\n\n sourceName = undefined,\n\n referenceNodeName = undefined,\n\n trimSelects = true,\n } = options;\n\n // Find the specific select clause that is the source of the column we want\n // This can either be a specific, named select or a generic `*` clause\n let select: Expression;\n\n if (typeof column === 'number') {\n if (scope.expression.selects.length <= column) {\n throw new SqlglotError(\n `Cannot find column's source with index ${column} in query: ${scope.expression.sql({\n dialect,\n })}`,\n );\n }\n\n select = scope.expression.selects[column];\n } else {\n const foundSelect = scope.expression.selects.find(\n (s) => s.aliasOrName === column,\n );\n\n select = foundSelect || (scope.expression.isStar ? new StarExpr({}) : scope.expression);\n }\n\n if (scope.expression instanceof SubqueryExpr) {\n for (const source of scope.subqueryScopes) {\n return toNode(column, source, dialect, {\n upstream,\n sourceName,\n referenceNodeName,\n trimSelects,\n });\n }\n }\n\n if (scope.expression instanceof SetOperationExpr) {\n const name = scope.expression.constructor.name.toUpperCase().replace('EXPR', '');\n\n upstream = upstream || new Node({\n name,\n source: scope.expression,\n expression: select,\n });\n\n let index: number;\n\n if (typeof column === 'number') {\n index = column;\n } else {\n index = scope.expression.selects.findIndex(\n (s) => s.aliasOrName === column || s.isStar,\n );\n }\n\n if (index === -1) {\n throw new Error(`Could not find ${column} in ${scope.expression}`);\n }\n\n for (const s of scope.unionScopes) {\n toNode(index, s, dialect, {\n upstream,\n sourceName,\n referenceNodeName,\n trimSelects,\n });\n }\n\n return upstream;\n }\n\n let source: Expression;\n\n if (trimSelects && scope.expression instanceof SelectExpr) {\n // For better ergonomics in our node labels, replace the full select with\n // a version that has only the column we care about\n source = scope.expression.select(select, {\n append: false,\n }) as Expression;\n } else {\n source = scope.expression;\n }\n\n // Create the node for this step in the lineage chain, and attach it to the previous one\n const node = new Node({\n name: scopeName ? `${scopeName}.${column}` : String(column),\n source,\n expression: select,\n sourceName: sourceName || '',\n referenceNodeName: referenceNodeName || '',\n });\n\n if (upstream) {\n upstream.downstream.push(node);\n }\n\n const subqueryScopes = new WeakMap<Expression, Scope>();\n\n for (const subqueryScope of scope.subqueryScopes) {\n subqueryScopes.set(subqueryScope.expression, subqueryScope);\n }\n\n for (const subquery of findAllInScope<QueryExpr>(select, UNWRAPPED_QUERIES)) {\n const subqueryScope = subqueryScopes.get(subquery);\n\n if (!subqueryScope) {\n console.warn(`Unknown subquery scope: ${subquery.sql({\n dialect,\n })}`);\n continue;\n }\n\n for (const name of subquery.namedSelects || []) {\n toNode(name, subqueryScope, dialect, {\n upstream: node,\n trimSelects,\n });\n }\n }\n\n // if the select is a star add all scope sources as downstreams\n if (select instanceof StarExpr) {\n for (const sourceVal of Array.from(scope.sources.values())) {\n let sourceExpr;\n\n if (sourceVal instanceof Scope) {\n sourceExpr = sourceVal.expression;\n } else {\n sourceExpr = sourceVal;\n }\n node.downstream.push(\n new Node({\n name: select.sql({\n comments: false,\n }),\n source: sourceExpr,\n expression: sourceExpr,\n }),\n );\n }\n }\n\n // Find all columns that went into creating this one to list their lineage nodes\n const sourceColumnsSet = new Set<ColumnExpr>(\n findAllInScope(select, [ColumnExpr]),\n );\n\n let derivedTables: Expression[];\n\n // If the source is a Udtf find columns used in the Udtf to generate the table\n if (source instanceof UdtfExpr) {\n const udtfCols = source.findAll(ColumnExpr);\n\n for (const c of udtfCols) sourceColumnsSet.add(c);\n\n derivedTables = Array.from(scope.sources.values())\n .filter((s): s is Scope => s instanceof Scope && s.isDerivedTable)\n .map((s) => s.expression.parent)\n .filter((p): p is Expression => p !== undefined);\n } else {\n derivedTables = scope.derivedTables;\n }\n\n const sourceNames = new Map<string, string>();\n\n for (const dt of derivedTables) {\n if (dt.comments && dt.comments[0]?.startsWith('source: ')) {\n sourceNames.set(dt.alias, dt.comments[0].split(' ')[1]);\n }\n }\n\n const pivots = scope.pivots;\n const pivot = pivots.length === 1 && !pivots[0].unpivot ? pivots[0] : undefined;\n const pivotColumnMapping = new Map<string, ColumnExpr[]>();\n\n if (pivot) {\n const pivotColumns = pivot.args.columns ?? [];\n const pivotAggsCount = pivot.args.expressions?.length ?? 0;\n\n pivot.args.expressions?.forEach((agg, i: number) => {\n const aggCols = Array.from(agg.findAll(ColumnExpr)) as ColumnExpr[];\n\n for (let colIndex = i; colIndex < (pivotColumns?.length || 0); colIndex += pivotAggsCount) {\n pivotColumnMapping.set(pivotColumns[colIndex].name, aggCols);\n }\n });\n }\n\n for (const c of Array.from(sourceColumnsSet)) {\n const table = c.table;\n let sourceScopeOrExpr: Expression | Scope | undefined = scope.sources.get(table);\n\n if (sourceScopeOrExpr instanceof Scope) {\n let refNodeName: string | undefined = undefined;\n\n if (sourceScopeOrExpr.scopeType === ScopeType.DERIVED_TABLE && !sourceNames.has(table)) {\n refNodeName = table;\n } else if (sourceScopeOrExpr.scopeType === ScopeType.CTE) {\n const selectedNode = scope.selectedSources[table]?.[0];\n\n refNodeName = selectedNode ? selectedNode.name : undefined;\n }\n\n toNode(c.name, sourceScopeOrExpr, dialect, {\n scopeName: table,\n upstream: node,\n sourceName: sourceNames.get(table) || sourceName,\n referenceNodeName: refNodeName,\n trimSelects,\n });\n } else if (pivot && pivot.aliasOrName === c.table) {\n const downstreamColumns: ColumnExpr[] = [];\n const columnName = c.name;\n\n if (pivot.args.columns?.some((pc) => pc.name === columnName)) {\n downstreamColumns.push(...(pivotColumnMapping.get(columnName) || []));\n } else {\n // Adapt column to be from the implicit pivoted source\n downstreamColumns.push(new ColumnExpr({\n this: c.args.this,\n table: pivot.parent?.aliasOrName,\n }));\n }\n\n for (const downstreamColumn of downstreamColumns) {\n const dsTable = downstreamColumn.table;\n let dsSource: Expression | Scope | undefined = scope.sources.get(dsTable);\n\n if (dsSource instanceof Scope) {\n toNode(downstreamColumn.name, dsSource, dialect, {\n scopeName: dsTable,\n upstream: node,\n sourceName: sourceNames.get(dsTable) || sourceName,\n referenceNodeName,\n trimSelects,\n });\n } else {\n dsSource = dsSource || new PlaceholderExpr({});\n node.downstream.push(\n new Node({\n name: downstreamColumn.sql({\n comments: false,\n }),\n source: dsSource,\n expression: dsSource,\n }),\n );\n }\n }\n } else {\n sourceScopeOrExpr = sourceScopeOrExpr || new PlaceholderExpr({});\n node.downstream.push(\n new Node({\n name: c.sql({\n comments: false,\n }),\n source: sourceScopeOrExpr,\n expression: sourceScopeOrExpr,\n }),\n );\n }\n }\n\n return node;\n}\n\n/**\n * Node to HTML generator using vis.js.\n *\n * https://visjs.github.io/vis-network/docs/network/\n */\nexport class GraphHTML {\n public imports: boolean;\n public options: Record<string, unknown>;\n public nodes: Record<string, unknown>;\n public edges: unknown[];\n\n constructor (\n nodes: Record<string, unknown>,\n edges: unknown[],\n options: {\n imports?: boolean;\n [index: string]: unknown;\n } = {},\n ) {\n const {\n imports = true,\n } = options;\n\n this.imports = imports;\n this.nodes = nodes;\n this.edges = edges;\n\n this.options = {\n height: '500px',\n width: '100%',\n layout: {\n hierarchical: {\n enabled: true,\n nodeSpacing: 200,\n sortMethod: 'directed',\n },\n },\n interaction: {\n dragNodes: false,\n selectable: false,\n },\n physics: {\n enabled: false,\n },\n edges: {\n arrows: 'to',\n },\n nodes: {\n font: '20px monaco',\n shape: 'box',\n widthConstraint: {\n maximum: 300,\n },\n },\n ...(options || {}),\n };\n }\n\n toString (): string {\n const nodesJson = JSON.stringify(Object.values(this.nodes));\n const edgesJson = JSON.stringify(this.edges);\n const optionsJson = JSON.stringify(this.options);\n\n const importsHtml = this.imports\n ? `<script type=\"text/javascript\" src=\"https://unpkg.com/vis-data@latest/peer/umd/vis-data.min.js\"></script>\n <script type=\"text/javascript\" src=\"https://unpkg.com/vis-network@latest/peer/umd/vis-network.min.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://unpkg.com/vis-network/styles/vis-network.min.css\" />`\n : '';\n\n return `<div>\n <div id=\"sqlglot-lineage\"></div>\n ${importsHtml}\n <script type=\"text/javascript\">\n var nodes = new vis.DataSet(${nodesJson});\n nodes.forEach(row => {\n row[\"title\"] = new DOMParser().parseFromString(row[\"title\"], \"text/html\").body.childNodes[0];\n });\n\n new vis.Network(\n document.getElementById(\"sqlglot-lineage\"),\n {\n nodes: nodes,\n edges: new vis.DataSet(${edgesJson})\n },\n ${optionsJson}\n );\n </script>\n</div>`;\n }\n\n toHtml (): string {\n return this.toString();\n }\n}\n","import type {\n ExpressionOrString,\n} from './expressions';\nimport {\n Expression,\n WithExpr,\n SelectExpr, SetOperationExpr, AggFuncExpr,\n ColumnExpr, IdentifierExpr,\n SubqueryExpr,\n column,\n alias,\n JoinExpr,\n} from './expressions';\nimport {\n nameSequence,\n} from './helper';\nimport {\n assertIsInstanceOf, filterInstanceOf, id, isInstanceOf,\n} from './port_internals';\nimport {\n joinCondition,\n} from './optimizer';\n\n/**\n * Represents a query execution plan as a Directed Acyclic Graph (DAG) of Steps\n */\nexport class Plan {\n public expression: Expression;\n public root: Step | undefined;\n private _dag: Map<Step, Set<Step>> | undefined = undefined;\n\n constructor (expression: Expression) {\n // Ensuring we work on a copy to prevent mutation of the original AST\n this.expression = expression.copy();\n this.root = Step.fromExpression(this.expression);\n }\n\n /**\n * Generates or retrieves the DAG of steps\n */\n get dag (): Map<Step, Set<Step>> {\n if (this._dag) {\n return this._dag;\n }\n\n const dag = new Map<Step, Set<Step>>();\n const seen = new Set<Step>();\n\n const stack = [this.root];\n\n while (0 < stack.length) {\n const node = stack.pop()!;\n\n if (seen.has(node)) continue;\n\n seen.add(node);\n const dependencies = new Set<Step>();\n\n for (const dep of node.dependencies) {\n dependencies.add(dep);\n stack.push(dep);\n }\n\n dag.set(node, dependencies);\n }\n\n this._dag = dag;\n\n return this._dag;\n }\n\n /**\n * Returns an iterator over the leaf nodes (steps with no dependencies)\n */\n get leaves (): IterableIterator<Step> {\n const leafNodes: Step[] = [];\n\n for (const [\n node,\n deps,\n ] of this.dag.entries()) {\n if (deps.size === 0) {\n leafNodes.push(node);\n }\n }\n\n return leafNodes[Symbol.iterator]();\n }\n\n toString (): string {\n return `Plan\\n----\\n${this.root?.toString() ?? 'unnamed'}`;\n }\n}\n\n/**\n * Base class for an execution step in the query plan DAG\n */\nexport class Step {\n public name: string = '';\n public dependencies: Set<Step> = new Set();\n public dependents: Set<Step> = new Set();\n public projections: Expression[] = [];\n public limit: number = Infinity;\n public condition: Expression | undefined = undefined;\n\n // Intermediate state for builders\n public operands: Expression[] = [];\n public aggregations: Expression[] = [];\n\n static fromExpression (\n expression?: Expression,\n ctes: Map<string, Step> = new Map(),\n ): Step | undefined {\n if (!expression) return undefined;\n const unnested = expression.unnest();\n const with_ = unnested.getArgKey('with');\n\n // Handle CTEs\n if (isInstanceOf(with_, WithExpr)) {\n ctes = new Map(ctes);\n for (const cte of with_.args.expressions || []) {\n assertIsInstanceOf(cte.args.this, Expression);\n const step = Step.fromExpression(cte.args.this, ctes);\n\n if (step) {\n step.name = cte.alias;\n ctes.set(step.name, step);\n }\n }\n }\n\n const from = unnested.args.from;\n let step: Step | undefined;\n\n if (unnested instanceof SelectExpr && from instanceof Expression) {\n assertIsInstanceOf(from.args.this, Expression);\n step = Scan.fromExpression(from.args.this, ctes);\n } else if (unnested instanceof SetOperationExpr) {\n step = SetOperation.fromExpression(unnested, ctes);\n } else {\n step = new Scan();\n }\n\n const joins = filterInstanceOf(unnested.args.joins || [], JoinExpr);\n\n if (joins && 0 < joins.length) {\n const joinStep = Join.fromJoins(joins, ctes);\n\n if (step) {\n joinStep.name = step.name;\n joinStep.sourceName = step.name;\n joinStep.addDependency(step);\n }\n step = joinStep;\n }\n\n const projections: Expression[] = [];\n const operands = new Map<Expression, string>();\n const aggregations = new Map<Expression, undefined>();\n const nextOperandName = nameSequence('_a_');\n\n const extractAggOperands = (expr: Expression): boolean => {\n const aggFuncs = Array.from(expr.findAll(AggFuncExpr));\n\n if (0 < aggFuncs.length) {\n aggregations.set(expr, undefined);\n }\n\n for (const agg of aggFuncs) {\n for (const operand of agg.unnestOperands()) {\n if (operand instanceof ColumnExpr) continue;\n if (!operands.has(operand)) {\n operands.set(operand, nextOperandName());\n }\n operand.replace(new ColumnExpr({\n this: new IdentifierExpr({\n this: operands.get(operand),\n quoted: true,\n }),\n }));\n }\n }\n\n return 0 < aggFuncs.length;\n };\n\n const setOpsAndAggs = (target: Step) => {\n target.operands = Array.from(operands.entries()).map(\n ([\n expr,\n aliasExpr,\n ]) => alias(\n expr,\n aliasExpr,\n ),\n );\n target.aggregations = Array.from(aggregations.keys());\n };\n\n for (const e of unnested.args.expressions || []) {\n assertIsInstanceOf(e, Expression);\n if (e.find(AggFuncExpr)) {\n projections.push(column(\n {\n col: e.aliasOrName,\n table: step?.name,\n },\n {\n quoted: true,\n },\n ));\n extractAggOperands(e);\n } else {\n projections.push(e);\n }\n }\n\n const where = unnested.getArgKey('where');\n\n if (step && where instanceof Expression && where.args.this instanceof Expression) {\n step.condition = where.args.this;\n }\n\n const group = unnested.getArgKey('group');\n\n if (group || 0 < aggregations.size) {\n const aggregate = new Aggregate();\n\n if (step) {\n aggregate.source = step.name;\n aggregate.name = step.name;\n }\n\n const having = unnested.getArgKey('having');\n\n if (having instanceof Expression && isInstanceOf(having.args.this, 'string', Expression)) {\n if (extractAggOperands(alias(\n having.args.this,\n '_h',\n {\n quoted: true,\n },\n ))) {\n aggregate.condition = column(\n {\n col: '_h',\n table: step?.name,\n },\n {\n quoted: true,\n },\n );\n } else if (isInstanceOf(having.args.this, Expression)) {\n aggregate.condition = having.args.this;\n }\n }\n\n setOpsAndAggs(aggregate);\n\n const groupExprs = isInstanceOf(group, Expression)\n ? filterInstanceOf(group.args.expressions ?? [], Expression)\n : [];\n\n aggregate.group = Object.fromEntries(\n groupExprs.map((e, i) => [\n `_g${i}`,\n e,\n ]),\n );\n\n const intermediate = new Map<string, string>();\n\n Object.entries(aggregate.group).forEach(([\n k,\n v,\n ]) => {\n intermediate.set(v.sql(), k);\n if (v instanceof ColumnExpr) {\n intermediate.set(v.name, k);\n }\n });\n\n const lookupNode = (node: Expression): string | undefined =>\n intermediate.get(node.sql()) ?? (node instanceof ColumnExpr ? intermediate.get(node.name) : undefined);\n\n // Replace projections with group references\n for (const projection of projections) {\n for (const node of projection.walk()) {\n const name = lookupNode(node);\n\n if (name) {\n node.replace(column({\n col: name,\n table: step?.name,\n }, {\n quoted: true,\n }));\n }\n }\n }\n\n // Replace group references in the HAVING condition (non-aggregate)\n if (aggregate.condition) {\n for (const node of aggregate.condition.walk()) {\n const name = lookupNode(node);\n\n if (name) {\n node.replace(column({\n col: name,\n table: step?.name,\n }, {\n quoted: true,\n }));\n }\n }\n }\n\n aggregate.addDependency(step);\n step = aggregate;\n }\n\n const order = unnested.getArgKey('order');\n\n if (isInstanceOf(order, Expression)) {\n // If we have an aggregate step, extract any agg funcs in ORDER BY into operands\n if (step instanceof Aggregate) {\n const orderExprs = filterInstanceOf(order.args.expressions || [], Expression);\n\n for (let i = 0; i < orderExprs.length; i++) {\n const ordered = orderExprs[i];\n const orderThis = (ordered.args as Record<string, Expression | undefined>).this;\n\n if (orderThis && extractAggOperands(alias(orderThis, `_o_${i}`, {\n quoted: true,\n }))) {\n orderThis.replace(column({\n col: `_o_${i}`,\n table: step.name,\n }, {\n quoted: true,\n }));\n }\n }\n setOpsAndAggs(step);\n }\n\n const sort = new Sort();\n\n sort.name = step?.name ?? '';\n sort.key = filterInstanceOf(order.args.expressions || [], Expression);\n sort.addDependency(step);\n step = sort;\n }\n\n if (step) step.projections = projections;\n\n if (unnested instanceof SelectExpr && unnested.args.distinct) {\n const distinct = new Aggregate();\n\n distinct.source = step?.name;\n distinct.name = step?.name ?? '';\n distinct.group = Object.fromEntries(\n (projections.length\n ? projections\n : filterInstanceOf(unnested.args.expressions || [], Expression))\n .map((e) => [\n e.aliasOrName,\n column({\n col: e.aliasOrName,\n table: step?.name,\n }, {\n quoted: true,\n }),\n ]),\n );\n distinct.addDependency(step);\n step = distinct;\n }\n\n const limit = unnested.getArgKey('limit');\n\n if (step && isInstanceOf(limit, Expression)) {\n step.limit = parseInt(limit.text('expression'));\n }\n\n return step;\n }\n\n addDependency (dependency?: Step): void {\n if (!dependency) return;\n this.dependencies.add(dependency);\n dependency.dependents.add(this);\n }\n\n /**\n * Returns a string representation of the execution step\n */\n toString (): string {\n return this.toS();\n }\n\n /**\n * Recursive helper to build the formatted string tree.\n * @param level Indentation depth\n */\n toS (level: number = 0): string {\n const indent = ' '.repeat(level);\n const nested = `${indent} `;\n\n // Each subclass (Scan, Join, Aggregate) can provide specific context lines\n let context = this._toS(`${nested} `);\n\n if (0 < context.length) {\n context = [\n `${nested}Context:`,\n ...context,\n ];\n }\n\n const lines: string[] = [\n `${indent}- ${this.id}`,\n ...context,\n `${nested}Projections:`,\n ];\n\n for (const expression of this.projections) {\n lines.push(`${nested} - ${expression.sql()}`);\n }\n\n if (this.condition) {\n lines.push(`${nested}Condition: ${this.condition.sql()}`);\n }\n\n if (this.limit !== Infinity) {\n lines.push(`${nested}Limit: ${this.limit}`);\n }\n\n if (0 < this.dependencies.size) {\n lines.push(`${nested}Dependencies:`);\n for (const dependency of this.dependencies) {\n // Recursively call toS for each dependency with increased level\n lines.push(` ${dependency.toS(level + 1)}`);\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Property-like getter for the class name\n */\n get typeName (): string {\n return this.constructor.name;\n }\n\n /**\n * Unique identifier for the step in the output\n */\n get id (): string {\n const nameStr = this.name ? ` ${this.name}` : '';\n\n return `${this.typeName}:${nameStr} (${id(this)})`;\n }\n\n /**\n * Hook for subclasses to add extra descriptive lines (like Join conditions or Source tables)\n */\n _toS (_indent: string): string[] {\n return [];\n }\n}\n\n/**\n * Represents a leaf-level operation that reads from a table, subquery, or CTE\n */\nexport class Scan extends Step {\n public source: ExpressionOrString | undefined = undefined;\n\n static fromExpression (\n expression: Expression,\n ctes: Map<string, Step> = new Map(),\n ): Step | undefined {\n const table = expression;\n const alias = expression.aliasOrName;\n\n if (expression instanceof SubqueryExpr) {\n const innerTable = expression.args.this;\n const step = innerTable !== undefined ? Step.fromExpression(innerTable, ctes) : undefined;\n\n if (step) step.name = alias;\n\n return step;\n }\n\n const step = new Scan();\n\n step.name = alias;\n step.source = expression;\n\n // If the table name matches a CTE, we add that CTE's step as a dependency\n const tableName = table.name;\n\n if (ctes.has(tableName)) {\n step.addDependency(ctes.get(tableName));\n }\n\n return step;\n }\n\n override _toS (indent: string): string[] {\n const source = this.source instanceof Expression ? this.source.sql() : this.source ?? '-static-';\n\n return [`${indent}Source: ${source}`];\n }\n}\n\n/**\n * Represents a join operation between a source step and one or more join targets\n */\nexport class Join extends Step {\n public sourceName: string | undefined = undefined;\n public joins: Record<string, {\n side: string | undefined;\n joinKey: unknown[];\n sourceKey: unknown[];\n condition: Expression | undefined;\n }> = {};\n\n static fromJoins (\n joins: Iterable<JoinExpr>,\n ctes: Map<string, Step> = new Map(),\n ): Join {\n const step = new Join();\n\n for (const join of joins) {\n const {\n sourceKeys, joinKeys, on,\n } = joinCondition(join);\n\n step.joins[join.aliasOrName] = {\n side: join.side,\n joinKey: joinKeys || [],\n sourceKey: sourceKeys || [],\n condition: on || undefined,\n };\n\n // Each join target becomes a new dependency branch via a Scan\n if (join.args.this !== undefined) step.addDependency(Scan.fromExpression(join.args.this, ctes));\n }\n\n return step;\n }\n\n override _toS (indent: string): string[] {\n const lines = [`${indent}Source: ${this.sourceName || this.name}`];\n\n for (const [\n name,\n join,\n ] of Object.entries(this.joins)) {\n lines.push(`${indent}${name}: ${join.side || 'INNER'}`);\n\n const joinKeyStr = join.joinKey.map((key) => String(key)).join(', ');\n\n if (joinKeyStr) {\n lines.push(`${indent}Key: ${joinKeyStr}`);\n }\n\n if (join.condition) {\n lines.push(`${indent}On: ${join.condition.sql()}`);\n }\n }\n\n return lines;\n }\n}\n\n/**\n * Represents an aggregation step (GROUP BY / HAVING)\n */\nexport class Aggregate extends Step {\n public aggregations: Expression[] = [];\n public operands: Expression[] = [];\n public group: Record<string, Expression> = {};\n public source: ExpressionOrString | undefined = undefined;\n\n constructor () {\n super();\n }\n\n override _toS (indent: string): string[] {\n const lines: string[] = [`${indent}Aggregations:`];\n\n for (const expression of this.aggregations) {\n lines.push(`${indent} - ${expression.sql()}`);\n }\n\n if (0 < Object.keys(this.group).length) {\n lines.push(`${indent}Group:`);\n for (const expression of Object.values(this.group)) {\n lines.push(`${indent} - ${expression.sql()}`);\n }\n }\n\n if (this.condition) {\n lines.push(`${indent}Having:`);\n lines.push(`${indent} - ${this.condition.sql()}`);\n }\n\n if (0 < this.operands.length) {\n lines.push(`${indent}Operands:`);\n for (const expression of this.operands) {\n lines.push(`${indent} - ${expression.sql()}`);\n }\n }\n\n return lines;\n }\n}\n\n/**\n * Represents an ordering step (ORDER BY)\n */\nexport class Sort extends Step {\n public key: Expression[] = [];\n\n constructor () {\n super();\n }\n\n override _toS (indent: string): string[] {\n const lines: string[] = [`${indent}Key:`];\n\n for (const expression of this.key) {\n lines.push(`${indent} - ${expression.sql()}`);\n }\n\n return lines;\n }\n}\n\n/**\n * Represents set operations like UNION, INTERSECT, and EXCEPT\n */\nexport class SetOperation extends Step {\n public op: typeof SetOperationExpr; // Constructor for the specific SetOperation type\n public left: string | undefined;\n public right: string | undefined;\n public distinct: boolean;\n\n constructor (\n op: typeof SetOperationExpr,\n left: string | undefined,\n right: string | undefined,\n options: {\n distinct?: boolean;\n } = {},\n ) {\n const {\n distinct = false,\n } = options;\n\n super();\n this.op = op;\n this.left = left;\n this.right = right;\n this.distinct = distinct;\n }\n\n static fromExpression (\n expression?: SetOperationExpr,\n ctes: Map<string, Step> = new Map(),\n ): SetOperation | undefined {\n if (!(expression instanceof SetOperationExpr)) {\n throw new Error('Expected SetOperation expression');\n }\n\n const left = expression.args.this !== undefined ? Step.fromExpression(expression.args.this, ctes) : undefined;\n\n if (left) left.name = left.name || 'left';\n\n const right = expression.args.expression !== undefined ? Step.fromExpression(expression.args.expression, ctes) : undefined;\n\n if (right) right.name = right.name || 'right';\n\n const step = new SetOperation(\n expression._constructor as typeof SetOperationExpr,\n left?.name,\n right?.name,\n {\n distinct: Boolean(expression.args.distinct),\n },\n );\n\n if (left) step.addDependency(left);\n if (right) step.addDependency(right);\n\n const limit = expression.args.limit;\n\n if (isInstanceOf(limit, Expression)) {\n step.limit = parseInt(limit.text('expression'));\n }\n\n return step;\n }\n\n override _toS (indent: string): string[] {\n const lines: string[] = [];\n\n if (this.distinct) {\n lines.push(`${indent}Distinct: ${this.distinct}`);\n }\n\n return lines;\n }\n\n get typeName (): string {\n return this.op.name;\n }\n}\n","import type {\n DialectType,\n} from '../dialects/dialect';\nimport {\n objectDepth,\n} from '../helper';\nimport {\n MappingSchema, normalizeName,\n} from '../schema';\n\nexport class Table {\n public columns: string[];\n public columnRange?: ColumnRange;\n public reader: RowReader;\n public rows: unknown[][];\n public rangeReader: RangeReader;\n\n constructor (\n columns: Iterable<string>,\n rows: unknown[][] = [],\n columnRange?: ColumnRange,\n ) {\n this.columns = Array.from(columns);\n this.columnRange = columnRange;\n this.reader = new RowReader(this.columns, this.columnRange);\n this.rows = rows;\n\n if (0 < this.rows.length) {\n if (this.rows[0].length !== this.columns.length) {\n throw new Error('Row length does not match column length.');\n }\n }\n\n this.rangeReader = new RangeReader(this);\n }\n\n addColumns (...columns: string[]): void {\n this.columns.push(...columns);\n if (this.columnRange) {\n this.columnRange = {\n start: this.columnRange.start,\n stop: this.columnRange.stop + columns.length,\n };\n }\n this.reader = new RowReader(this.columns, this.columnRange);\n }\n\n append (row: unknown[]): void {\n if (row.length !== this.columns.length) {\n throw new Error('Row length does not match column length.');\n }\n this.rows.push(row);\n }\n\n pop (): void {\n this.rows.pop();\n }\n\n toJslist (): Record<string, unknown>[] {\n return this.rows.map((row) => {\n const obj: Record<string, unknown> = {};\n\n this.columns.forEach((col, i) => {\n obj[col] = row[i];\n });\n\n return obj;\n });\n }\n\n get width (): number {\n return this.columns.length;\n }\n\n get length (): number {\n return this.rows.length;\n }\n\n * [Symbol.iterator] (): Generator<RowReader> {\n for (let i = 0; i < this.rows.length; i++) {\n yield this.get(i);\n }\n }\n\n get (index: number): RowReader {\n this.reader.row = this.rows[index];\n\n return this.reader;\n }\n\n toString (): string {\n const cols = this.columns.filter(\n (_, i) => !this.columnRange || (this.columnRange.start <= i && i < this.columnRange.stop),\n );\n\n const widths: Record<string, number> = {};\n\n cols.forEach((col) => {\n widths[col] = col.length;\n });\n\n const lines = [cols.join(' ')];\n\n for (let i = 0; i < this.length; i++) {\n if (10 < i) break;\n\n const reader = this.get(i);\n const rowStr = cols\n .map((col) => {\n const valStr = String(reader.row[reader.columns[col]] ?? '');\n\n return valStr.padStart(widths[col], ' ').substring(0, widths[col]);\n })\n .join(' ');\n\n lines.push(rowStr);\n }\n\n return lines.join('\\n');\n }\n}\n\nexport class TableIter implements Iterator<RowReader> {\n public table: Table;\n public index: number = -1;\n\n constructor (table: Table) {\n this.table = table;\n }\n\n [Symbol.iterator] () {\n return this;\n }\n\n next (): IteratorResult<RowReader> {\n this.index++;\n if (this.index < this.table.length) {\n return {\n value: this.table.get(this.index),\n done: false,\n };\n }\n\n return {\n value: undefined,\n done: true,\n };\n }\n}\n\nexport class Tables extends MappingSchema {\n override depth (): number {\n return objectDepth(this.mapping);\n }\n}\n\nexport function ensureTables (d?: Record<string, unknown>, dialect?: DialectType): Tables {\n return new Tables(_ensureTables(d, dialect), {\n normalize: false,\n dialect,\n });\n}\n\nfunction _ensureTables (d?: unknown, dialect?: DialectType): Record<string, unknown> {\n if (typeof d !== 'object' || !d || Object.keys(d).length === 0) {\n return {};\n }\n\n const depth = objectDepth(d);\n\n if (1 < depth) {\n const nestedResult: Record<string, unknown> = {};\n\n for (const [\n k,\n v,\n ] of Object.entries(d)) {\n const normalizedName = normalizeName(k, {\n dialect,\n isTable: true,\n }).name;\n\n nestedResult[normalizedName] = _ensureTables(v, dialect);\n }\n\n return nestedResult;\n }\n\n const result: Record<string, unknown> = {};\n\n for (const [\n rawTableName,\n tableData,\n ] of Object.entries(d)) {\n const tableName = normalizeName(rawTableName, {\n dialect,\n }).name;\n\n if (tableData instanceof Table) {\n result[tableName] = tableData;\n } else {\n // Normalize raw object arrays into Table structures\n const normalizedTableData = tableData.map((row: Record<string, unknown>) => {\n const newRow: Record<string, unknown> = {};\n\n for (const [\n columnName,\n value,\n ] of Object.entries(row)) {\n newRow[normalizeName(columnName, {\n dialect,\n }).name] = value;\n }\n\n return newRow;\n });\n\n const columnNames = 0 < normalizedTableData.length\n ? Object.keys(normalizedTableData[0])\n : [];\n const rows = normalizedTableData.map((row: Record<string, unknown>) => columnNames.map((name) => row[name]));\n\n result[tableName] = new Table(columnNames, rows);\n }\n }\n\n return result;\n}\n\nexport interface ColumnRange {\n start: number;\n stop: number;\n}\n\n/**\n * Reads a specific column for the current row.\n * Wrapped in a Proxy to allow dynamic column access like `reader.column_name`\n */\nexport class RowReader {\n [column: string]: unknown;\n public columns: Record<string, number> = {};\n public row: unknown[] = [];\n\n constructor (columns: string[], columnRange?: ColumnRange) {\n columns.forEach((column, i) => {\n if (!columnRange || (columnRange.start <= i && i < columnRange.stop)) {\n this.columns[column] = i;\n }\n });\n\n return new Proxy(this as any, {\n get (target, prop: string | symbol) {\n if (prop in target) return target[prop];\n if (typeof prop === 'string' && prop in target.columns && target.row) {\n return target.row[target.columns[prop]];\n }\n\n return undefined;\n },\n });\n }\n}\n\n/**\n * Reads a range of rows for a specific column, returning an iterator.\n * Wrapped in a Proxy to allow dynamic column access like `rangeReader.column_name`\n */\nexport class RangeReader {\n public table: Table;\n public range: ColumnRange = {\n start: 0,\n stop: 0,\n };\n\n constructor (table: Table) {\n this.table = table;\n\n return new Proxy(this as any, {\n get (target, prop: string | symbol) {\n if (prop in target) return target[prop];\n if (typeof prop === 'string') {\n return (function* () {\n for (let i = target.range.start; i < target.range.stop; i++) {\n yield target.table.rows[i][target.table.columns.indexOf(prop)];\n }\n })();\n }\n\n return undefined;\n },\n });\n }\n\n get length (): number {\n return Math.max(0, this.range.stop - this.range.start);\n }\n}\n","/**\n * sqlingo\n * A JavaScript port of SQLGlot - SQL parser, transpiler, optimizer, and engine\n *\n * Based on SQLGlot by Toby Mao (https://github.com/tobymao/sqlglot)\n */\n\nimport packageJson from '../package.json';\nimport {\n ErrorLevel, SqlglotError, ParseError, TokenError, UnsupportedError,\n} from './errors';\nimport type {\n Token,\n} from './tokens';\nimport {\n TokenType, Tokenizer,\n} from './tokens';\nimport type {\n ParseOptions,\n} from './parser';\nimport {\n Parser, parse, parseOne, parseNewlineDelimited,\n} from './parser';\nimport type {\n GeneratorOptions, TranspileOptions,\n} from './generator';\nimport {\n Generator, generate,\n} from './generator';\nimport {\n Schema, MappingSchema,\n} from './schema';\nimport {\n Dialect, type Dialects, type DialectType,\n} from './dialects/dialect';\nimport {\n diff,\n} from './diff';\nimport {\n lineage,\n} from './lineage';\nimport {\n optimize,\n} from './optimizer/optimizer';\nimport {\n execute,\n} from './executor';\n\nexport * from './expressions';\n\nexport {\n dump, load,\n} from './serde';\n\nexport const version = packageJson.version;\n\nexport {\n ErrorLevel, SqlglotError, ParseError, TokenError, UnsupportedError,\n};\nexport type {\n Token,\n};\nexport {\n TokenType, Tokenizer,\n};\nexport type {\n ParseOptions,\n};\nexport {\n Parser, parse, parseOne, parseNewlineDelimited,\n};\nexport type {\n GeneratorOptions, TranspileOptions,\n};\nexport {\n Generator, generate,\n};\nexport {\n Schema, MappingSchema,\n};\nexport {\n Dialect, type Dialects, type DialectType,\n};\nexport {\n diff,\n};\nexport {\n lineage,\n};\nexport {\n optimize,\n};\nexport {\n execute,\n};\n\nexport let pretty = false;\n\nexport function setPretty (value: boolean): void {\n pretty = value;\n}\n\nexport function tokenize (sql: string, read?: DialectType, dialect?: DialectType): Token[] {\n return Dialect.getOrRaise(read ?? dialect).tokenize(sql);\n}\n\nexport function transpile (\n sql: string,\n opts: TranspileOptions = {},\n): string[] {\n const {\n read, dialect, write, identity = true, errorLevel, ...rest\n } = opts;\n const writeDialect = identity ? (write ?? read ?? dialect) : write;\n const writeDial = Dialect.getOrRaise(writeDialect);\n\n return parse(sql, {\n read: read ?? dialect,\n errorLevel,\n ...rest,\n }).map((expression) =>\n expression\n ? writeDial.generate(expression, {\n copy: false,\n ...rest,\n })\n : '');\n}\n"]}
1
+ {"version":3,"sources":["/home/huydna/projects/sqlingo.js/packages/sqlingo/dist/index.cjs","../package.json","../src/diff.ts","../src/lineage.ts","../src/planner.ts","../src/executor/table.ts","../src/index.ts"],"names":["package_default","_Insert","expression","__name","Insert","_Remove","Remove","_Move","source","target","Move","_Update","Update","_Keep","Keep","diff","options","matchings","deltaOnly","kwargs","computeNodeMappings","oldNodes","newNodes","nodeMapping","i","oldNode","newNode","sourceNodes","targetNodes","sourceSet","targetSet","copy","n","sourceCopy","targetCopy","sourceMapping","targetMapping","s","t","node","ChangeDistiller","UPDATABLE_EXPRESSION_TYPES","AliasExpr","BooleanExpr","ColumnExpr","DataTypeExpr","LambdaExpr","LiteralExpr","TableExpr","WindowExpr","IGNORED_LEAF_EXPRESSION_TYPES","IdentifierExpr","_ChangeDistiller","f","dialect","Dialect","preMatchedNodes","type","isPreMatched","targetMatch","computedMatchings","v","k","editScript","targetNode","sourceNode","identicalNodes","sParent","tParent","sourceLeaves","getNonExpressionLeaves","targetLeaves","sourceArgs","expressionOnlyArgs","targetArgs","lcsResult","lcs","l","r","argsLcs","moveEdits","a","leavesMatchingSet","matchingSet","orderedUnmatchedSource","orderedUnmatchedTarget","isSameType","sourceLeafIds","getExpressionLeaves","targetLeafIds","maxLeavesNum","leafSimilarityScore","commonLeavesNum","sLeaf","tLeaf","adjustedT","sourceHisto","targetHisto","sourceTotal","targetTotal","totalGrams","overlapLen","count","gram","gramCount","candidateMatchings","sourceExpressionLeaves","targetExpressionLeaves","sourceLeaf","targetLeaf","similarityScore","parentSimilarityScore","b","candidate","cached","str","histo","hasChildExprs","arg","value","Expression","JoinExpr","AnonymousExpr","sThis","tThis","_seqA","_seqB","equal","seqA","seqB","lenA","lenB","j","top","left","_Node","d","opts","nodes","edges","label","title","group"],"mappings":"AAAA,yuBAAyD,wDAAyyU,ICAl2UA,EAAAA,CAAA,CACC,OAAA,CAAW,2CAAA,CACX,IAAA,CAAQ,SAAA,CACR,OAAA,CAAW,CACV,MAAA,CAAU,0CAAA,CACV,OAAA,CAAW,QAAA,CACX,GAAA,CAAO,oCACR,CAAA,CACA,OAAA,CAAW,QAAA,CACX,IAAA,CAAQ,QAAA,CACR,WAAA,CAAe,CAAA,CAAA,CACf,WAAA,CAAe,oKAAA,CACf,IAAA,CAAQ,gBAAA,CACR,MAAA,CAAU,eAAA,CACV,KAAA,CAAS,iBAAA,CACT,OAAA,CAAW,CACV,GAAA,CAAK,CACJ,KAAA,CAAS,mBAAA,CACT,MAAA,CAAU,iBAAA,CACV,OAAA,CAAW,kBACZ,CAAA,CACA,UAAA,CAAY,CACX,KAAA,CAAS,6BAAA,CACT,MAAA,CAAU,2BAAA,CACV,OAAA,CAAW,4BACZ,CAAA,CACA,YAAA,CAAc,CACb,KAAA,CAAS,+BAAA,CACT,MAAA,CAAU,6BAAA,CACV,OAAA,CAAW,8BACZ,CAAA,CACA,cAAA,CAAgB,CACf,KAAA,CAAS,iCAAA,CACT,MAAA,CAAU,+BAAA,CACV,OAAA,CAAW,gCACZ,CAAA,CACA,cAAA,CAAgB,CACf,KAAA,CA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qG,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAEAvG,CAAAA,CAAK,WAAA,WAAsBS,oBAAAA,CAAAA,CAC7B4F,CAAAA,CAAQ,CAAA,KAAA,EAAQrG,CAAAA,CAAK,UAAA,CAAW,IAAA,CAAK,IAAI,CAAA,CAAA;AAmftC;AALH,EAAA;AAAA;AAOO,2GAAA;AAAA;AAE4B,gCAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASG,mCAAA;AAAA;AAEzB,QAAA;AAAA;AAAA;AC1fV,MAAA;AAAA;AAmWW;ACvUA;ACZN","file":"/home/huydna/projects/sqlingo.js/packages/sqlingo/dist/index.cjs","sourcesContent":[null,"{\n\t\"$schema\": \"https://json.schemastore.org/package.json\",\n\t\"name\": \"sqlingo\",\n\t\"sqlglot\": {\n\t\t\"commit\": \"872625011c6a601d80dc61fdedf5d7356c836de0\",\n\t\t\"version\": \"30.1.0\",\n\t\t\"url\": \"https://github.com/tobymao/sqlglot\"\n\t},\n\t\"version\": \"0.12.3\",\n\t\"type\": \"module\",\n\t\"sideEffects\": false,\n\t\"description\": \"SQL parser, transpiler, optimizer, and engine for JavaScript/TypeScript - 32 dialects (Postgres, MySQL, BigQuery, Snowflake, DuckDB, etc). Port of Python SQLGlot.\",\n\t\"main\": \"dist/index.cjs\",\n\t\"module\": \"dist/index.js\",\n\t\"types\": \"dist/index.d.ts\",\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"types\": \"./dist/index.d.ts\",\n\t\t\t\"import\": \"./dist/index.js\",\n\t\t\t\"require\": \"./dist/index.cjs\"\n\t\t},\n\t\t\"./athena\": {\n\t\t\t\"types\": \"./dist/dialects/athena.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/athena.js\",\n\t\t\t\"require\": \"./dist/dialects/athena.cjs\"\n\t\t},\n\t\t\"./bigquery\": {\n\t\t\t\"types\": \"./dist/dialects/bigquery.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/bigquery.js\",\n\t\t\t\"require\": \"./dist/dialects/bigquery.cjs\"\n\t\t},\n\t\t\"./clickhouse\": {\n\t\t\t\"types\": \"./dist/dialects/clickhouse.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/clickhouse.js\",\n\t\t\t\"require\": \"./dist/dialects/clickhouse.cjs\"\n\t\t},\n\t\t\"./databricks\": {\n\t\t\t\"types\": \"./dist/dialects/databricks.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/databricks.js\",\n\t\t\t\"require\": \"./dist/dialects/databricks.cjs\"\n\t\t},\n\t\t\"./doris\": {\n\t\t\t\"types\": \"./dist/dialects/doris.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/doris.js\",\n\t\t\t\"require\": \"./dist/dialects/doris.cjs\"\n\t\t},\n\t\t\"./dremio\": {\n\t\t\t\"types\": \"./dist/dialects/dremio.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/dremio.js\",\n\t\t\t\"require\": \"./dist/dialects/dremio.cjs\"\n\t\t},\n\t\t\"./drill\": {\n\t\t\t\"types\": \"./dist/dialects/drill.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/drill.js\",\n\t\t\t\"require\": \"./dist/dialects/drill.cjs\"\n\t\t},\n\t\t\"./druid\": {\n\t\t\t\"types\": \"./dist/dialects/druid.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/druid.js\",\n\t\t\t\"require\": \"./dist/dialects/druid.cjs\"\n\t\t},\n\t\t\"./duckdb\": {\n\t\t\t\"types\": \"./dist/dialects/duckdb.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/duckdb.js\",\n\t\t\t\"require\": \"./dist/dialects/duckdb.cjs\"\n\t\t},\n\t\t\"./dune\": {\n\t\t\t\"types\": \"./dist/dialects/dune.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/dune.js\",\n\t\t\t\"require\": \"./dist/dialects/dune.cjs\"\n\t\t},\n\t\t\"./exasol\": {\n\t\t\t\"types\": \"./dist/dialects/exasol.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/exasol.js\",\n\t\t\t\"require\": \"./dist/dialects/exasol.cjs\"\n\t\t},\n\t\t\"./fabric\": {\n\t\t\t\"types\": \"./dist/dialects/fabric.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/fabric.js\",\n\t\t\t\"require\": \"./dist/dialects/fabric.cjs\"\n\t\t},\n\t\t\"./hive\": {\n\t\t\t\"types\": \"./dist/dialects/hive.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/hive.js\",\n\t\t\t\"require\": \"./dist/dialects/hive.cjs\"\n\t\t},\n\t\t\"./materialize\": {\n\t\t\t\"types\": \"./dist/dialects/materialize.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/materialize.js\",\n\t\t\t\"require\": \"./dist/dialects/materialize.cjs\"\n\t\t},\n\t\t\"./mysql\": {\n\t\t\t\"types\": \"./dist/dialects/mysql.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/mysql.js\",\n\t\t\t\"require\": \"./dist/dialects/mysql.cjs\"\n\t\t},\n\t\t\"./mssql\": {\n\t\t\t\"types\": \"./dist/dialects/tsql.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/tsql.js\",\n\t\t\t\"require\": \"./dist/dialects/tsql.cjs\"\n\t\t},\n\t\t\"./oracle\": {\n\t\t\t\"types\": \"./dist/dialects/oracle.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/oracle.js\",\n\t\t\t\"require\": \"./dist/dialects/oracle.cjs\"\n\t\t},\n\t\t\"./postgres\": {\n\t\t\t\"types\": \"./dist/dialects/postgres.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/postgres.js\",\n\t\t\t\"require\": \"./dist/dialects/postgres.cjs\"\n\t\t},\n\t\t\"./presto\": {\n\t\t\t\"types\": \"./dist/dialects/presto.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/presto.js\",\n\t\t\t\"require\": \"./dist/dialects/presto.cjs\"\n\t\t},\n\t\t\"./prql\": {\n\t\t\t\"types\": \"./dist/dialects/prql.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/prql.js\",\n\t\t\t\"require\": \"./dist/dialects/prql.cjs\"\n\t\t},\n\t\t\"./redshift\": {\n\t\t\t\"types\": \"./dist/dialects/redshift.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/redshift.js\",\n\t\t\t\"require\": \"./dist/dialects/redshift.cjs\"\n\t\t},\n\t\t\"./risingwave\": {\n\t\t\t\"types\": \"./dist/dialects/risingwave.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/risingwave.js\",\n\t\t\t\"require\": \"./dist/dialects/risingwave.cjs\"\n\t\t},\n\t\t\"./singlestore\": {\n\t\t\t\"types\": \"./dist/dialects/singlestore.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/singlestore.js\",\n\t\t\t\"require\": \"./dist/dialects/singlestore.cjs\"\n\t\t},\n\t\t\"./snowflake\": {\n\t\t\t\"types\": \"./dist/dialects/snowflake.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/snowflake.js\",\n\t\t\t\"require\": \"./dist/dialects/snowflake.cjs\"\n\t\t},\n\t\t\"./solr\": {\n\t\t\t\"types\": \"./dist/dialects/solr.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/solr.js\",\n\t\t\t\"require\": \"./dist/dialects/solr.cjs\"\n\t\t},\n\t\t\"./spark\": {\n\t\t\t\"types\": \"./dist/dialects/spark.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/spark.js\",\n\t\t\t\"require\": \"./dist/dialects/spark.cjs\"\n\t\t},\n\t\t\"./spark2\": {\n\t\t\t\"types\": \"./dist/dialects/spark2.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/spark2.js\",\n\t\t\t\"require\": \"./dist/dialects/spark2.cjs\"\n\t\t},\n\t\t\"./sqlite\": {\n\t\t\t\"types\": \"./dist/dialects/sqlite.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/sqlite.js\",\n\t\t\t\"require\": \"./dist/dialects/sqlite.cjs\"\n\t\t},\n\t\t\"./starrocks\": {\n\t\t\t\"types\": \"./dist/dialects/starrocks.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/starrocks.js\",\n\t\t\t\"require\": \"./dist/dialects/starrocks.cjs\"\n\t\t},\n\t\t\"./tableau\": {\n\t\t\t\"types\": \"./dist/dialects/tableau.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/tableau.js\",\n\t\t\t\"require\": \"./dist/dialects/tableau.cjs\"\n\t\t},\n\t\t\"./teradata\": {\n\t\t\t\"types\": \"./dist/dialects/teradata.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/teradata.js\",\n\t\t\t\"require\": \"./dist/dialects/teradata.cjs\"\n\t\t},\n\t\t\"./trino\": {\n\t\t\t\"types\": \"./dist/dialects/trino.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/trino.js\",\n\t\t\t\"require\": \"./dist/dialects/trino.cjs\"\n\t\t},\n\t\t\"./tsql\": {\n\t\t\t\"types\": \"./dist/dialects/tsql.d.ts\",\n\t\t\t\"import\": \"./dist/dialects/tsql.js\",\n\t\t\t\"require\": \"./dist/dialects/tsql.cjs\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"test\": \"vitest\",\n\t\t\"test:ui\": \"vitest --ui\",\n\t\t\"test:coverage\": \"vitest --coverage\",\n\t\t\"build\": \"tsup\",\n\t\t\"dev\": \"tsup --watch\",\n\t\t\"lint\": \"eslint .\",\n\t\t\"lint:fix\": \"eslint . --fix\",\n\t\t\"typecheck\": \"tsc --noEmit\",\n\t\t\"prepublishOnly\": \"cp README.md README.repo.md && cp README.npm.md README.md\",\n\t\t\"postpublish\": \"mv README.repo.md README.md\"\n\t},\n\t\"keywords\": [\n\t\t\"sql\",\n\t\t\"sqlingo\",\n\t\t\"sqlingo.js\",\n\t\t\"tokenizer\",\n\t\t\"parser\",\n\t\t\"transpiler\",\n\t\t\"optimizer\",\n\t\t\"sqlingo\",\n\t\t\"sqlglot\",\n\t\t\"sql-parser\",\n\t\t\"sql-transpiler\",\n\t\t\"sql-optimizer\",\n\t\t\"sql-engine\",\n\t\t\"sql-builder\",\n\t\t\"query-builder\",\n\t\t\"sql-to-sql\",\n\t\t\"sql-converter\",\n\t\t\"sql-formatter\",\n\t\t\"ast\",\n\t\t\"abstract-syntax-tree\",\n\t\t\"column-lineage\",\n\t\t\"dialect\",\n\t\t\"mysql\",\n\t\t\"postgres\",\n\t\t\"bigquery\",\n\t\t\"snowflake\",\n\t\t\"duckdb\",\n\t\t\"clickhouse\",\n\t\t\"redshift\",\n\t\t\"athena\",\n\t\t\"hive\",\n\t\t\"spark\",\n\t\t\"oracle\",\n\t\t\"tsql\",\n\t\t\"sqlite\",\n\t\t\"presto\",\n\t\t\"trino\",\n\t\t\"javascript\",\n\t\t\"typescript\"\n\t],\n\t\"author\": \"Huy DNA\",\n\t\"license\": \"MIT\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"https://github.com/huydo862003/sqlingo.git\"\n\t},\n\t\"bugs\": {\n\t\t\"url\": \"https://github.com/huydo862003/sqlingo/issues\"\n\t},\n\t\"homepage\": \"https://huydo862003.github.io/sqlingo\",\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"LICENSE\",\n\t\t\"README.md\",\n\t\t\"COPYRIGHT_NOTICE\",\n\t\t\"CHANGELOG.md\"\n\t],\n\t\"devDependencies\": {\n\t\t\"@types/luxon\": \"^3.7.5\",\n\t\t\"@types/node\": \"^26.6.3\",\n\t\t\"tsup\": \"^8.5.1\",\n\t\t\"typescript\": \"^5.9.3\",\n\t\t\"vite\": \"^7.3.6\",\n\t\t\"vitest\": \"5.0.1\"\n\t},\n\t\"peerDependencies\": {\n\t\t\"luxon\": \"^3.7.2\"\n\t}\n}\n","import {\n Dialect,\n} from './dialects/dialect';\nimport {\n AliasExpr, AnonymousExpr, BooleanExpr, ColumnExpr, DataTypeExpr, Expression, IdentifierExpr, JoinExpr, LambdaExpr, LiteralExpr, TableExpr, WindowExpr,\n} from './expressions';\nimport type {\n Generator as SqlGenerator,\n} from './generator';\n\n/**\n * Indicates that a new node has been inserted\n */\nexport class Insert {\n constructor (public readonly expression: Expression) {}\n toJSON () {\n return {\n type: 'Insert',\n expression: this.expression.sql(),\n };\n }\n}\n\n/**\n * Indicates that an existing node has been removed\n */\nexport class Remove {\n constructor (public readonly expression: Expression) {}\n toJSON () {\n return {\n type: 'Remove',\n expression: this.expression.sql(),\n };\n }\n}\n\n/**\n * Indicates that an existing node's position within the tree has changed\n */\nexport class Move {\n constructor (\n public readonly source: Expression,\n public readonly target: Expression,\n ) {}\n\n toJSON () {\n return {\n type: 'Move',\n source: this.source.sql(),\n target: this.target.sql(),\n };\n }\n}\n\n/**\n * Indicates that an existing node has been updated\n */\nexport class Update {\n constructor (\n public readonly source: Expression,\n public readonly target: Expression,\n ) {}\n\n toJSON () {\n return {\n type: 'Update',\n source: this.source.sql(),\n target: this.target.sql(),\n };\n }\n}\n\n/**\n * Indicates that an existing node hasn't been changed\n */\nexport class Keep {\n constructor (\n public readonly source: Expression,\n public readonly target: Expression,\n ) {}\n\n toJSON () {\n return {\n type: 'Keep',\n source: this.source.sql(),\n target: this.target.sql(),\n };\n }\n}\n\n/**\n * Union type representing any possible tree edit operation\n */\nexport type Edit = Insert | Remove | Move | Update | Keep;\n\ntype MatchingPair = [Expression, Expression];\n\nexport function diff (\n source: Expression,\n target: Expression,\n options: {\n matchings?: MatchingPair[];\n deltaOnly?: boolean;\n [key: string]: unknown;\n } = {},\n): Edit[] {\n let {\n matchings = [],\n\n deltaOnly = false,\n\n ...kwargs\n } = options;\n\n function computeNodeMappings (\n oldNodes: Expression[],\n newNodes: Expression[],\n ): Map<Expression, Expression> {\n const nodeMapping = new Map<Expression, Expression>();\n\n // Zip reversed arrays\n for (let i = 0; i < oldNodes.length; i++) {\n const oldNode = oldNodes[oldNodes.length - 1 - i];\n const newNode = newNodes[newNodes.length - 1 - i];\n\n newNode.computeHash();\n nodeMapping.set(oldNode, newNode);\n }\n\n return nodeMapping;\n }\n\n const sourceNodes = Array.from(source.walk());\n const targetNodes = Array.from(target.walk());\n\n const sourceSet = new Set(sourceNodes);\n const targetSet = new Set(targetNodes);\n\n const copy = (\n sourceNodes.length !== sourceSet.size\n || targetNodes.length !== targetSet.size\n || sourceNodes.some((n) => targetSet.has(n))\n );\n\n const sourceCopy = copy ? source.copy() : source;\n const targetCopy = copy ? target.copy() : target;\n\n try {\n if (copy && 0 < matchings.length) {\n const sourceMapping = computeNodeMappings(sourceNodes, Array.from(sourceCopy.walk()));\n const targetMapping = computeNodeMappings(targetNodes, Array.from(targetCopy.walk()));\n\n matchings = matchings.map(([\n s,\n t,\n ]) => [\n sourceMapping.get(s)!,\n targetMapping.get(t)!,\n ]);\n } else {\n [\n ...sourceNodes,\n ...targetNodes,\n ].reverse().forEach((node) => {\n node.computeHash();\n });\n }\n\n return new ChangeDistiller(kwargs).diff(\n sourceCopy,\n targetCopy,\n {\n deltaOnly,\n matchings,\n },\n );\n } finally {\n if (!copy) {\n [\n ...sourceNodes,\n ...targetNodes,\n ].forEach((node) => {\n node.resetHash();\n });\n }\n }\n}\n\nconst UPDATABLE_EXPRESSION_TYPES = [\n AliasExpr,\n BooleanExpr,\n ColumnExpr,\n DataTypeExpr,\n LambdaExpr,\n LiteralExpr,\n TableExpr,\n WindowExpr,\n];\n\nconst IGNORED_LEAF_EXPRESSION_TYPES = [IdentifierExpr];\n\nclass ChangeDistiller {\n private f: number;\n private t: number;\n private sqlGenerator: SqlGenerator;\n private bigramHistoCache = new Map<Expression, Map<string, number>>();\n private unmatchedSourceNodes = new Set<Expression>();\n private unmatchedTargetNodes = new Set<Expression>();\n private source?: Expression;\n private sourceIndex = new Map<Expression, Expression>();\n private target?: Expression;\n private targetIndex = new Map<Expression, Expression>();\n\n constructor (options: {\n f?: number;\n t?: number;\n dialect?: string;\n } = {}) {\n const {\n f = 0.6,\n t = 0.6,\n dialect,\n } = options;\n\n this.f = f;\n this.t = t;\n this.sqlGenerator = Dialect.getOrRaise(dialect).generator({\n comments: false,\n });\n }\n\n diff (\n source: Expression,\n target: Expression,\n options: {\n deltaOnly?: boolean;\n matchings?: MatchingPair[];\n } = {},\n ): Edit[] {\n const {\n deltaOnly = false,\n matchings = [],\n } = options;\n\n const preMatchedNodes = new Map<Expression, Expression>(matchings);\n\n this.source = source;\n this.target = target;\n\n for (const n of source.bfs()) {\n if (!IGNORED_LEAF_EXPRESSION_TYPES.some((type) => n instanceof type)) {\n this.sourceIndex.set(n, n);\n if (!preMatchedNodes.has(n)) this.unmatchedSourceNodes.add(n);\n }\n }\n\n for (const n of target.bfs()) {\n if (!IGNORED_LEAF_EXPRESSION_TYPES.some((type) => n instanceof type)) {\n this.targetIndex.set(n, n);\n // Check if n is a target in preMatchedNodes\n let isPreMatched = false;\n\n for (const targetMatch of preMatchedNodes.values()) {\n if (targetMatch === n) {\n isPreMatched = true;\n break;\n }\n }\n if (!isPreMatched) this.unmatchedTargetNodes.add(n);\n }\n }\n\n this.bigramHistoCache.clear();\n\n const computedMatchings = this.computeMatchingSet();\n\n preMatchedNodes.forEach((v, k) => computedMatchings.set(k, v));\n\n return this.generateEditScript(computedMatchings, {\n deltaOnly,\n });\n }\n\n private generateEditScript (\n matchings: Map<Expression, Expression>,\n options: {\n deltaOnly: boolean;\n },\n ): Edit[] {\n const {\n deltaOnly,\n } = options;\n const editScript: Edit[] = [];\n\n this.unmatchedSourceNodes.forEach((node) => editScript.push(new Remove(node)));\n this.unmatchedTargetNodes.forEach((node) => editScript.push(new Insert(node)));\n\n matchings.forEach((targetNode, sourceNode) => {\n const identicalNodes = sourceNode.equals(targetNode);\n\n if (!UPDATABLE_EXPRESSION_TYPES.some((type) => sourceNode instanceof type) || identicalNodes) {\n if (identicalNodes) {\n const sParent = sourceNode.parent;\n const tParent = targetNode.parent;\n\n if (\n (!sParent && tParent)\n || (sParent && !tParent)\n || (sParent && tParent && matchings.get(sParent) !== tParent)\n ) {\n editScript.push(new Move(sourceNode, targetNode));\n }\n } else {\n editScript.push(...this.generateMoveEdits(sourceNode, targetNode, matchings));\n }\n\n // Check non-expression leaves (attributes)\n const sourceLeaves = Object.fromEntries(getNonExpressionLeaves(sourceNode));\n const targetLeaves = Object.fromEntries(getNonExpressionLeaves(targetNode));\n\n if (JSON.stringify(sourceLeaves) !== JSON.stringify(targetLeaves)) {\n editScript.push(new Update(sourceNode, targetNode));\n } else if (!deltaOnly) {\n editScript.push(new Keep(sourceNode, targetNode));\n }\n } else {\n editScript.push(new Update(sourceNode, targetNode));\n }\n });\n\n return editScript;\n }\n\n private generateMoveEdits (\n source: Expression,\n target: Expression,\n matchings: Map<Expression, Expression>,\n ): Move[] {\n const sourceArgs = [...expressionOnlyArgs(source)];\n const targetArgs = [...expressionOnlyArgs(target)];\n\n // LCS expects a comparator that returns true if source element matches target element\n const lcsResult = lcs(\n sourceArgs,\n targetArgs,\n (l, r) => matchings.get(l) === r,\n );\n const argsLcs = new Set(lcsResult);\n\n const moveEdits: Move[] = [];\n\n for (const a of sourceArgs) {\n // If the node is matched but its position in the arg list changed (not in LCS), it's a Move\n if (!argsLcs.has(a) && !this.unmatchedSourceNodes.has(a)) {\n const targetNode = matchings.get(a)!;\n\n moveEdits.push(new Move(this.sourceIndex.get(a)!, this.targetIndex.get(targetNode)!));\n }\n }\n\n return moveEdits;\n }\n\n private computeMatchingSet (): Map<Expression, Expression> {\n const leavesMatchingSet = this.computeLeafMatchingSet();\n const matchingSet = new Map<Expression, Expression>(leavesMatchingSet);\n\n // Maintain BFS order for unmatched nodes\n const orderedUnmatchedSource: Expression[] = [];\n\n for (const n of this.source?.bfs() ?? []) {\n if (this.unmatchedSourceNodes.has(n)) orderedUnmatchedSource.push(n);\n }\n\n const orderedUnmatchedTarget: Expression[] = [];\n\n for (const n of this.target?.bfs() ?? []) {\n if (this.unmatchedTargetNodes.has(n)) orderedUnmatchedTarget.push(n);\n };\n\n for (const sourceNode of orderedUnmatchedSource) {\n for (const targetNode of orderedUnmatchedTarget) {\n if (isSameType(sourceNode, targetNode)) {\n const sourceLeafIds = new Set(getExpressionLeaves(sourceNode));\n const targetLeafIds = new Set(getExpressionLeaves(targetNode));\n\n const maxLeavesNum = Math.max(sourceLeafIds.size, targetLeafIds.size);\n let leafSimilarityScore = 0.0;\n\n if (0 < maxLeavesNum) {\n let commonLeavesNum = 0;\n\n for (const [\n sLeaf,\n tLeaf,\n ] of leavesMatchingSet) {\n if (sourceLeafIds.has(sLeaf) && targetLeafIds.has(tLeaf)) {\n commonLeavesNum++;\n }\n }\n leafSimilarityScore = commonLeavesNum / maxLeavesNum;\n }\n\n const adjustedT = 4 < Math.min(sourceLeafIds.size, targetLeafIds.size) ? this.t : 0.4;\n\n if (\n 0.8 <= leafSimilarityScore\n || (adjustedT <= leafSimilarityScore && this.f <= this.diceCoefficient(sourceNode, targetNode))\n ) {\n matchingSet.set(sourceNode, targetNode);\n this.unmatchedSourceNodes.delete(sourceNode);\n this.unmatchedTargetNodes.delete(targetNode);\n orderedUnmatchedTarget.splice(orderedUnmatchedTarget.indexOf(targetNode), 1);\n break;\n }\n }\n }\n }\n\n return matchingSet;\n }\n\n private diceCoefficient (source: Expression, target: Expression): number {\n const sourceHisto = this.getBigramHisto(source);\n const targetHisto = this.getBigramHisto(target);\n\n let sourceTotal = 0;\n\n sourceHisto.forEach((v) => {\n sourceTotal += v;\n });\n let targetTotal = 0;\n\n targetHisto.forEach((v) => {\n targetTotal += v;\n });\n\n const totalGrams = sourceTotal + targetTotal;\n\n if (totalGrams === 0) return source.equals(target) ? 1.0 : 0.0;\n\n let overlapLen = 0;\n\n sourceHisto.forEach((count, gram) => {\n const gramCount = targetHisto.get(gram);\n\n if (gramCount !== undefined) {\n overlapLen += Math.min(count, gramCount);\n }\n });\n\n return (2 * overlapLen) / totalGrams;\n }\n\n private computeLeafMatchingSet (): Map<Expression, Expression> {\n const candidateMatchings: Array<{\n similarity: number;\n parentSimilarity: number;\n index: number;\n sourceLeaf: Expression;\n targetLeaf: Expression;\n }> = [];\n\n const sourceExpressionLeaves = this.source\n ? [...getExpressionLeaves(this.source)]\n : [];\n const targetExpressionLeaves = this.target\n ? [...getExpressionLeaves(this.target)]\n : [];\n\n for (const sourceLeaf of sourceExpressionLeaves) {\n for (const targetLeaf of targetExpressionLeaves) {\n if (isSameType(sourceLeaf, targetLeaf)) {\n const similarityScore = this.diceCoefficient(sourceLeaf, targetLeaf);\n\n if (this.f <= similarityScore) {\n candidateMatchings.push({\n similarity: -similarityScore, // Negative for min-priority behavior\n parentSimilarity: -parentSimilarityScore(sourceLeaf, targetLeaf),\n index: candidateMatchings.length,\n sourceLeaf,\n targetLeaf,\n });\n }\n }\n }\n }\n\n // Sort to simulate heappop (highest similarity first)\n candidateMatchings.sort((a, b) => {\n if (a.similarity !== b.similarity) return a.similarity - b.similarity;\n if (a.parentSimilarity !== b.parentSimilarity) return a.parentSimilarity - b.parentSimilarity;\n\n return a.index - b.index;\n });\n\n const matchingSet = new Map<Expression, Expression>();\n\n for (const candidate of candidateMatchings) {\n const {\n sourceLeaf, targetLeaf,\n } = candidate;\n\n if (\n this.unmatchedSourceNodes.has(sourceLeaf)\n && this.unmatchedTargetNodes.has(targetLeaf)\n ) {\n matchingSet.set(sourceLeaf, targetLeaf);\n this.unmatchedSourceNodes.delete(sourceLeaf);\n this.unmatchedTargetNodes.delete(targetLeaf);\n }\n }\n\n return matchingSet;\n }\n\n private getBigramHisto (expression: Expression): Map<string, number> {\n const cached = this.bigramHistoCache.get(expression);\n\n if (cached !== undefined) return cached;\n\n const str = this.sqlGenerator.generate(expression);\n const histo = new Map<string, number>();\n\n for (let i = 0; i < str.length - 1; i++) {\n const gram = str.substring(i, i + 2);\n\n histo.set(gram, (histo.get(gram) || 0) + 1);\n }\n this.bigramHistoCache.set(expression, histo);\n\n return histo;\n }\n}\n\n/**\n * Recursively finds all leaf nodes in an expression tree\n */\nexport function* getExpressionLeaves (expression: Expression): Generator<Expression> {\n let hasChildExprs = false;\n\n for (const node of expression.iterExpressions()) {\n if (!IGNORED_LEAF_EXPRESSION_TYPES.some((type) => node instanceof type)) {\n hasChildExprs = true;\n yield* getExpressionLeaves(node);\n }\n }\n\n if (!hasChildExprs) {\n yield expression;\n }\n}\n\n/**\n * Yields non-expression attributes (metadata) of a node for Update detection\n */\nexport function* getNonExpressionLeaves (expression: Expression): Generator<[string, unknown]> {\n for (const [\n arg,\n value,\n ] of Object.entries(expression.args)) {\n if (\n value === null\n || value === undefined\n || value instanceof Expression\n || (Array.isArray(value) && value[0] instanceof Expression)\n ) {\n continue;\n }\n\n yield [\n arg,\n value,\n ];\n }\n}\n\n/**\n * Determines if two nodes are of the same semantic type\n */\nexport function isSameType (source: Expression, target: Expression): boolean {\n if (source.constructor === target.constructor) {\n if (source instanceof JoinExpr && target instanceof JoinExpr) {\n return source.args.side === target.args.side;\n }\n\n if (source instanceof AnonymousExpr && target instanceof AnonymousExpr) {\n const sThis = source.args.this;\n const tThis = target.args.this;\n\n if (sThis instanceof Expression && tThis instanceof Expression) {\n return sThis.equals(tThis);\n }\n\n return sThis === tThis;\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * Calculates a similarity score based on the depth of matching parent types\n */\nexport function parentSimilarityScore (\n source: Expression | undefined,\n target: Expression | undefined,\n): number {\n if (!source || !target || source.constructor !== target.constructor) {\n return 0;\n }\n\n return 1 + parentSimilarityScore(source.parent, target.parent);\n}\n\n/**\n * Yields only child expressions, filtering out ignored leaf types (like Identifiers)\n */\nexport function* expressionOnlyArgs (expression: Expression): Generator<Expression> {\n for (const arg of expression.iterExpressions()) {\n if (!IGNORED_LEAF_EXPRESSION_TYPES.some((type) => arg instanceof type)) {\n yield arg;\n }\n }\n}\n\n/**\n * Calculates the longest common subsequence between two sequences.\n * * This is used to detect \"Move\" edits by determining which nodes\n * maintained their relative order\n */\nexport function lcs<T> (\n _seqA: Iterable<T>,\n _seqB: Iterable<T>,\n equal: (a: T, b: T) => boolean,\n): T[] {\n const seqA = [..._seqA];\n const seqB = [..._seqB];\n const lenA = seqA.length;\n const lenB = seqB.length;\n\n // Initialize a 2D array for DP\n const lcsResult: T[][][] = Array.from({\n length: lenA + 1,\n }, () =>\n Array.from({\n length: lenB + 1,\n }, () => []));\n\n for (let i = 1; i <= lenA; i++) {\n for (let j = 1; j <= lenB; j++) {\n if (equal(seqA[i - 1], seqB[j - 1])) {\n // If equal, take the diagonal result and add current element\n lcsResult[i][j] = [\n ...lcsResult[i - 1][j - 1],\n seqA[i - 1],\n ];\n } else {\n // Otherwise, take the maximum of top or left\n const top = lcsResult[i - 1][j];\n const left = lcsResult[i][j - 1];\n\n lcsResult[i][j] = left.length < top.length ? top : left;\n }\n }\n }\n\n return lcsResult[lenA][lenB];\n}\n","import type {\n Expression, QueryExpr,\n} from './expressions';\nimport {\n TableExpr, TagExpr,\n SelectExpr,\n StarExpr,\n SubqueryExpr,\n SetOperationExpr,\n ColumnExpr,\n UdtfExpr,\n PlaceholderExpr,\n UNWRAPPED_QUERIES,\n maybeParse,\n expand,\n} from './expressions';\nimport {\n SqlglotError,\n} from './errors';\nimport {\n normalizeIdentifiers,\n} from './optimizer/normalize_identifiers';\nimport {\n qualify,\n} from './optimizer/qualify';\nimport {\n buildScope,\n Scope, ScopeType, findAllInScope,\n} from './optimizer/scope';\nimport type {\n DialectType,\n} from './dialects/dialect';\nimport type {\n Schema,\n} from './schema';\nimport {\n id,\n} from './port_internals';\n\nexport interface NodeOptions {\n name: string;\n expression: Expression;\n source: Expression;\n downstream?: Node[];\n sourceName?: string;\n referenceNodeName?: string;\n}\n\nexport class Node {\n public name: string;\n public expression: Expression;\n public source: Expression;\n public downstream: Node[];\n public sourceName: string;\n public referenceNodeName: string;\n\n constructor (options: NodeOptions) {\n this.name = options.name;\n this.expression = options.expression;\n this.source = options.source;\n this.downstream = options.downstream || [];\n this.sourceName = options.sourceName || '';\n this.referenceNodeName = options.referenceNodeName || '';\n }\n\n * walk (): Generator<Node> {\n yield this;\n for (const d of this.downstream) {\n yield* d.walk();\n }\n }\n\n toHtml (dialect?: DialectType, opts: Record<string, unknown> = {}): GraphHTML {\n const nodes: Record<string, unknown> = {};\n const edges: unknown[] = [];\n\n for (const node of this.walk()) {\n let label: string;\n let title: string;\n let group: number;\n\n if (node.expression instanceof TableExpr) {\n label = `FROM ${node.expression.args.this}`;\n title = `<pre>SELECT ${node.name} FROM ${node.expression.args.this}</pre>`;\n group = 1;\n } else {\n label = node.expression.sql({\n pretty: true,\n dialect,\n });\n\n const sourceSql = node.source.transform((n: Expression) => {\n return n === node.expression\n ? new TagExpr({\n this: n,\n prefix: '<b>',\n postfix: '</b>',\n })\n : n;\n }, {\n copy: false,\n }).sql({\n pretty: true,\n dialect,\n });\n\n title = `<pre>${sourceSql}</pre>`;\n group = 0;\n }\n\n const nodeId = id(node);\n\n nodes[nodeId] = {\n id: nodeId,\n label,\n title,\n group,\n };\n\n for (const d of node.downstream) {\n edges.push({\n from: nodeId,\n to: id(d),\n });\n }\n }\n\n return new GraphHTML(nodes, edges, opts);\n }\n}\n\nexport interface LineageOptions {\n schema?: Record<string, unknown> | Schema;\n sources?: Record<string, string | QueryExpr>;\n dialect?: DialectType;\n scope?: Scope;\n trimSelects?: boolean;\n copy?: boolean;\n [key: string]: unknown;\n}\n\n/**\n * Build the lineage graph for a column of a SQL query.\n *\n * @param column The column to build the lineage for.\n * @param sql The SQL string or expression.\n * @param options Additional options like schema, dialect, scope, etc.\n * @returns A lineage node\n */\nexport function lineage (\n column: string | ColumnExpr,\n sql: string | Expression,\n options: LineageOptions = {},\n): Node {\n const {\n schema,\n sources,\n dialect,\n scope: providedScope,\n trimSelects = true,\n copy = true,\n ...kwargs\n } = options;\n\n let expression = maybeParse(sql, {\n copy,\n dialect,\n });\n const normalizedColumn = normalizeIdentifiers(column, {\n dialect,\n }).name;\n\n if (sources) {\n const parsedSources: Record<string, QueryExpr> = {};\n\n for (const [\n k,\n v,\n ] of Object.entries(sources)) {\n parsedSources[k] = maybeParse(v, {\n copy,\n dialect,\n }) as QueryExpr;\n }\n\n expression = expand(expression, parsedSources, {\n dialect,\n copy,\n });\n }\n\n let scope = providedScope;\n\n if (!scope) {\n expression = qualify(expression, {\n dialect,\n schema,\n validateQualifyColumns: false,\n identify: false,\n ...kwargs,\n });\n\n scope = buildScope(expression);\n }\n\n if (!scope) {\n throw new SqlglotError('Cannot build lineage, sql must be SELECT');\n }\n\n // Assuming scope.expression is a Select expression containing `selects`\n const hasColumn = scope.expression.selects.some(\n (select) => select.aliasOrName === normalizedColumn,\n );\n\n if (!hasColumn) {\n throw new SqlglotError(`Cannot find column '${normalizedColumn}' in query.`);\n }\n\n return toNode(normalizedColumn, scope, dialect, {\n trimSelects,\n });\n}\n\nexport interface ToNodeOptions {\n scopeName?: string;\n upstream?: Node;\n sourceName?: string;\n referenceNodeName?: string;\n trimSelects?: boolean;\n}\n\nexport function toNode (\n column: string | number,\n scope: Scope,\n dialect: DialectType | undefined,\n options: ToNodeOptions = {},\n): Node {\n let {\n\n scopeName = undefined,\n upstream = undefined,\n\n sourceName = undefined,\n\n referenceNodeName = undefined,\n\n trimSelects = true,\n } = options;\n\n // Find the specific select clause that is the source of the column we want\n // This can either be a specific, named select or a generic `*` clause\n let select: Expression;\n\n if (typeof column === 'number') {\n if (scope.expression.selects.length <= column) {\n throw new SqlglotError(\n `Cannot find column's source with index ${column} in query: ${scope.expression.sql({\n dialect,\n })}`,\n );\n }\n\n select = scope.expression.selects[column];\n } else {\n const foundSelect = scope.expression.selects.find(\n (s) => s.aliasOrName === column,\n );\n\n select = foundSelect || (scope.expression.isStar ? new StarExpr({}) : scope.expression);\n }\n\n if (scope.expression instanceof SubqueryExpr) {\n for (const source of scope.subqueryScopes) {\n return toNode(column, source, dialect, {\n upstream,\n sourceName,\n referenceNodeName,\n trimSelects,\n });\n }\n }\n\n if (scope.expression instanceof SetOperationExpr) {\n const name = scope.expression.constructor.name.toUpperCase().replace('EXPR', '');\n\n upstream = upstream || new Node({\n name,\n source: scope.expression,\n expression: select,\n });\n\n let index: number;\n\n if (typeof column === 'number') {\n index = column;\n } else {\n index = scope.expression.selects.findIndex(\n (s) => s.aliasOrName === column || s.isStar,\n );\n }\n\n if (index === -1) {\n throw new Error(`Could not find ${column} in ${scope.expression}`);\n }\n\n for (const s of scope.unionScopes) {\n toNode(index, s, dialect, {\n upstream,\n sourceName,\n referenceNodeName,\n trimSelects,\n });\n }\n\n return upstream;\n }\n\n let source: Expression;\n\n if (trimSelects && scope.expression instanceof SelectExpr) {\n // For better ergonomics in our node labels, replace the full select with\n // a version that has only the column we care about\n source = scope.expression.select(select, {\n append: false,\n }) as Expression;\n } else {\n source = scope.expression;\n }\n\n // Create the node for this step in the lineage chain, and attach it to the previous one\n const node = new Node({\n name: scopeName ? `${scopeName}.${column}` : String(column),\n source,\n expression: select,\n sourceName: sourceName || '',\n referenceNodeName: referenceNodeName || '',\n });\n\n if (upstream) {\n upstream.downstream.push(node);\n }\n\n const subqueryScopes = new WeakMap<Expression, Scope>();\n\n for (const subqueryScope of scope.subqueryScopes) {\n subqueryScopes.set(subqueryScope.expression, subqueryScope);\n }\n\n for (const subquery of findAllInScope<QueryExpr>(select, UNWRAPPED_QUERIES)) {\n const subqueryScope = subqueryScopes.get(subquery);\n\n if (!subqueryScope) {\n console.warn(`Unknown subquery scope: ${subquery.sql({\n dialect,\n })}`);\n continue;\n }\n\n for (const name of subquery.namedSelects || []) {\n toNode(name, subqueryScope, dialect, {\n upstream: node,\n trimSelects,\n });\n }\n }\n\n // if the select is a star add all scope sources as downstreams\n if (select instanceof StarExpr) {\n for (const sourceVal of Array.from(scope.sources.values())) {\n let sourceExpr;\n\n if (sourceVal instanceof Scope) {\n sourceExpr = sourceVal.expression;\n } else {\n sourceExpr = sourceVal;\n }\n node.downstream.push(\n new Node({\n name: select.sql({\n comments: false,\n }),\n source: sourceExpr,\n expression: sourceExpr,\n }),\n );\n }\n }\n\n // Find all columns that went into creating this one to list their lineage nodes\n const sourceColumnsSet = new Set<ColumnExpr>(\n findAllInScope(select, [ColumnExpr]),\n );\n\n let derivedTables: Expression[];\n\n // If the source is a Udtf find columns used in the Udtf to generate the table\n if (source instanceof UdtfExpr) {\n const udtfCols = source.findAll(ColumnExpr);\n\n for (const c of udtfCols) sourceColumnsSet.add(c);\n\n derivedTables = Array.from(scope.sources.values())\n .filter((s): s is Scope => s instanceof Scope && s.isDerivedTable)\n .map((s) => s.expression.parent)\n .filter((p): p is Expression => p !== undefined);\n } else {\n derivedTables = scope.derivedTables;\n }\n\n const sourceNames = new Map<string, string>();\n\n for (const dt of derivedTables) {\n if (dt.comments && dt.comments[0]?.startsWith('source: ')) {\n sourceNames.set(dt.alias, dt.comments[0].split(' ')[1]);\n }\n }\n\n const pivots = scope.pivots;\n const pivot = pivots.length === 1 && !pivots[0].unpivot ? pivots[0] : undefined;\n const pivotColumnMapping = new Map<string, ColumnExpr[]>();\n\n if (pivot) {\n const pivotColumns = pivot.args.columns ?? [];\n const pivotAggsCount = pivot.args.expressions?.length ?? 0;\n\n pivot.args.expressions?.forEach((agg, i: number) => {\n const aggCols = Array.from(agg.findAll(ColumnExpr)) as ColumnExpr[];\n\n for (let colIndex = i; colIndex < (pivotColumns?.length || 0); colIndex += pivotAggsCount) {\n pivotColumnMapping.set(pivotColumns[colIndex].name, aggCols);\n }\n });\n }\n\n for (const c of Array.from(sourceColumnsSet)) {\n const table = c.table;\n let sourceScopeOrExpr: Expression | Scope | undefined = scope.sources.get(table);\n\n if (sourceScopeOrExpr instanceof Scope) {\n let refNodeName: string | undefined = undefined;\n\n if (sourceScopeOrExpr.scopeType === ScopeType.DERIVED_TABLE && !sourceNames.has(table)) {\n refNodeName = table;\n } else if (sourceScopeOrExpr.scopeType === ScopeType.CTE) {\n const selectedNode = scope.selectedSources[table]?.[0];\n\n refNodeName = selectedNode ? selectedNode.name : undefined;\n }\n\n toNode(c.name, sourceScopeOrExpr, dialect, {\n scopeName: table,\n upstream: node,\n sourceName: sourceNames.get(table) || sourceName,\n referenceNodeName: refNodeName,\n trimSelects,\n });\n } else if (pivot && pivot.aliasOrName === c.table) {\n const downstreamColumns: ColumnExpr[] = [];\n const columnName = c.name;\n\n if (pivot.args.columns?.some((pc) => pc.name === columnName)) {\n downstreamColumns.push(...(pivotColumnMapping.get(columnName) || []));\n } else {\n // Adapt column to be from the implicit pivoted source\n downstreamColumns.push(new ColumnExpr({\n this: c.args.this,\n table: pivot.parent?.aliasOrName,\n }));\n }\n\n for (const downstreamColumn of downstreamColumns) {\n const dsTable = downstreamColumn.table;\n let dsSource: Expression | Scope | undefined = scope.sources.get(dsTable);\n\n if (dsSource instanceof Scope) {\n toNode(downstreamColumn.name, dsSource, dialect, {\n scopeName: dsTable,\n upstream: node,\n sourceName: sourceNames.get(dsTable) || sourceName,\n referenceNodeName,\n trimSelects,\n });\n } else {\n dsSource = dsSource || new PlaceholderExpr({});\n node.downstream.push(\n new Node({\n name: downstreamColumn.sql({\n comments: false,\n }),\n source: dsSource,\n expression: dsSource,\n }),\n );\n }\n }\n } else {\n sourceScopeOrExpr = sourceScopeOrExpr || new PlaceholderExpr({});\n node.downstream.push(\n new Node({\n name: c.sql({\n comments: false,\n }),\n source: sourceScopeOrExpr,\n expression: sourceScopeOrExpr,\n }),\n );\n }\n }\n\n return node;\n}\n\n/**\n * Node to HTML generator using vis.js.\n *\n * https://visjs.github.io/vis-network/docs/network/\n */\nexport class GraphHTML {\n public imports: boolean;\n public options: Record<string, unknown>;\n public nodes: Record<string, unknown>;\n public edges: unknown[];\n\n constructor (\n nodes: Record<string, unknown>,\n edges: unknown[],\n options: {\n imports?: boolean;\n [index: string]: unknown;\n } = {},\n ) {\n const {\n imports = true,\n } = options;\n\n this.imports = imports;\n this.nodes = nodes;\n this.edges = edges;\n\n this.options = {\n height: '500px',\n width: '100%',\n layout: {\n hierarchical: {\n enabled: true,\n nodeSpacing: 200,\n sortMethod: 'directed',\n },\n },\n interaction: {\n dragNodes: false,\n selectable: false,\n },\n physics: {\n enabled: false,\n },\n edges: {\n arrows: 'to',\n },\n nodes: {\n font: '20px monaco',\n shape: 'box',\n widthConstraint: {\n maximum: 300,\n },\n },\n ...(options || {}),\n };\n }\n\n toString (): string {\n const nodesJson = JSON.stringify(Object.values(this.nodes));\n const edgesJson = JSON.stringify(this.edges);\n const optionsJson = JSON.stringify(this.options);\n\n const importsHtml = this.imports\n ? `<script type=\"text/javascript\" src=\"https://unpkg.com/vis-data@latest/peer/umd/vis-data.min.js\"></script>\n <script type=\"text/javascript\" src=\"https://unpkg.com/vis-network@latest/peer/umd/vis-network.min.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://unpkg.com/vis-network/styles/vis-network.min.css\" />`\n : '';\n\n return `<div>\n <div id=\"sqlglot-lineage\"></div>\n ${importsHtml}\n <script type=\"text/javascript\">\n var nodes = new vis.DataSet(${nodesJson});\n nodes.forEach(row => {\n row[\"title\"] = new DOMParser().parseFromString(row[\"title\"], \"text/html\").body.childNodes[0];\n });\n\n new vis.Network(\n document.getElementById(\"sqlglot-lineage\"),\n {\n nodes: nodes,\n edges: new vis.DataSet(${edgesJson})\n },\n ${optionsJson}\n );\n </script>\n</div>`;\n }\n\n toHtml (): string {\n return this.toString();\n }\n}\n","import type {\n ExpressionOrString,\n} from './expressions';\nimport {\n Expression,\n WithExpr,\n SelectExpr, SetOperationExpr, AggFuncExpr,\n ColumnExpr, IdentifierExpr,\n SubqueryExpr,\n column,\n alias,\n JoinExpr,\n} from './expressions';\nimport {\n nameSequence,\n} from './helper';\nimport {\n assertIsInstanceOf, filterInstanceOf, id, isInstanceOf,\n} from './port_internals';\nimport {\n joinCondition,\n} from './optimizer';\n\n/**\n * Represents a query execution plan as a Directed Acyclic Graph (DAG) of Steps\n */\nexport class Plan {\n public expression: Expression;\n public root: Step | undefined;\n private _dag: Map<Step, Set<Step>> | undefined = undefined;\n\n constructor (expression: Expression) {\n // Ensuring we work on a copy to prevent mutation of the original AST\n this.expression = expression.copy();\n this.root = Step.fromExpression(this.expression);\n }\n\n /**\n * Generates or retrieves the DAG of steps\n */\n get dag (): Map<Step, Set<Step>> {\n if (this._dag) {\n return this._dag;\n }\n\n const dag = new Map<Step, Set<Step>>();\n const seen = new Set<Step>();\n\n const stack = [this.root];\n\n while (0 < stack.length) {\n const node = stack.pop()!;\n\n if (seen.has(node)) continue;\n\n seen.add(node);\n const dependencies = new Set<Step>();\n\n for (const dep of node.dependencies) {\n dependencies.add(dep);\n stack.push(dep);\n }\n\n dag.set(node, dependencies);\n }\n\n this._dag = dag;\n\n return this._dag;\n }\n\n /**\n * Returns an iterator over the leaf nodes (steps with no dependencies)\n */\n get leaves (): IterableIterator<Step> {\n const leafNodes: Step[] = [];\n\n for (const [\n node,\n deps,\n ] of this.dag.entries()) {\n if (deps.size === 0) {\n leafNodes.push(node);\n }\n }\n\n return leafNodes[Symbol.iterator]();\n }\n\n toString (): string {\n return `Plan\\n----\\n${this.root?.toString() ?? 'unnamed'}`;\n }\n}\n\n/**\n * Base class for an execution step in the query plan DAG\n */\nexport class Step {\n public name: string = '';\n public dependencies: Set<Step> = new Set();\n public dependents: Set<Step> = new Set();\n public projections: Expression[] = [];\n public limit: number = Infinity;\n public condition: Expression | undefined = undefined;\n\n // Intermediate state for builders\n public operands: Expression[] = [];\n public aggregations: Expression[] = [];\n\n static fromExpression (\n expression?: Expression,\n ctes: Map<string, Step> = new Map(),\n ): Step | undefined {\n if (!expression) return undefined;\n const unnested = expression.unnest();\n const with_ = unnested.getArgKey('with');\n\n // Handle CTEs\n if (isInstanceOf(with_, WithExpr)) {\n ctes = new Map(ctes);\n for (const cte of with_.args.expressions || []) {\n assertIsInstanceOf(cte.args.this, Expression);\n const step = Step.fromExpression(cte.args.this, ctes);\n\n if (step) {\n step.name = cte.alias;\n ctes.set(step.name, step);\n }\n }\n }\n\n const from = unnested.args.from;\n let step: Step | undefined;\n\n if (unnested instanceof SelectExpr && from instanceof Expression) {\n assertIsInstanceOf(from.args.this, Expression);\n step = Scan.fromExpression(from.args.this, ctes);\n } else if (unnested instanceof SetOperationExpr) {\n step = SetOperation.fromExpression(unnested, ctes);\n } else {\n step = new Scan();\n }\n\n const joins = filterInstanceOf(unnested.args.joins || [], JoinExpr);\n\n if (joins && 0 < joins.length) {\n const joinStep = Join.fromJoins(joins, ctes);\n\n if (step) {\n joinStep.name = step.name;\n joinStep.sourceName = step.name;\n joinStep.addDependency(step);\n }\n step = joinStep;\n }\n\n const projections: Expression[] = [];\n const operands = new Map<Expression, string>();\n const aggregations = new Map<Expression, undefined>();\n const nextOperandName = nameSequence('_a_');\n\n const extractAggOperands = (expr: Expression): boolean => {\n const aggFuncs = Array.from(expr.findAll(AggFuncExpr));\n\n if (0 < aggFuncs.length) {\n aggregations.set(expr, undefined);\n }\n\n for (const agg of aggFuncs) {\n for (const operand of agg.unnestOperands()) {\n if (operand instanceof ColumnExpr) continue;\n if (!operands.has(operand)) {\n operands.set(operand, nextOperandName());\n }\n operand.replace(new ColumnExpr({\n this: new IdentifierExpr({\n this: operands.get(operand),\n quoted: true,\n }),\n }));\n }\n }\n\n return 0 < aggFuncs.length;\n };\n\n const setOpsAndAggs = (target: Step) => {\n target.operands = Array.from(operands.entries()).map(\n ([\n expr,\n aliasExpr,\n ]) => alias(\n expr,\n aliasExpr,\n ),\n );\n target.aggregations = Array.from(aggregations.keys());\n };\n\n for (const e of unnested.args.expressions || []) {\n assertIsInstanceOf(e, Expression);\n if (e.find(AggFuncExpr)) {\n projections.push(column(\n {\n col: e.aliasOrName,\n table: step?.name,\n },\n {\n quoted: true,\n },\n ));\n extractAggOperands(e);\n } else {\n projections.push(e);\n }\n }\n\n const where = unnested.getArgKey('where');\n\n if (step && where instanceof Expression && where.args.this instanceof Expression) {\n step.condition = where.args.this;\n }\n\n const group = unnested.getArgKey('group');\n\n if (group || 0 < aggregations.size) {\n const aggregate = new Aggregate();\n\n if (step) {\n aggregate.source = step.name;\n aggregate.name = step.name;\n }\n\n const having = unnested.getArgKey('having');\n\n if (having instanceof Expression && isInstanceOf(having.args.this, 'string', Expression)) {\n if (extractAggOperands(alias(\n having.args.this,\n '_h',\n {\n quoted: true,\n },\n ))) {\n aggregate.condition = column(\n {\n col: '_h',\n table: step?.name,\n },\n {\n quoted: true,\n },\n );\n } else if (isInstanceOf(having.args.this, Expression)) {\n aggregate.condition = having.args.this;\n }\n }\n\n setOpsAndAggs(aggregate);\n\n const groupExprs = isInstanceOf(group, Expression)\n ? filterInstanceOf(group.args.expressions ?? [], Expression)\n : [];\n\n aggregate.group = Object.fromEntries(\n groupExprs.map((e, i) => [\n `_g${i}`,\n e,\n ]),\n );\n\n const intermediate = new Map<string, string>();\n\n Object.entries(aggregate.group).forEach(([\n k,\n v,\n ]) => {\n intermediate.set(v.sql(), k);\n if (v instanceof ColumnExpr) {\n intermediate.set(v.name, k);\n }\n });\n\n const lookupNode = (node: Expression): string | undefined =>\n intermediate.get(node.sql()) ?? (node instanceof ColumnExpr ? intermediate.get(node.name) : undefined);\n\n // Replace projections with group references\n for (const projection of projections) {\n for (const node of projection.walk()) {\n const name = lookupNode(node);\n\n if (name) {\n node.replace(column({\n col: name,\n table: step?.name,\n }, {\n quoted: true,\n }));\n }\n }\n }\n\n // Replace group references in the HAVING condition (non-aggregate)\n if (aggregate.condition) {\n for (const node of aggregate.condition.walk()) {\n const name = lookupNode(node);\n\n if (name) {\n node.replace(column({\n col: name,\n table: step?.name,\n }, {\n quoted: true,\n }));\n }\n }\n }\n\n aggregate.addDependency(step);\n step = aggregate;\n }\n\n const order = unnested.getArgKey('order');\n\n if (isInstanceOf(order, Expression)) {\n // If we have an aggregate step, extract any agg funcs in ORDER BY into operands\n if (step instanceof Aggregate) {\n const orderExprs = filterInstanceOf(order.args.expressions || [], Expression);\n\n for (let i = 0; i < orderExprs.length; i++) {\n const ordered = orderExprs[i];\n const orderThis = (ordered.args as Record<string, Expression | undefined>).this;\n\n if (orderThis && extractAggOperands(alias(orderThis, `_o_${i}`, {\n quoted: true,\n }))) {\n orderThis.replace(column({\n col: `_o_${i}`,\n table: step.name,\n }, {\n quoted: true,\n }));\n }\n }\n setOpsAndAggs(step);\n }\n\n const sort = new Sort();\n\n sort.name = step?.name ?? '';\n sort.key = filterInstanceOf(order.args.expressions || [], Expression);\n sort.addDependency(step);\n step = sort;\n }\n\n if (step) step.projections = projections;\n\n if (unnested instanceof SelectExpr && unnested.args.distinct) {\n const distinct = new Aggregate();\n\n distinct.source = step?.name;\n distinct.name = step?.name ?? '';\n distinct.group = Object.fromEntries(\n (projections.length\n ? projections\n : filterInstanceOf(unnested.args.expressions || [], Expression))\n .map((e) => [\n e.aliasOrName,\n column({\n col: e.aliasOrName,\n table: step?.name,\n }, {\n quoted: true,\n }),\n ]),\n );\n distinct.addDependency(step);\n step = distinct;\n }\n\n const limit = unnested.getArgKey('limit');\n\n if (step && isInstanceOf(limit, Expression)) {\n step.limit = parseInt(limit.text('expression'));\n }\n\n return step;\n }\n\n addDependency (dependency?: Step): void {\n if (!dependency) return;\n this.dependencies.add(dependency);\n dependency.dependents.add(this);\n }\n\n /**\n * Returns a string representation of the execution step\n */\n toString (): string {\n return this.toS();\n }\n\n /**\n * Recursive helper to build the formatted string tree.\n * @param level Indentation depth\n */\n toS (level: number = 0): string {\n const indent = ' '.repeat(level);\n const nested = `${indent} `;\n\n // Each subclass (Scan, Join, Aggregate) can provide specific context lines\n let context = this._toS(`${nested} `);\n\n if (0 < context.length) {\n context = [\n `${nested}Context:`,\n ...context,\n ];\n }\n\n const lines: string[] = [\n `${indent}- ${this.id}`,\n ...context,\n `${nested}Projections:`,\n ];\n\n for (const expression of this.projections) {\n lines.push(`${nested} - ${expression.sql()}`);\n }\n\n if (this.condition) {\n lines.push(`${nested}Condition: ${this.condition.sql()}`);\n }\n\n if (this.limit !== Infinity) {\n lines.push(`${nested}Limit: ${this.limit}`);\n }\n\n if (0 < this.dependencies.size) {\n lines.push(`${nested}Dependencies:`);\n for (const dependency of this.dependencies) {\n // Recursively call toS for each dependency with increased level\n lines.push(` ${dependency.toS(level + 1)}`);\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Property-like getter for the class name\n */\n get typeName (): string {\n return this.constructor.name;\n }\n\n /**\n * Unique identifier for the step in the output\n */\n get id (): string {\n const nameStr = this.name ? ` ${this.name}` : '';\n\n return `${this.typeName}:${nameStr} (${id(this)})`;\n }\n\n /**\n * Hook for subclasses to add extra descriptive lines (like Join conditions or Source tables)\n */\n _toS (_indent: string): string[] {\n return [];\n }\n}\n\n/**\n * Represents a leaf-level operation that reads from a table, subquery, or CTE\n */\nexport class Scan extends Step {\n public source: ExpressionOrString | undefined = undefined;\n\n static fromExpression (\n expression: Expression,\n ctes: Map<string, Step> = new Map(),\n ): Step | undefined {\n const table = expression;\n const alias = expression.aliasOrName;\n\n if (expression instanceof SubqueryExpr) {\n const innerTable = expression.args.this;\n const step = innerTable !== undefined ? Step.fromExpression(innerTable, ctes) : undefined;\n\n if (step) step.name = alias;\n\n return step;\n }\n\n const step = new Scan();\n\n step.name = alias;\n step.source = expression;\n\n // If the table name matches a CTE, we add that CTE's step as a dependency\n const tableName = table.name;\n\n if (ctes.has(tableName)) {\n step.addDependency(ctes.get(tableName));\n }\n\n return step;\n }\n\n override _toS (indent: string): string[] {\n const source = this.source instanceof Expression ? this.source.sql() : this.source ?? '-static-';\n\n return [`${indent}Source: ${source}`];\n }\n}\n\n/**\n * Represents a join operation between a source step and one or more join targets\n */\nexport class Join extends Step {\n public sourceName: string | undefined = undefined;\n public joins: Record<string, {\n side: string | undefined;\n joinKey: unknown[];\n sourceKey: unknown[];\n condition: Expression | undefined;\n }> = {};\n\n static fromJoins (\n joins: Iterable<JoinExpr>,\n ctes: Map<string, Step> = new Map(),\n ): Join {\n const step = new Join();\n\n for (const join of joins) {\n const {\n sourceKeys, joinKeys, on,\n } = joinCondition(join);\n\n step.joins[join.aliasOrName] = {\n side: join.side,\n joinKey: joinKeys || [],\n sourceKey: sourceKeys || [],\n condition: on || undefined,\n };\n\n // Each join target becomes a new dependency branch via a Scan\n if (join.args.this !== undefined) step.addDependency(Scan.fromExpression(join.args.this, ctes));\n }\n\n return step;\n }\n\n override _toS (indent: string): string[] {\n const lines = [`${indent}Source: ${this.sourceName || this.name}`];\n\n for (const [\n name,\n join,\n ] of Object.entries(this.joins)) {\n lines.push(`${indent}${name}: ${join.side || 'INNER'}`);\n\n const joinKeyStr = join.joinKey.map((key) => String(key)).join(', ');\n\n if (joinKeyStr) {\n lines.push(`${indent}Key: ${joinKeyStr}`);\n }\n\n if (join.condition) {\n lines.push(`${indent}On: ${join.condition.sql()}`);\n }\n }\n\n return lines;\n }\n}\n\n/**\n * Represents an aggregation step (GROUP BY / HAVING)\n */\nexport class Aggregate extends Step {\n public aggregations: Expression[] = [];\n public operands: Expression[] = [];\n public group: Record<string, Expression> = {};\n public source: ExpressionOrString | undefined = undefined;\n\n constructor () {\n super();\n }\n\n override _toS (indent: string): string[] {\n const lines: string[] = [`${indent}Aggregations:`];\n\n for (const expression of this.aggregations) {\n lines.push(`${indent} - ${expression.sql()}`);\n }\n\n if (0 < Object.keys(this.group).length) {\n lines.push(`${indent}Group:`);\n for (const expression of Object.values(this.group)) {\n lines.push(`${indent} - ${expression.sql()}`);\n }\n }\n\n if (this.condition) {\n lines.push(`${indent}Having:`);\n lines.push(`${indent} - ${this.condition.sql()}`);\n }\n\n if (0 < this.operands.length) {\n lines.push(`${indent}Operands:`);\n for (const expression of this.operands) {\n lines.push(`${indent} - ${expression.sql()}`);\n }\n }\n\n return lines;\n }\n}\n\n/**\n * Represents an ordering step (ORDER BY)\n */\nexport class Sort extends Step {\n public key: Expression[] = [];\n\n constructor () {\n super();\n }\n\n override _toS (indent: string): string[] {\n const lines: string[] = [`${indent}Key:`];\n\n for (const expression of this.key) {\n lines.push(`${indent} - ${expression.sql()}`);\n }\n\n return lines;\n }\n}\n\n/**\n * Represents set operations like UNION, INTERSECT, and EXCEPT\n */\nexport class SetOperation extends Step {\n public op: typeof SetOperationExpr; // Constructor for the specific SetOperation type\n public left: string | undefined;\n public right: string | undefined;\n public distinct: boolean;\n\n constructor (\n op: typeof SetOperationExpr,\n left: string | undefined,\n right: string | undefined,\n options: {\n distinct?: boolean;\n } = {},\n ) {\n const {\n distinct = false,\n } = options;\n\n super();\n this.op = op;\n this.left = left;\n this.right = right;\n this.distinct = distinct;\n }\n\n static fromExpression (\n expression?: SetOperationExpr,\n ctes: Map<string, Step> = new Map(),\n ): SetOperation | undefined {\n if (!(expression instanceof SetOperationExpr)) {\n throw new Error('Expected SetOperation expression');\n }\n\n const left = expression.args.this !== undefined ? Step.fromExpression(expression.args.this, ctes) : undefined;\n\n if (left) left.name = left.name || 'left';\n\n const right = expression.args.expression !== undefined ? Step.fromExpression(expression.args.expression, ctes) : undefined;\n\n if (right) right.name = right.name || 'right';\n\n const step = new SetOperation(\n expression._constructor as typeof SetOperationExpr,\n left?.name,\n right?.name,\n {\n distinct: Boolean(expression.args.distinct),\n },\n );\n\n if (left) step.addDependency(left);\n if (right) step.addDependency(right);\n\n const limit = expression.args.limit;\n\n if (isInstanceOf(limit, Expression)) {\n step.limit = parseInt(limit.text('expression'));\n }\n\n return step;\n }\n\n override _toS (indent: string): string[] {\n const lines: string[] = [];\n\n if (this.distinct) {\n lines.push(`${indent}Distinct: ${this.distinct}`);\n }\n\n return lines;\n }\n\n get typeName (): string {\n return this.op.name;\n }\n}\n","import type {\n DialectType,\n} from '../dialects/dialect';\nimport {\n objectDepth,\n} from '../helper';\nimport {\n MappingSchema, normalizeName,\n} from '../schema';\n\nexport class Table {\n public columns: string[];\n public columnRange?: ColumnRange;\n public reader: RowReader;\n public rows: unknown[][];\n public rangeReader: RangeReader;\n\n constructor (\n columns: Iterable<string>,\n rows: unknown[][] = [],\n columnRange?: ColumnRange,\n ) {\n this.columns = Array.from(columns);\n this.columnRange = columnRange;\n this.reader = new RowReader(this.columns, this.columnRange);\n this.rows = rows;\n\n if (0 < this.rows.length) {\n if (this.rows[0].length !== this.columns.length) {\n throw new Error('Row length does not match column length.');\n }\n }\n\n this.rangeReader = new RangeReader(this);\n }\n\n addColumns (...columns: string[]): void {\n this.columns.push(...columns);\n if (this.columnRange) {\n this.columnRange = {\n start: this.columnRange.start,\n stop: this.columnRange.stop + columns.length,\n };\n }\n this.reader = new RowReader(this.columns, this.columnRange);\n }\n\n append (row: unknown[]): void {\n if (row.length !== this.columns.length) {\n throw new Error('Row length does not match column length.');\n }\n this.rows.push(row);\n }\n\n pop (): void {\n this.rows.pop();\n }\n\n toJslist (): Record<string, unknown>[] {\n return this.rows.map((row) => {\n const obj: Record<string, unknown> = {};\n\n this.columns.forEach((col, i) => {\n obj[col] = row[i];\n });\n\n return obj;\n });\n }\n\n get width (): number {\n return this.columns.length;\n }\n\n get length (): number {\n return this.rows.length;\n }\n\n * [Symbol.iterator] (): Generator<RowReader> {\n for (let i = 0; i < this.rows.length; i++) {\n yield this.get(i);\n }\n }\n\n get (index: number): RowReader {\n this.reader.row = this.rows[index];\n\n return this.reader;\n }\n\n toString (): string {\n const cols = this.columns.filter(\n (_, i) => !this.columnRange || (this.columnRange.start <= i && i < this.columnRange.stop),\n );\n\n const widths: Record<string, number> = {};\n\n cols.forEach((col) => {\n widths[col] = col.length;\n });\n\n const lines = [cols.join(' ')];\n\n for (let i = 0; i < this.length; i++) {\n if (10 < i) break;\n\n const reader = this.get(i);\n const rowStr = cols\n .map((col) => {\n const valStr = String(reader.row[reader.columns[col]] ?? '');\n\n return valStr.padStart(widths[col], ' ').substring(0, widths[col]);\n })\n .join(' ');\n\n lines.push(rowStr);\n }\n\n return lines.join('\\n');\n }\n}\n\nexport class TableIter implements Iterator<RowReader> {\n public table: Table;\n public index: number = -1;\n\n constructor (table: Table) {\n this.table = table;\n }\n\n [Symbol.iterator] () {\n return this;\n }\n\n next (): IteratorResult<RowReader> {\n this.index++;\n if (this.index < this.table.length) {\n return {\n value: this.table.get(this.index),\n done: false,\n };\n }\n\n return {\n value: undefined,\n done: true,\n };\n }\n}\n\nexport class Tables extends MappingSchema {\n override depth (): number {\n return objectDepth(this.mapping);\n }\n}\n\nexport function ensureTables (d?: Record<string, unknown>, dialect?: DialectType): Tables {\n return new Tables(_ensureTables(d, dialect), {\n normalize: false,\n dialect,\n });\n}\n\nfunction _ensureTables (d?: unknown, dialect?: DialectType): Record<string, unknown> {\n if (typeof d !== 'object' || !d || Object.keys(d).length === 0) {\n return {};\n }\n\n const depth = objectDepth(d);\n\n if (1 < depth) {\n const nestedResult: Record<string, unknown> = {};\n\n for (const [\n k,\n v,\n ] of Object.entries(d)) {\n const normalizedName = normalizeName(k, {\n dialect,\n isTable: true,\n }).name;\n\n nestedResult[normalizedName] = _ensureTables(v, dialect);\n }\n\n return nestedResult;\n }\n\n const result: Record<string, unknown> = {};\n\n for (const [\n rawTableName,\n tableData,\n ] of Object.entries(d)) {\n const tableName = normalizeName(rawTableName, {\n dialect,\n }).name;\n\n if (tableData instanceof Table) {\n result[tableName] = tableData;\n } else {\n // Normalize raw object arrays into Table structures\n const normalizedTableData = tableData.map((row: Record<string, unknown>) => {\n const newRow: Record<string, unknown> = {};\n\n for (const [\n columnName,\n value,\n ] of Object.entries(row)) {\n newRow[normalizeName(columnName, {\n dialect,\n }).name] = value;\n }\n\n return newRow;\n });\n\n const columnNames = 0 < normalizedTableData.length\n ? Object.keys(normalizedTableData[0])\n : [];\n const rows = normalizedTableData.map((row: Record<string, unknown>) => columnNames.map((name) => row[name]));\n\n result[tableName] = new Table(columnNames, rows);\n }\n }\n\n return result;\n}\n\nexport interface ColumnRange {\n start: number;\n stop: number;\n}\n\n/**\n * Reads a specific column for the current row.\n * Wrapped in a Proxy to allow dynamic column access like `reader.column_name`\n */\nexport class RowReader {\n [column: string]: unknown;\n public columns: Record<string, number> = {};\n public row: unknown[] = [];\n\n constructor (columns: string[], columnRange?: ColumnRange) {\n columns.forEach((column, i) => {\n if (!columnRange || (columnRange.start <= i && i < columnRange.stop)) {\n this.columns[column] = i;\n }\n });\n\n return new Proxy(this as any, {\n get (target, prop: string | symbol) {\n if (prop in target) return target[prop];\n if (typeof prop === 'string' && prop in target.columns && target.row) {\n return target.row[target.columns[prop]];\n }\n\n return undefined;\n },\n });\n }\n}\n\n/**\n * Reads a range of rows for a specific column, returning an iterator.\n * Wrapped in a Proxy to allow dynamic column access like `rangeReader.column_name`\n */\nexport class RangeReader {\n public table: Table;\n public range: ColumnRange = {\n start: 0,\n stop: 0,\n };\n\n constructor (table: Table) {\n this.table = table;\n\n return new Proxy(this as any, {\n get (target, prop: string | symbol) {\n if (prop in target) return target[prop];\n if (typeof prop === 'string') {\n return (function* () {\n for (let i = target.range.start; i < target.range.stop; i++) {\n yield target.table.rows[i][target.table.columns.indexOf(prop)];\n }\n })();\n }\n\n return undefined;\n },\n });\n }\n\n get length (): number {\n return Math.max(0, this.range.stop - this.range.start);\n }\n}\n","/**\n * sqlingo\n * A JavaScript port of SQLGlot - SQL parser, transpiler, optimizer, and engine\n *\n * Based on SQLGlot by Toby Mao (https://github.com/tobymao/sqlglot)\n */\n\nimport packageJson from '../package.json';\nimport {\n ErrorLevel, SqlglotError, ParseError, TokenError, UnsupportedError,\n} from './errors';\nimport type {\n Token,\n} from './tokens';\nimport {\n TokenType, Tokenizer,\n} from './tokens';\nimport type {\n ParseOptions,\n} from './parser';\nimport {\n Parser, parse, parseOne, parseNewlineDelimited,\n} from './parser';\nimport type {\n GeneratorOptions, TranspileOptions,\n} from './generator';\nimport {\n Generator, generate,\n} from './generator';\nimport {\n Schema, MappingSchema,\n} from './schema';\nimport {\n Dialect, type Dialects, type DialectType,\n} from './dialects/dialect';\nimport {\n diff,\n} from './diff';\nimport {\n lineage,\n} from './lineage';\nimport {\n optimize,\n} from './optimizer/optimizer';\nimport {\n execute,\n} from './executor';\n\nexport * from './expressions';\n\nexport {\n dump, load,\n} from './serde';\n\nexport const version = packageJson.version;\n\nexport {\n ErrorLevel, SqlglotError, ParseError, TokenError, UnsupportedError,\n};\nexport type {\n Token,\n};\nexport {\n TokenType, Tokenizer,\n};\nexport type {\n ParseOptions,\n};\nexport {\n Parser, parse, parseOne, parseNewlineDelimited,\n};\nexport type {\n GeneratorOptions, TranspileOptions,\n};\nexport {\n Generator, generate,\n};\nexport {\n Schema, MappingSchema,\n};\nexport {\n Dialect, type Dialects, type DialectType,\n};\nexport {\n diff,\n};\nexport {\n lineage,\n};\nexport {\n optimize,\n};\nexport {\n execute,\n};\n\nexport let pretty = false;\n\nexport function setPretty (value: boolean): void {\n pretty = value;\n}\n\nexport function tokenize (sql: string, read?: DialectType, dialect?: DialectType): Token[] {\n return Dialect.getOrRaise(read ?? dialect).tokenize(sql);\n}\n\nexport function transpile (\n sql: string,\n opts: TranspileOptions = {},\n): string[] {\n const {\n read, dialect, write, identity = true, errorLevel, ...rest\n } = opts;\n const writeDialect = identity ? (write ?? read ?? dialect) : write;\n const writeDial = Dialect.getOrRaise(writeDialect);\n\n return parse(sql, {\n read: read ?? dialect,\n errorLevel,\n ...rest,\n }).map((expression) =>\n expression\n ? writeDial.generate(expression, {\n copy: false,\n ...rest,\n })\n : '');\n}\n"]}