codecop 0.1.0__py3-none-any.whl

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 (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,296 @@
1
+ """Which database a project talks to, from evidence outside any one statement.
2
+
3
+ A statement whose text and call site say nothing about the engine (`SELECT id FROM users WHERE id = ?`)
4
+ still runs on some database. This module collects what the repository says about that: the database
5
+ drivers it depends on and imports, the images its compose files start, the connection URLs in its
6
+ configuration. When that evidence names one engine, discovery uses it as the project's engine for the
7
+ statements nothing else decides, and records the basis as `inferred`. A project that sets
8
+ `[discover] default_engine` in codecop.toml (or `--default-engine`) gets basis `default` instead.
9
+ Neither is ever a per-statement guess, and the inventory says how many sites got their engine this way.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import re
16
+ from collections import defaultdict
17
+
18
+ # Engines that run inside the process: a project that also has a server database uses these for tests,
19
+ # local development or a cache, so they do not make the project's engine unclear.
20
+ EMBEDDED = {"sqlite", "h2"}
21
+ # With several drivers, the schema statements decide when at least this many name an engine by their syntax
22
+ # and at least this share of them name the same one. Settings: `[discover] min_migration_statements`,
23
+ # `migration_share`.
24
+ MIN_MIGRATION_STATEMENTS = 5
25
+ MIGRATION_SHARE = 0.95
26
+ KNOWN = ("postgres", "clickhouse", "mysql", "sqlite", "mssql", "oracle", "h2")
27
+
28
+ # Dependency manifests: the driver a project ships with.
29
+ MANIFEST = re.compile(
30
+ r"(^|/)(go\.mod|requirements[^/]*\.(?:txt|in)|pyproject\.toml|setup\.py|setup\.cfg|Pipfile|Cargo\.toml|pom\.xml|"
31
+ r"build\.gradle(?:\.kts)?|[^/]*\.gradle(?:\.kts)?|libs\.versions\.toml|constraints[^/]*\.txt)$")
32
+ DRIVERS = {
33
+ "postgres": re.compile(
34
+ r"github\.com/lib/pq\b|github\.com/jackc/pgx|gorm\.io/driver/postgres|bun/driver/pgdriver|\bpsycopg|\basyncpg\b|\bpg8000\b|"
35
+ r"org\.postgresql|<artifactId>postgresql</artifactId>|\btokio-postgres\b|\bdeadpool-postgres\b|"
36
+ r"\b(?:sqlx|diesel|sea-orm|diesel-async)\b[^\n]*\bpostgres|\bpostgres\s*=\s*[\"{]|\bpgdialect\b", re.I),
37
+ "mysql": re.compile(
38
+ r"github\.com/go-sql-driver/mysql|gorm\.io/driver/mysql|\bpymysql\b|\bmysqlclient\b|\bmysql-connector|\baiomysql\b|"
39
+ r"mariadb-java-client|com\.mysql|<artifactId>mysql-connector|\b(?:sqlx|diesel|sea-orm)\b[^\n]*\bmysql|\bmysql_async\b", re.I),
40
+ "clickhouse": re.compile(
41
+ r"github\.com/ClickHouse/(?:clickhouse-go|ch-go)|gorm\.io/driver/clickhouse|\bclickhouse[-_]connect\b|\bclickhouse[-_]driver\b|"
42
+ r"clickhouse-jdbc|com\.clickhouse|ru\.yandex\.clickhouse|\bclickhouse\s*=\s*[\"{]|\bclickhouse-rs\b|\bklickhouse\b", re.I),
43
+ "sqlite": re.compile(
44
+ r"github\.com/mattn/go-sqlite3|modernc\.org/sqlite|gorm\.io/driver/sqlite|\baiosqlite\b|\brusqlite\b|sqlite-jdbc|"
45
+ r"\b(?:sqlx|diesel|sea-orm)\b[^\n]*\bsqlite", re.I),
46
+ "mssql": re.compile(r"go-mssqldb|mssql-jdbc|\bpymssql\b|\bpyodbc\b|com\.microsoft\.sqlserver|\btiberius\b", re.I),
47
+ "oracle": re.compile(r"\bojdbc\d*\b|\bcx_Oracle\b|\boracledb\b|github\.com/godror/godror|com\.oracle\.database", re.I),
48
+ "h2": re.compile(r"com\.h2database", re.I),
49
+ }
50
+ # Driver imports in source code, by language.
51
+ IMPORTS = {
52
+ ".py": [
53
+ ("postgres", re.compile(r"^\s*(?:import|from)\s+(?:psycopg2?|psycopg_pool|asyncpg|pg8000)\b", re.M)),
54
+ ("mysql", re.compile(r"^\s*(?:import|from)\s+(?:pymysql|MySQLdb|aiomysql|mysql\.connector)\b", re.M)),
55
+ ("clickhouse", re.compile(r"^\s*(?:import|from)\s+(?:clickhouse_connect|clickhouse_driver|chdb)\b", re.M)),
56
+ ("sqlite", re.compile(r"^\s*(?:import|from)\s+(?:sqlite3|aiosqlite)\b", re.M)),
57
+ ("mssql", re.compile(r"^\s*(?:import|from)\s+(?:pymssql|pyodbc)\b", re.M)),
58
+ ("oracle", re.compile(r"^\s*(?:import|from)\s+(?:cx_Oracle|oracledb)\b", re.M)),
59
+ ],
60
+ ".go": [
61
+ ("postgres", re.compile(r'"github\.com/(?:lib/pq|jackc/pgx[^"]*|jackc/pgconn|uptrace/bun/driver/pgdriver)"|"gorm\.io/driver/postgres"')),
62
+ ("mysql", re.compile(r'"github\.com/go-sql-driver/mysql"|"gorm\.io/driver/mysql"')),
63
+ ("clickhouse", re.compile(r'"github\.com/ClickHouse/(?:clickhouse-go|ch-go)[^"]*"|"gorm\.io/driver/clickhouse"')),
64
+ ("sqlite", re.compile(r'"github\.com/mattn/go-sqlite3"|"modernc\.org/sqlite"|"gorm\.io/driver/sqlite"')),
65
+ ("mssql", re.compile(r'"github\.com/(?:denisenkom|microsoft)/go-mssqldb"')),
66
+ ],
67
+ ".java": [
68
+ ("postgres", re.compile(r"^\s*import\s+org\.postgresql\.", re.M)),
69
+ ("mysql", re.compile(r"^\s*import\s+(?:com\.mysql|org\.mariadb)\.", re.M)),
70
+ ("clickhouse", re.compile(r"^\s*import\s+(?:com\.clickhouse|ru\.yandex\.clickhouse)\.", re.M)),
71
+ ("sqlite", re.compile(r"^\s*import\s+org\.sqlite\.", re.M)),
72
+ ("mssql", re.compile(r"^\s*import\s+com\.microsoft\.sqlserver\.", re.M)),
73
+ ("oracle", re.compile(r"^\s*import\s+oracle\.jdbc\.", re.M)),
74
+ ("h2", re.compile(r"^\s*import\s+org\.h2\.", re.M)),
75
+ ],
76
+ ".rs": [
77
+ ("postgres", re.compile(r"\b(?:tokio_postgres|deadpool_postgres|sqlx::(?:postgres|Postgres|PgPool)|diesel::pg|sea_orm::DbBackend::Postgres)\b")),
78
+ ("mysql", re.compile(r"\b(?:mysql_async|sqlx::(?:mysql|MySql|MySqlPool)|diesel::mysql)\b")),
79
+ ("clickhouse", re.compile(r"^\s*use\s+(?:clickhouse|klickhouse|clickhouse_rs)\b", re.M)),
80
+ ("sqlite", re.compile(r"\b(?:rusqlite|sqlx::(?:sqlite|Sqlite|SqlitePool)|diesel::sqlite)\b")),
81
+ ],
82
+ }
83
+ # Services a compose file or Dockerfile starts.
84
+ COMPOSE_FILE = re.compile(r"(^|/)(docker-compose[^/]*\.ya?ml|compose[^/]*\.ya?ml|Dockerfile[^/]*)$")
85
+ IMAGES = [
86
+ ("postgres", re.compile(r"(?:image:\s*|FROM\s+)[\"']?(?:[\w.-]+/)*(?:postgres|postgresql|postgis|timescaledb(?:-ha)?|pgvector)[:@\"'\s]", re.I)),
87
+ ("mysql", re.compile(r"(?:image:\s*|FROM\s+)[\"']?(?:[\w.-]+/)*(?:mysql|mariadb|percona)[:@\"'\s]", re.I)),
88
+ ("clickhouse", re.compile(r"(?:image:\s*|FROM\s+)[\"']?(?:[\w.-]+/)*clickhouse(?:-server)?[:@\"'\s]", re.I)),
89
+ ("mssql", re.compile(r"(?:image:\s*|FROM\s+)[\"']?mcr\.microsoft\.com/mssql", re.I)),
90
+ ]
91
+ # Connection settings in configuration and code.
92
+ CONFIG_EXTS = {".py", ".go", ".rs", ".java", ".yml", ".yaml", ".toml", ".properties", ".conf", ".ini", ".cfg", ".kt"}
93
+ URLS = [
94
+ ("postgres", re.compile(r"\bpostgres(?:ql)?(?:\+\w+)?://|jdbc:postgresql:|django\.db\.backends\.postgresql|django\.contrib\.gis\.db\.backends\.postgis")),
95
+ ("mysql", re.compile(r"\bmysql(?:\+\w+)?://|jdbc:(?:mysql|mariadb):|django\.db\.backends\.mysql")),
96
+ ("clickhouse", re.compile(r"\bclickhouse(?:\+\w+)?://|jdbc:(?:clickhouse|ch):")),
97
+ ("sqlite", re.compile(r"\bsqlite(?:\+\w+)?://|jdbc:sqlite:|django\.db\.backends\.sqlite3")),
98
+ ("mssql", re.compile(r"jdbc:sqlserver:|\bmssql(?:\+\w+)?://|\bsqlserver://")),
99
+ ("oracle", re.compile(r"jdbc:oracle:|django\.db\.backends\.oracle")),
100
+ ("h2", re.compile(r"jdbc:h2:")),
101
+ ]
102
+ URL_HINT = re.compile(r"://|jdbc:|django\.db\.backends|django\.contrib\.gis")
103
+ # Services a CI definition starts for the project's own test jobs.
104
+ CI_FILE = re.compile(r"(^|/)(\.github/workflows/[^/]+\.ya?ml|\.gitlab-ci\.ya?ml|\.circleci/config\.ya?ml|\.drone\.ya?ml|"
105
+ r"\.woodpecker(?:/[^/]+)?\.ya?ml|azure-pipelines\.ya?ml|bitbucket-pipelines\.ya?ml)$")
106
+ # What an ORM or query builder is told to talk to: its dialect setting, the driver name it opens, its dialect import.
107
+ _ORM_NAMES = {
108
+ "postgres": r"postgres(?:ql)?|pgsql|pgx|PostgreSQL\w*|Postgres\w*|Cockroach\w*",
109
+ "mysql": r"mysql|mariadb|MySQL\w*|MariaDB\w*",
110
+ "sqlite": r"sqlite3?|SQLite\w*",
111
+ "mssql": r"mssql|sqlserver|SQLServer\w*",
112
+ "oracle": r"oracle|Oracle\w*",
113
+ "h2": r"h2|H2\w*",
114
+ "clickhouse": r"clickhouse|ClickHouse\w*",
115
+ }
116
+ _ORM_SHAPES = (
117
+ # Hibernate / Spring / Quarkus / Micronaut: the dialect class or the database kind
118
+ r"(?:hibernate\.dialect|database-platform|databasePlatform|db-kind|spring\.jpa\.database|jpa\.database)[\"']?\s*[=:>]\s*[\"']?(?:[\w.]*\.)?(?:{n})(?:Dialect)?\b",
119
+ r"\borg\.hibernate\.dialect\.(?:{n})Dialect\b",
120
+ r"\bSQLDialect\.(?:{n})\b", # jOOQ
121
+ # Go: the driver name an ORM or database/sql opens
122
+ r"\b(?:xorm\.NewEngine|sql\.Open|sqlx\.(?:Open|Connect|MustConnect)|gorm\.Open|ent\.Open)\(\s*(?:\"(?:{n})\"|(?:{n})\.(?:Open|New)\b)",
123
+ r"\bcreate_(?:async_)?engine\(\s*f?[\"'](?:{n})(?:\+\w+)?://", # SQLAlchemy
124
+ r"\b(?:sql_alchemy_conn|sqlalchemy\.url|SQLALCHEMY_DATABASE_URI)[\"']?\s*[=:]\s*[\"']?(?:{n})(?:\+\w+)?://",
125
+ r"\b(?:dialect|client)\s*:\s*[\"'](?:{n})[\"']", # Drizzle, Knex, Sequelize options
126
+ r"\bnew\s+(?:{n})Dialect\(", # Kysely
127
+ )
128
+ ORM_CONFIG = [(engine, re.compile("|".join(shape.replace("{n}", names) for shape in _ORM_SHAPES)))
129
+ for engine, names in _ORM_NAMES.items()]
130
+ ORM_HINT = re.compile(r"[Dd]ialect|database-platform|databasePlatform|db-kind|jpa\.database|NewEngine\(|\.Open\(|\.Connect\(|"
131
+ r"create_(?:async_)?engine\(|sql_alchemy_conn|sqlalchemy\.url|SQLALCHEMY_DATABASE_URI|\bclient\s*:")
132
+ ORM_EXTS = CONFIG_EXTS | {".ts", ".js", ".xml", ".kts", ".gradle"}
133
+
134
+
135
+ class Evidence:
136
+ """What the repository says about its databases: engine -> source -> the files that say it."""
137
+
138
+ SOURCES = ("driver", "import", "compose", "config", "ci", "orm")
139
+
140
+ def __init__(self) -> None:
141
+ self.found: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list))
142
+
143
+ def note(self, engine: str, source: str, rel: str) -> None:
144
+ files = self.found[engine][source]
145
+ if rel not in files:
146
+ files.append(rel)
147
+
148
+ def scan(self, rel: str, text: str, is_test: bool) -> None:
149
+ """Read one text file for evidence. Test code is skipped: a test suite brings its own databases."""
150
+ if is_test:
151
+ return
152
+ ext = os.path.splitext(rel)[1]
153
+ if MANIFEST.search(rel):
154
+ if rel.endswith("go.mod"): # a driver another module pulls in is not one this project uses
155
+ text = "\n".join(line for line in text.split("\n") if "// indirect" not in line)
156
+ for engine, rx in DRIVERS.items():
157
+ if rx.search(text):
158
+ self.note(engine, "driver", rel)
159
+ for engine, rx in IMPORTS.get(ext, ()):
160
+ if rx.search(text):
161
+ self.note(engine, "import", rel)
162
+ if COMPOSE_FILE.search(rel):
163
+ for engine, rx in IMAGES:
164
+ if rx.search(text):
165
+ self.note(engine, "compose", rel)
166
+ if ext in CONFIG_EXTS and URL_HINT.search(text):
167
+ for engine, rx in URLS:
168
+ if rx.search(text):
169
+ self.note(engine, "config", rel)
170
+ if CI_FILE.search(rel):
171
+ for engine, rx in IMAGES:
172
+ if rx.search(text):
173
+ self.note(engine, "ci", rel)
174
+ if ext in ORM_EXTS and ORM_HINT.search(text):
175
+ for engine, rx in ORM_CONFIG:
176
+ if rx.search(text):
177
+ self.note(engine, "orm", rel)
178
+
179
+ def engines(self, *sources: str) -> set[str]:
180
+ return {e for e, by in self.found.items() if any(by.get(s) for s in sources)}
181
+
182
+ def to_dict(self, sample: int = 5) -> dict:
183
+ return {e: {s: {"files": len(f), "examples": f[:sample]} for s, f in sorted(by.items())}
184
+ for e, by in sorted(self.found.items())}
185
+
186
+
187
+ # An embedded engine is a store of its own, not the test or fallback database, when the application leans on
188
+ # it: at least this share of the application statements with direct engine evidence are written for it, and
189
+ # at least this share of the source files that import a database driver import its driver. A setting:
190
+ # `[discover] embedded_store_share`.
191
+ EMBEDDED_STORE_SHARE = 0.2
192
+
193
+
194
+ def _servers(engines: set[str], usage: dict[str, int] | None = None, evidence: "Evidence | None" = None) -> set[str]:
195
+ """Server engines when there are any: an embedded engine next to one is the test or fallback database,
196
+ unless the application's own statements and imports lean on it."""
197
+ total = sum((usage or {}).values())
198
+ real = {e for e in engines & EMBEDDED if total and (usage or {}).get(e, 0) >= total * EMBEDDED_STORE_SHARE}
199
+ if evidence is not None and real:
200
+ importing = {e: len(by.get("import") or ()) for e, by in evidence.found.items()}
201
+ files = sum(importing.values())
202
+ real = {e for e in real if files and importing.get(e, 0) >= files * EMBEDDED_STORE_SHARE}
203
+ servers = (engines - EMBEDDED) | real
204
+ return servers or engines
205
+
206
+
207
+ def stores(evidence: Evidence, usage: dict[str, int] | None = None) -> set[str]:
208
+ """The engines the project's drivers say it keeps data in."""
209
+ return _servers(evidence.engines("driver", "import"), usage, evidence)
210
+
211
+
212
+ def infer(evidence: Evidence, migrations: dict[str, int] | None = None, usage: dict[str, int] | None = None) -> tuple[str, str]:
213
+ """(engine, reason) when the evidence names one engine, else ("", why not).
214
+
215
+ Drivers decide: what the project depends on or imports is what it can talk to. Compose files and
216
+ connection settings only count when there is no driver evidence at all. With several drivers, the
217
+ dialect of the project's own schema statements settles it when they are all written for one of them
218
+ (`migrations`: engine -> DDL and .sql statements whose syntax names it). Never with ClickHouse among
219
+ the drivers: such a project has two stores, and ClickHouse DDL is the only kind that always shows."""
220
+ drivers = stores(evidence, usage)
221
+ if len(drivers) > 1 and "clickhouse" not in drivers and migrations:
222
+ total = sum(migrations.values())
223
+ engine, n = max(migrations.items(), key=lambda kv: kv[1])
224
+ if engine in drivers and n >= MIN_MIGRATION_STATEMENTS and n >= total * MIGRATION_SHARE:
225
+ return engine, (f"several database drivers ({', '.join(sorted(drivers))}), and the schema statements are "
226
+ f"written for {engine} ({n} of {total} with dialect syntax)")
227
+ if len(drivers) == 1:
228
+ engine = next(iter(drivers))
229
+ embedded = sorted(evidence.engines("driver", "import") - drivers)
230
+ files = (evidence.found[engine].get("driver") or evidence.found[engine].get("import") or [])[:2]
231
+ reason = f"the only server database driver is {engine} ({', '.join(files)})"
232
+ if embedded:
233
+ reason += f"; {', '.join(embedded)} is embedded and taken as the test or local store"
234
+ return engine, reason
235
+ if len(drivers) > 1:
236
+ return "", ("several database drivers: " + ", ".join(sorted(drivers))
237
+ + ". Set default_engine under [discover] in codecop.toml, or pass --default-engine, to choose")
238
+ hints = _servers(evidence.engines("compose", "config"))
239
+ if len(hints) == 1:
240
+ engine = next(iter(hints))
241
+ by = evidence.found[engine]
242
+ files = (by.get("compose") or by.get("config") or [])[:2]
243
+ return engine, f"no driver found; compose files and connection settings only name {engine} ({', '.join(files)})"
244
+ if hints:
245
+ return "", "no driver found, and compose files and connection settings name several engines: " + ", ".join(sorted(hints))
246
+ return "", "no database driver, compose service or connection setting found"
247
+
248
+
249
+ # ---- a project that supports several engines with one code base --------------------------------------------
250
+ # The evidence that says which engine a project itself runs on by default, in the order it is reported.
251
+ CHOICE_SOURCES = ("orm", "config", "compose", "ci")
252
+ # Engines the rank stage can examine: among engines the evidence does not tell apart, one of these is taken.
253
+ RANKED = ("postgres", "clickhouse")
254
+ # Libraries that write SQL for whatever connection they are handed, ClickHouse included: in a project with
255
+ # ClickHouse and another store their statements are not given to the other store.
256
+ BUILDERS = {"squirrel", "sqlbuilder", "goqu", "kysely", "knex", "bun"}
257
+
258
+
259
+ def choose(evidence: Evidence, usage: dict[str, int] | None = None) -> dict:
260
+ """The engine to read portable statements as in a project whose drivers name several engines.
261
+
262
+ A code base that ships drivers for PostgreSQL, MySQL and SQLite sends one statement to whichever is
263
+ configured, so a statement with no dialect of its own is valid on each of them. The rule, in order:
264
+ 1. the candidates are the server engines among the project's drivers (an embedded engine only when the
265
+ application leans on it), without ClickHouse: that is a second store, not an alternative;
266
+ 2. each candidate is scored by the files outside tests that favour it: ORM and builder settings (`orm`),
267
+ connection settings (`config`), compose services (`compose`) and CI services (`ci`);
268
+ 3. the highest score wins; among equals an engine the rank stage examines (postgres) wins, then the
269
+ first by name.
270
+ Returns {engine, alternatives, scores, reason, rule}; engine is "" when there is no candidate. `rule` is
271
+ only (one candidate) | evidence | tie."""
272
+ candidates = sorted(stores(evidence, usage) - {"clickhouse"})
273
+ if not candidates:
274
+ return {"engine": "", "alternatives": [], "scores": {}, "reason": "no server database driver found", "rule": ""}
275
+ scores = {e: {s: len(evidence.found[e].get(s) or ()) for s in CHOICE_SOURCES if evidence.found[e].get(s)} for e in candidates}
276
+ total = {e: sum(by.values()) for e, by in scores.items()}
277
+ # an embedded engine the application leans on is listed as an alternative, and is taken only when there is no server engine
278
+ pool = [e for e in candidates if e not in EMBEDDED] or candidates
279
+ best = min(pool, key=lambda e: (-total[e], RANKED.index(e) if e in RANKED else len(RANKED), e))
280
+ tied = [e for e in pool if total[e] == total[best]]
281
+ if len(candidates) == 1:
282
+ rule, reason = "only", f"{best} is the only server engine among the drivers besides ClickHouse"
283
+ elif len(pool) == 1:
284
+ rule = "evidence"
285
+ reason = f"{best} is the only server engine; {', '.join(e for e in candidates if e != best)} runs inside the process"
286
+ elif len(tied) == 1:
287
+ rule = "evidence"
288
+ said = ", ".join(f"{s} in {n} file{'s' if n != 1 else ''}" for s, n in scores[best].items())
289
+ reason = (f"the project's own settings favour {best} ({said}; "
290
+ + ", ".join(f"{e} {total[e]}" for e in candidates if e != best) + ")")
291
+ else:
292
+ rule = "tie"
293
+ reason = ((f"the project's settings favour {' and '.join(tied)} equally ({total[best]} file{'s' if total[best] != 1 else ''} each)"
294
+ if total[best] else "no setting, compose file or CI service favours one engine")
295
+ + f"; {best} is taken because " + ("the rank stage examines it" if best in RANKED else "it is first by name"))
296
+ return {"engine": best, "alternatives": [e for e in candidates if e != best], "scores": scores, "reason": reason, "rule": rule}
@@ -0,0 +1,64 @@
1
+ """Elixir: read only for its database library, Ecto (`orm_ex_ecto`).
2
+
3
+ Every .ex / .exs file is parsed once with tree-sitter-elixir; the Ecto pass then indexes modules (aliases,
4
+ functions, module attributes, `schema` blocks, `use Ecto.Repo`) and translates every `Repo.<function>` call.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ from .base import LangRules, RawSite, is_test_path, read_text
12
+
13
+ _PARSER = None
14
+
15
+
16
+ def parser():
17
+ global _PARSER
18
+ if _PARSER is None:
19
+ import tree_sitter_elixir
20
+ from tree_sitter import Language, Parser
21
+ _PARSER = Parser(Language(tree_sitter_elixir.language()))
22
+ return _PARSER
23
+
24
+
25
+ def is_test(rel: str) -> bool:
26
+ return is_test_path(rel) or rel.endswith("_test.exs") or rel.startswith("test/") or "/test/" in rel
27
+
28
+
29
+ class ExFile:
30
+ __slots__ = ("rel", "src", "tree", "test")
31
+
32
+ def __init__(self, rel: str, src: bytes, tree, test: bool):
33
+ self.rel, self.src, self.tree, self.test = rel, src, tree, test
34
+
35
+ @property
36
+ def root(self):
37
+ return self.tree.root_node
38
+
39
+
40
+ def extract(root: Path, files: list[str], rules: LangRules) -> list[RawSite]:
41
+ from . import orm_ex_ecto
42
+ p = parser()
43
+ parsed: list[ExFile] = []
44
+ for rel in files:
45
+ text = read_text(root / rel)
46
+ if text is None:
47
+ continue
48
+ src = text.encode("utf-8")
49
+ try:
50
+ tree = p.parse(src)
51
+ except Exception:
52
+ continue
53
+ parsed.append(ExFile(rel, src, tree, is_test(rel)))
54
+ return orm_ex_ecto.run(root, parsed)
55
+
56
+
57
+ def tables() -> list:
58
+ from . import orm_ex_ecto
59
+ return orm_ex_ecto.tables()
60
+
61
+
62
+ def summary_extras() -> dict:
63
+ from . import orm_ex_ecto
64
+ return orm_ex_ecto.summary_extras()