taon-typeorm 18.0.19 → 18.0.20

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 (867) hide show
  1. package/browser/esm2022/lib/typeorm/driver/cordova/CordovaDriver.mjs +1 -1
  2. package/browser/esm2022/lib/typeorm/driver/cordova/CordovaQueryRunner.mjs +1 -1
  3. package/browser/esm2022/lib/typeorm/driver/nativescript/NativescriptDriver.mjs +1 -1
  4. package/browser/esm2022/lib/typeorm/driver/nativescript/NativescriptQueryRunner.mjs +1 -1
  5. package/browser/esm2022/lib/typeorm/driver/react-native/ReactNativeDriver.mjs +1 -1
  6. package/browser/esm2022/lib/typeorm/driver/react-native/ReactNativeQueryRunner.mjs +1 -1
  7. package/browser/esm2022/lib/typeorm/driver/sqljs/SqljsDriver.mjs +1 -1
  8. package/browser/esm2022/lib/typeorm/driver/sqljs/SqljsQueryRunner.mjs +1 -1
  9. package/browser/esm2022/lib/typeorm/index.mjs +1 -3
  10. package/browser/fesm2022/taon-typeorm.mjs.map +1 -1
  11. package/client/esm2022/lib/typeorm/driver/cordova/CordovaDriver.mjs +1 -1
  12. package/client/esm2022/lib/typeorm/driver/cordova/CordovaQueryRunner.mjs +1 -1
  13. package/client/esm2022/lib/typeorm/driver/nativescript/NativescriptDriver.mjs +1 -1
  14. package/client/esm2022/lib/typeorm/driver/nativescript/NativescriptQueryRunner.mjs +1 -1
  15. package/client/esm2022/lib/typeorm/driver/react-native/ReactNativeDriver.mjs +1 -1
  16. package/client/esm2022/lib/typeorm/driver/react-native/ReactNativeQueryRunner.mjs +1 -1
  17. package/client/esm2022/lib/typeorm/driver/sqljs/SqljsDriver.mjs +1 -1
  18. package/client/esm2022/lib/typeorm/driver/sqljs/SqljsQueryRunner.mjs +1 -1
  19. package/client/esm2022/lib/typeorm/index.mjs +1 -3
  20. package/client/fesm2022/taon-typeorm.mjs.map +1 -1
  21. package/index.js +15 -2
  22. package/index.js.map +1 -1
  23. package/lib/build-info._auto-generated_.js.map +1 -1
  24. package/lib/index._auto-generated_.d.ts +1 -0
  25. package/lib/index._auto-generated_.js.map +1 -1
  26. package/lib/index.js +15 -2
  27. package/lib/index.js.map +1 -1
  28. package/lib/typeorm/cache/DbQueryResultCache.js +178 -231
  29. package/lib/typeorm/cache/DbQueryResultCache.js.map +1 -1
  30. package/lib/typeorm/cache/QueryResultCache.js.map +1 -1
  31. package/lib/typeorm/cache/QueryResultCacheFactory.js +11 -11
  32. package/lib/typeorm/cache/QueryResultCacheFactory.js.map +1 -1
  33. package/lib/typeorm/cache/QueryResultCacheOptions.js.map +1 -1
  34. package/lib/typeorm/cache/RedisQueryResultCache.js +121 -149
  35. package/lib/typeorm/cache/RedisQueryResultCache.js.map +1 -1
  36. package/lib/typeorm/cli-ts-node-commonjs.js.map +1 -1
  37. package/lib/typeorm/cli-ts-node-esm.js +7 -5
  38. package/lib/typeorm/cli-ts-node-esm.js.map +1 -1
  39. package/lib/typeorm/cli.d.ts +1 -1
  40. package/lib/typeorm/cli.js +15 -16
  41. package/lib/typeorm/cli.js.map +1 -1
  42. package/lib/typeorm/commands/CacheClearCommand.js +37 -65
  43. package/lib/typeorm/commands/CacheClearCommand.js.map +1 -1
  44. package/lib/typeorm/commands/CommandUtils.js +57 -112
  45. package/lib/typeorm/commands/CommandUtils.js.map +1 -1
  46. package/lib/typeorm/commands/EntityCreateCommand.js +35 -47
  47. package/lib/typeorm/commands/EntityCreateCommand.js.map +1 -1
  48. package/lib/typeorm/commands/InitCommand.js +397 -168
  49. package/lib/typeorm/commands/InitCommand.js.map +1 -1
  50. package/lib/typeorm/commands/MigrationCreateCommand.js +58 -52
  51. package/lib/typeorm/commands/MigrationCreateCommand.js.map +1 -1
  52. package/lib/typeorm/commands/MigrationGenerateCommand.js +141 -138
  53. package/lib/typeorm/commands/MigrationGenerateCommand.js.map +1 -1
  54. package/lib/typeorm/commands/MigrationRevertCommand.js +49 -77
  55. package/lib/typeorm/commands/MigrationRevertCommand.js.map +1 -1
  56. package/lib/typeorm/commands/MigrationRunCommand.js +52 -82
  57. package/lib/typeorm/commands/MigrationRunCommand.js.map +1 -1
  58. package/lib/typeorm/commands/MigrationShowCommand.js +32 -60
  59. package/lib/typeorm/commands/MigrationShowCommand.js.map +1 -1
  60. package/lib/typeorm/commands/QueryCommand.js +47 -83
  61. package/lib/typeorm/commands/QueryCommand.js.map +1 -1
  62. package/lib/typeorm/commands/SchemaDropCommand.js +33 -61
  63. package/lib/typeorm/commands/SchemaDropCommand.js.map +1 -1
  64. package/lib/typeorm/commands/SchemaLogCommand.js +57 -81
  65. package/lib/typeorm/commands/SchemaLogCommand.js.map +1 -1
  66. package/lib/typeorm/commands/SchemaSyncCommand.js +33 -61
  67. package/lib/typeorm/commands/SchemaSyncCommand.js.map +1 -1
  68. package/lib/typeorm/commands/SubscriberCreateCommand.js +35 -47
  69. package/lib/typeorm/commands/SubscriberCreateCommand.js.map +1 -1
  70. package/lib/typeorm/commands/VersionCommand.js +38 -54
  71. package/lib/typeorm/commands/VersionCommand.js.map +1 -1
  72. package/lib/typeorm/common/DeepPartial.js.map +1 -1
  73. package/lib/typeorm/common/EntityTarget.js.map +1 -1
  74. package/lib/typeorm/common/MixedList.js.map +1 -1
  75. package/lib/typeorm/common/NonNever.js.map +1 -1
  76. package/lib/typeorm/common/ObjectLiteral.js.map +1 -1
  77. package/lib/typeorm/common/ObjectType.js.map +1 -1
  78. package/lib/typeorm/common/RelationType.js.map +1 -1
  79. package/lib/typeorm/connection/BaseConnectionOptions.js.map +1 -1
  80. package/lib/typeorm/connection/Connection.js +3 -9
  81. package/lib/typeorm/connection/Connection.js.map +1 -1
  82. package/lib/typeorm/connection/ConnectionManager.js +23 -31
  83. package/lib/typeorm/connection/ConnectionManager.js.map +1 -1
  84. package/lib/typeorm/connection/ConnectionMetadataBuilder.js +48 -78
  85. package/lib/typeorm/connection/ConnectionMetadataBuilder.js.map +1 -1
  86. package/lib/typeorm/connection/ConnectionOptions.js.map +1 -1
  87. package/lib/typeorm/connection/ConnectionOptionsReader.js +146 -214
  88. package/lib/typeorm/connection/ConnectionOptionsReader.js.map +1 -1
  89. package/lib/typeorm/connection/options-reader/ConnectionOptionsEnvReader.js +50 -58
  90. package/lib/typeorm/connection/options-reader/ConnectionOptionsEnvReader.js.map +1 -1
  91. package/lib/typeorm/connection/options-reader/ConnectionOptionsXmlReader.js +45 -58
  92. package/lib/typeorm/connection/options-reader/ConnectionOptionsXmlReader.js.map +1 -1
  93. package/lib/typeorm/connection/options-reader/ConnectionOptionsYmlReader.js +14 -23
  94. package/lib/typeorm/connection/options-reader/ConnectionOptionsYmlReader.js.map +1 -1
  95. package/lib/typeorm/constants.js.map +1 -1
  96. package/lib/typeorm/container.js +9 -12
  97. package/lib/typeorm/container.js.map +1 -1
  98. package/lib/typeorm/data-source/BaseDataSourceOptions.js.map +1 -1
  99. package/lib/typeorm/data-source/DataSource.js +320 -478
  100. package/lib/typeorm/data-source/DataSource.js.map +1 -1
  101. package/lib/typeorm/data-source/DataSourceOptions.js.map +1 -1
  102. package/lib/typeorm/data-source/index.js +16 -3
  103. package/lib/typeorm/data-source/index.js.map +1 -1
  104. package/lib/typeorm/decorator/Check.js +5 -5
  105. package/lib/typeorm/decorator/Check.js.map +1 -1
  106. package/lib/typeorm/decorator/EntityRepository.js +1 -1
  107. package/lib/typeorm/decorator/EntityRepository.js.map +1 -1
  108. package/lib/typeorm/decorator/Exclusion.js +5 -5
  109. package/lib/typeorm/decorator/Exclusion.js.map +1 -1
  110. package/lib/typeorm/decorator/Generated.js +2 -3
  111. package/lib/typeorm/decorator/Generated.js.map +1 -1
  112. package/lib/typeorm/decorator/Index.js +5 -5
  113. package/lib/typeorm/decorator/Index.js.map +1 -1
  114. package/lib/typeorm/decorator/Unique.js +8 -8
  115. package/lib/typeorm/decorator/Unique.js.map +1 -1
  116. package/lib/typeorm/decorator/columns/Column.js +4 -4
  117. package/lib/typeorm/decorator/columns/Column.js.map +1 -1
  118. package/lib/typeorm/decorator/columns/CreateDateColumn.js +1 -1
  119. package/lib/typeorm/decorator/columns/CreateDateColumn.js.map +1 -1
  120. package/lib/typeorm/decorator/columns/DeleteDateColumn.js +1 -1
  121. package/lib/typeorm/decorator/columns/DeleteDateColumn.js.map +1 -1
  122. package/lib/typeorm/decorator/columns/ObjectIdColumn.js +1 -1
  123. package/lib/typeorm/decorator/columns/ObjectIdColumn.js.map +1 -1
  124. package/lib/typeorm/decorator/columns/PrimaryColumn.js +5 -5
  125. package/lib/typeorm/decorator/columns/PrimaryColumn.js.map +1 -1
  126. package/lib/typeorm/decorator/columns/PrimaryGeneratedColumn.js +4 -4
  127. package/lib/typeorm/decorator/columns/PrimaryGeneratedColumn.js.map +1 -1
  128. package/lib/typeorm/decorator/columns/UpdateDateColumn.js +1 -1
  129. package/lib/typeorm/decorator/columns/UpdateDateColumn.js.map +1 -1
  130. package/lib/typeorm/decorator/columns/VersionColumn.js +1 -1
  131. package/lib/typeorm/decorator/columns/VersionColumn.js.map +1 -1
  132. package/lib/typeorm/decorator/columns/ViewColumn.js +1 -1
  133. package/lib/typeorm/decorator/columns/ViewColumn.js.map +1 -1
  134. package/lib/typeorm/decorator/columns/VirtualColumn.js +5 -5
  135. package/lib/typeorm/decorator/columns/VirtualColumn.js.map +1 -1
  136. package/lib/typeorm/decorator/entity/ChildEntity.js +1 -1
  137. package/lib/typeorm/decorator/entity/ChildEntity.js.map +1 -1
  138. package/lib/typeorm/decorator/entity/Entity.js +4 -4
  139. package/lib/typeorm/decorator/entity/Entity.js.map +1 -1
  140. package/lib/typeorm/decorator/entity/TableInheritance.js +1 -1
  141. package/lib/typeorm/decorator/entity/TableInheritance.js.map +1 -1
  142. package/lib/typeorm/decorator/entity-view/ViewEntity.js +4 -4
  143. package/lib/typeorm/decorator/entity-view/ViewEntity.js.map +1 -1
  144. package/lib/typeorm/decorator/listeners/AfterInsert.js +2 -2
  145. package/lib/typeorm/decorator/listeners/AfterInsert.js.map +1 -1
  146. package/lib/typeorm/decorator/listeners/AfterLoad.js +2 -2
  147. package/lib/typeorm/decorator/listeners/AfterLoad.js.map +1 -1
  148. package/lib/typeorm/decorator/listeners/AfterRecover.js +2 -2
  149. package/lib/typeorm/decorator/listeners/AfterRecover.js.map +1 -1
  150. package/lib/typeorm/decorator/listeners/AfterRemove.js +2 -2
  151. package/lib/typeorm/decorator/listeners/AfterRemove.js.map +1 -1
  152. package/lib/typeorm/decorator/listeners/AfterSoftRemove.js +2 -2
  153. package/lib/typeorm/decorator/listeners/AfterSoftRemove.js.map +1 -1
  154. package/lib/typeorm/decorator/listeners/AfterUpdate.js +2 -2
  155. package/lib/typeorm/decorator/listeners/AfterUpdate.js.map +1 -1
  156. package/lib/typeorm/decorator/listeners/BeforeInsert.js +2 -2
  157. package/lib/typeorm/decorator/listeners/BeforeInsert.js.map +1 -1
  158. package/lib/typeorm/decorator/listeners/BeforeRecover.js +2 -2
  159. package/lib/typeorm/decorator/listeners/BeforeRecover.js.map +1 -1
  160. package/lib/typeorm/decorator/listeners/BeforeRemove.js +2 -2
  161. package/lib/typeorm/decorator/listeners/BeforeRemove.js.map +1 -1
  162. package/lib/typeorm/decorator/listeners/BeforeSoftRemove.js +2 -2
  163. package/lib/typeorm/decorator/listeners/BeforeSoftRemove.js.map +1 -1
  164. package/lib/typeorm/decorator/listeners/BeforeUpdate.js +2 -2
  165. package/lib/typeorm/decorator/listeners/BeforeUpdate.js.map +1 -1
  166. package/lib/typeorm/decorator/listeners/EventSubscriber.js +1 -1
  167. package/lib/typeorm/decorator/listeners/EventSubscriber.js.map +1 -1
  168. package/lib/typeorm/decorator/options/ColumnCommonOptions.js.map +1 -1
  169. package/lib/typeorm/decorator/options/ColumnEmbeddedOptions.js.map +1 -1
  170. package/lib/typeorm/decorator/options/ColumnEnumOptions.js.map +1 -1
  171. package/lib/typeorm/decorator/options/ColumnHstoreOptions.js.map +1 -1
  172. package/lib/typeorm/decorator/options/ColumnNumericOptions.js.map +1 -1
  173. package/lib/typeorm/decorator/options/ColumnOptions.js.map +1 -1
  174. package/lib/typeorm/decorator/options/ColumnWithLengthOptions.js.map +1 -1
  175. package/lib/typeorm/decorator/options/ColumnWithWidthOptions.js.map +1 -1
  176. package/lib/typeorm/decorator/options/EntityOptions.js.map +1 -1
  177. package/lib/typeorm/decorator/options/IndexOptions.js.map +1 -1
  178. package/lib/typeorm/decorator/options/JoinColumnOptions.js.map +1 -1
  179. package/lib/typeorm/decorator/options/JoinTableMultipleColumnsOptions.js.map +1 -1
  180. package/lib/typeorm/decorator/options/JoinTableOptions.js.map +1 -1
  181. package/lib/typeorm/decorator/options/PrimaryGeneratedColumnIdentityOptions.js.map +1 -1
  182. package/lib/typeorm/decorator/options/PrimaryGeneratedColumnNumericOptions.js.map +1 -1
  183. package/lib/typeorm/decorator/options/PrimaryGeneratedColumnUUIDOptions.js.map +1 -1
  184. package/lib/typeorm/decorator/options/RelationOptions.js.map +1 -1
  185. package/lib/typeorm/decorator/options/SpatialColumnOptions.js.map +1 -1
  186. package/lib/typeorm/decorator/options/TransactionOptions.js.map +1 -1
  187. package/lib/typeorm/decorator/options/UniqueOptions.js.map +1 -1
  188. package/lib/typeorm/decorator/options/ValueTransformer.js.map +1 -1
  189. package/lib/typeorm/decorator/options/ViewColumnOptions.js.map +1 -1
  190. package/lib/typeorm/decorator/options/ViewEntityOptions.js.map +1 -1
  191. package/lib/typeorm/decorator/options/VirtualColumnOptions.js.map +1 -1
  192. package/lib/typeorm/decorator/relations/JoinColumn.js +3 -3
  193. package/lib/typeorm/decorator/relations/JoinColumn.js.map +1 -1
  194. package/lib/typeorm/decorator/relations/JoinTable.js +1 -1
  195. package/lib/typeorm/decorator/relations/JoinTable.js.map +1 -1
  196. package/lib/typeorm/decorator/relations/ManyToMany.js +5 -5
  197. package/lib/typeorm/decorator/relations/ManyToMany.js.map +1 -1
  198. package/lib/typeorm/decorator/relations/ManyToOne.js +5 -5
  199. package/lib/typeorm/decorator/relations/ManyToOne.js.map +1 -1
  200. package/lib/typeorm/decorator/relations/OneToMany.js +3 -3
  201. package/lib/typeorm/decorator/relations/OneToMany.js.map +1 -1
  202. package/lib/typeorm/decorator/relations/OneToOne.js +5 -5
  203. package/lib/typeorm/decorator/relations/OneToOne.js.map +1 -1
  204. package/lib/typeorm/decorator/relations/RelationCount.js +1 -1
  205. package/lib/typeorm/decorator/relations/RelationCount.js.map +1 -1
  206. package/lib/typeorm/decorator/relations/RelationId.js +1 -1
  207. package/lib/typeorm/decorator/relations/RelationId.js.map +1 -1
  208. package/lib/typeorm/decorator/tree/Tree.js +1 -1
  209. package/lib/typeorm/decorator/tree/Tree.js.map +1 -1
  210. package/lib/typeorm/decorator/tree/TreeChildren.js +4 -4
  211. package/lib/typeorm/decorator/tree/TreeChildren.js.map +1 -1
  212. package/lib/typeorm/decorator/tree/TreeLevelColumn.js +1 -1
  213. package/lib/typeorm/decorator/tree/TreeLevelColumn.js.map +1 -1
  214. package/lib/typeorm/decorator/tree/TreeParent.js +4 -4
  215. package/lib/typeorm/decorator/tree/TreeParent.js.map +1 -1
  216. package/lib/typeorm/driver/Driver.js.map +1 -1
  217. package/lib/typeorm/driver/DriverFactory.js +24 -27
  218. package/lib/typeorm/driver/DriverFactory.js.map +1 -1
  219. package/lib/typeorm/driver/DriverUtils.js +78 -126
  220. package/lib/typeorm/driver/DriverUtils.js.map +1 -1
  221. package/lib/typeorm/driver/Query.js +6 -5
  222. package/lib/typeorm/driver/Query.js.map +1 -1
  223. package/lib/typeorm/driver/SqlInMemory.js +4 -7
  224. package/lib/typeorm/driver/SqlInMemory.js.map +1 -1
  225. package/lib/typeorm/driver/aurora-mysql/AuroraMysqlConnection.js +9 -12
  226. package/lib/typeorm/driver/aurora-mysql/AuroraMysqlConnection.js.map +1 -1
  227. package/lib/typeorm/driver/aurora-mysql/AuroraMysqlConnectionCredentialsOptions.js.map +1 -1
  228. package/lib/typeorm/driver/aurora-mysql/AuroraMysqlConnectionOptions.js.map +1 -1
  229. package/lib/typeorm/driver/aurora-mysql/AuroraMysqlDriver.js +392 -399
  230. package/lib/typeorm/driver/aurora-mysql/AuroraMysqlDriver.js.map +1 -1
  231. package/lib/typeorm/driver/aurora-mysql/AuroraMysqlQueryRunner.js +1320 -2084
  232. package/lib/typeorm/driver/aurora-mysql/AuroraMysqlQueryRunner.js.map +1 -1
  233. package/lib/typeorm/driver/aurora-postgres/AuroraPostgresConnectionOptions.js.map +1 -1
  234. package/lib/typeorm/driver/aurora-postgres/AuroraPostgresDriver.js +50 -78
  235. package/lib/typeorm/driver/aurora-postgres/AuroraPostgresDriver.js.map +1 -1
  236. package/lib/typeorm/driver/aurora-postgres/AuroraPostgresQueryRunner.js +89 -160
  237. package/lib/typeorm/driver/aurora-postgres/AuroraPostgresQueryRunner.js.map +1 -1
  238. package/lib/typeorm/driver/better-sqlite3/BetterSqlite3ConnectionOptions.js.map +1 -1
  239. package/lib/typeorm/driver/better-sqlite3/BetterSqlite3Driver.js +78 -152
  240. package/lib/typeorm/driver/better-sqlite3/BetterSqlite3Driver.js.map +1 -1
  241. package/lib/typeorm/driver/better-sqlite3/BetterSqlite3QueryRunner.js +96 -155
  242. package/lib/typeorm/driver/better-sqlite3/BetterSqlite3QueryRunner.js.map +1 -1
  243. package/lib/typeorm/driver/capacitor/CapacitorConnectionOptions.js.map +1 -1
  244. package/lib/typeorm/driver/capacitor/CapacitorDriver.js +44 -89
  245. package/lib/typeorm/driver/capacitor/CapacitorDriver.js.map +1 -1
  246. package/lib/typeorm/driver/capacitor/CapacitorQueryRunner.js +70 -122
  247. package/lib/typeorm/driver/capacitor/CapacitorQueryRunner.js.map +1 -1
  248. package/lib/typeorm/driver/cockroachdb/CockroachConnectionCredentialsOptions.js.map +1 -1
  249. package/lib/typeorm/driver/cockroachdb/CockroachConnectionOptions.js.map +1 -1
  250. package/lib/typeorm/driver/cockroachdb/CockroachDriver.js +368 -404
  251. package/lib/typeorm/driver/cockroachdb/CockroachDriver.js.map +1 -1
  252. package/lib/typeorm/driver/cockroachdb/CockroachQueryRunner.js +1752 -2862
  253. package/lib/typeorm/driver/cockroachdb/CockroachQueryRunner.js.map +1 -1
  254. package/lib/typeorm/driver/cordova/CordovaConnectionOptions.js.map +1 -1
  255. package/lib/typeorm/driver/cordova/CordovaDriver.js +36 -58
  256. package/lib/typeorm/driver/cordova/CordovaDriver.js.map +1 -1
  257. package/lib/typeorm/driver/cordova/CordovaQueryRunner.js +86 -164
  258. package/lib/typeorm/driver/cordova/CordovaQueryRunner.js.map +1 -1
  259. package/lib/typeorm/driver/expo/ExpoConnectionOptions.js.map +1 -1
  260. package/lib/typeorm/driver/expo/ExpoDriver.js +34 -44
  261. package/lib/typeorm/driver/expo/ExpoDriver.js.map +1 -1
  262. package/lib/typeorm/driver/expo/ExpoQueryRunner.js +114 -204
  263. package/lib/typeorm/driver/expo/ExpoQueryRunner.js.map +1 -1
  264. package/lib/typeorm/driver/mongodb/MongoConnectionOptions.js.map +1 -1
  265. package/lib/typeorm/driver/mongodb/MongoDriver.js +269 -243
  266. package/lib/typeorm/driver/mongodb/MongoDriver.js.map +1 -1
  267. package/lib/typeorm/driver/mongodb/MongoQueryRunner.js +357 -793
  268. package/lib/typeorm/driver/mongodb/MongoQueryRunner.js.map +1 -1
  269. package/lib/typeorm/driver/mongodb/typings.js.map +1 -1
  270. package/lib/typeorm/driver/mysql/MysqlConnectionCredentialsOptions.js.map +1 -1
  271. package/lib/typeorm/driver/mysql/MysqlConnectionOptions.js.map +1 -1
  272. package/lib/typeorm/driver/mysql/MysqlDriver.js +475 -480
  273. package/lib/typeorm/driver/mysql/MysqlDriver.js.map +1 -1
  274. package/lib/typeorm/driver/mysql/MysqlQueryRunner.js +1692 -2466
  275. package/lib/typeorm/driver/mysql/MysqlQueryRunner.js.map +1 -1
  276. package/lib/typeorm/driver/nativescript/NativescriptConnectionOptions.js.map +1 -1
  277. package/lib/typeorm/driver/nativescript/NativescriptDriver.js +46 -50
  278. package/lib/typeorm/driver/nativescript/NativescriptDriver.js.map +1 -1
  279. package/lib/typeorm/driver/nativescript/NativescriptQueryRunner.js +62 -101
  280. package/lib/typeorm/driver/nativescript/NativescriptQueryRunner.js.map +1 -1
  281. package/lib/typeorm/driver/oracle/OracleConnectionCredentialsOptions.js.map +1 -1
  282. package/lib/typeorm/driver/oracle/OracleConnectionOptions.js.map +1 -1
  283. package/lib/typeorm/driver/oracle/OracleDriver.js +345 -377
  284. package/lib/typeorm/driver/oracle/OracleDriver.js.map +1 -1
  285. package/lib/typeorm/driver/oracle/OracleQueryRunner.js +1484 -2384
  286. package/lib/typeorm/driver/oracle/OracleQueryRunner.js.map +1 -1
  287. package/lib/typeorm/driver/postgres/PostgresConnectionCredentialsOptions.js.map +1 -1
  288. package/lib/typeorm/driver/postgres/PostgresConnectionOptions.js.map +1 -1
  289. package/lib/typeorm/driver/postgres/PostgresDriver.js +574 -690
  290. package/lib/typeorm/driver/postgres/PostgresDriver.js.map +1 -1
  291. package/lib/typeorm/driver/postgres/PostgresQueryRunner.js +2153 -3379
  292. package/lib/typeorm/driver/postgres/PostgresQueryRunner.js.map +1 -1
  293. package/lib/typeorm/driver/react-native/ReactNativeConnectionOptions.js.map +1 -1
  294. package/lib/typeorm/driver/react-native/ReactNativeDriver.js +34 -44
  295. package/lib/typeorm/driver/react-native/ReactNativeDriver.js.map +1 -1
  296. package/lib/typeorm/driver/react-native/ReactNativeQueryRunner.js +60 -94
  297. package/lib/typeorm/driver/react-native/ReactNativeQueryRunner.js.map +1 -1
  298. package/lib/typeorm/driver/sap/SapConnectionCredentialsOptions.js.map +1 -1
  299. package/lib/typeorm/driver/sap/SapConnectionOptions.js.map +1 -1
  300. package/lib/typeorm/driver/sap/SapDriver.js +310 -305
  301. package/lib/typeorm/driver/sap/SapDriver.js.map +1 -1
  302. package/lib/typeorm/driver/sap/SapQueryRunner.js +1635 -2561
  303. package/lib/typeorm/driver/sap/SapQueryRunner.js.map +1 -1
  304. package/lib/typeorm/driver/spanner/SpannerConnectionCredentialsOptions.js.map +1 -1
  305. package/lib/typeorm/driver/spanner/SpannerConnectionOptions.js.map +1 -1
  306. package/lib/typeorm/driver/spanner/SpannerDriver.js +250 -236
  307. package/lib/typeorm/driver/spanner/SpannerDriver.js.map +1 -1
  308. package/lib/typeorm/driver/spanner/SpannerQueryRunner.js +1136 -2168
  309. package/lib/typeorm/driver/spanner/SpannerQueryRunner.js.map +1 -1
  310. package/lib/typeorm/driver/sqlite/SqliteConnectionOptions.js.map +1 -1
  311. package/lib/typeorm/driver/sqlite/SqliteDriver.js +82 -169
  312. package/lib/typeorm/driver/sqlite/SqliteDriver.js.map +1 -1
  313. package/lib/typeorm/driver/sqlite/SqliteQueryRunner.js +78 -122
  314. package/lib/typeorm/driver/sqlite/SqliteQueryRunner.js.map +1 -1
  315. package/lib/typeorm/driver/sqlite-abstract/AbstractSqliteDriver.js +280 -268
  316. package/lib/typeorm/driver/sqlite-abstract/AbstractSqliteDriver.js.map +1 -1
  317. package/lib/typeorm/driver/sqlite-abstract/AbstractSqliteQueryRunner.js +1158 -1990
  318. package/lib/typeorm/driver/sqlite-abstract/AbstractSqliteQueryRunner.js.map +1 -1
  319. package/lib/typeorm/driver/sqljs/SqljsConnectionOptions.js.map +1 -1
  320. package/lib/typeorm/driver/sqljs/SqljsDriver.js +187 -253
  321. package/lib/typeorm/driver/sqljs/SqljsDriver.js.map +1 -1
  322. package/lib/typeorm/driver/sqljs/SqljsQueryRunner.js +88 -147
  323. package/lib/typeorm/driver/sqljs/SqljsQueryRunner.js.map +1 -1
  324. package/lib/typeorm/driver/sqlserver/MssqlParameter.js +10 -13
  325. package/lib/typeorm/driver/sqlserver/MssqlParameter.js.map +1 -1
  326. package/lib/typeorm/driver/sqlserver/SqlServerConnectionCredentialsOptions.js.map +1 -1
  327. package/lib/typeorm/driver/sqlserver/SqlServerConnectionOptions.js.map +1 -1
  328. package/lib/typeorm/driver/sqlserver/SqlServerDriver.js +352 -372
  329. package/lib/typeorm/driver/sqlserver/SqlServerDriver.js.map +1 -1
  330. package/lib/typeorm/driver/sqlserver/SqlServerQueryRunner.js +1979 -3068
  331. package/lib/typeorm/driver/sqlserver/SqlServerQueryRunner.js.map +1 -1
  332. package/lib/typeorm/driver/sqlserver/authentication/AzureActiveDirectoryAccessTokenAuthentication.js.map +1 -1
  333. package/lib/typeorm/driver/sqlserver/authentication/AzureActiveDirectoryMsiAppServiceAuthentication.js.map +1 -1
  334. package/lib/typeorm/driver/sqlserver/authentication/AzureActiveDirectoryMsiVmAuthentication.js.map +1 -1
  335. package/lib/typeorm/driver/sqlserver/authentication/AzureActiveDirectoryPasswordAuthentication.js.map +1 -1
  336. package/lib/typeorm/driver/sqlserver/authentication/AzureActiveDirectoryServicePrincipalSecret.js.map +1 -1
  337. package/lib/typeorm/driver/sqlserver/authentication/DefaultAuthentication.js.map +1 -1
  338. package/lib/typeorm/driver/sqlserver/authentication/NtlmAuthentication.js.map +1 -1
  339. package/lib/typeorm/driver/types/ColumnTypes.js.map +1 -1
  340. package/lib/typeorm/driver/types/CteCapabilities.js.map +1 -1
  341. package/lib/typeorm/driver/types/DataTypeDefaults.js.map +1 -1
  342. package/lib/typeorm/driver/types/DatabaseType.js.map +1 -1
  343. package/lib/typeorm/driver/types/IsolationLevel.js.map +1 -1
  344. package/lib/typeorm/driver/types/MappedColumnTypes.js.map +1 -1
  345. package/lib/typeorm/driver/types/MetadataTableType.js.map +1 -1
  346. package/lib/typeorm/driver/types/ReplicationMode.js.map +1 -1
  347. package/lib/typeorm/driver/types/UpsertType.js.map +1 -1
  348. package/lib/typeorm/entity-manager/EntityManager.js +351 -469
  349. package/lib/typeorm/entity-manager/EntityManager.js.map +1 -1
  350. package/lib/typeorm/entity-manager/EntityManagerFactory.js +7 -10
  351. package/lib/typeorm/entity-manager/EntityManagerFactory.js.map +1 -1
  352. package/lib/typeorm/entity-manager/MongoEntityManager.js +371 -487
  353. package/lib/typeorm/entity-manager/MongoEntityManager.js.map +1 -1
  354. package/lib/typeorm/entity-manager/SqljsEntityManager.js +16 -37
  355. package/lib/typeorm/entity-manager/SqljsEntityManager.js.map +1 -1
  356. package/lib/typeorm/entity-schema/EntitySchema.js +5 -5
  357. package/lib/typeorm/entity-schema/EntitySchema.js.map +1 -1
  358. package/lib/typeorm/entity-schema/EntitySchemaCheckOptions.js.map +1 -1
  359. package/lib/typeorm/entity-schema/EntitySchemaColumnOptions.js.map +1 -1
  360. package/lib/typeorm/entity-schema/EntitySchemaEmbeddedColumnOptions.js +17 -5
  361. package/lib/typeorm/entity-schema/EntitySchemaEmbeddedColumnOptions.js.map +1 -1
  362. package/lib/typeorm/entity-schema/EntitySchemaEmbeddedError.js +11 -14
  363. package/lib/typeorm/entity-schema/EntitySchemaEmbeddedError.js.map +1 -1
  364. package/lib/typeorm/entity-schema/EntitySchemaExclusionOptions.js.map +1 -1
  365. package/lib/typeorm/entity-schema/EntitySchemaIndexOptions.js.map +1 -1
  366. package/lib/typeorm/entity-schema/EntitySchemaOptions.js +82 -5
  367. package/lib/typeorm/entity-schema/EntitySchemaOptions.js.map +1 -1
  368. package/lib/typeorm/entity-schema/EntitySchemaRelationIdOptions.js.map +1 -1
  369. package/lib/typeorm/entity-schema/EntitySchemaRelationOptions.js.map +1 -1
  370. package/lib/typeorm/entity-schema/EntitySchemaTransformer.js +51 -68
  371. package/lib/typeorm/entity-schema/EntitySchemaTransformer.js.map +1 -1
  372. package/lib/typeorm/entity-schema/EntitySchemaUniqueOptions.js.map +1 -1
  373. package/lib/typeorm/error/AlreadyHasActiveConnectionError.js +6 -9
  374. package/lib/typeorm/error/AlreadyHasActiveConnectionError.js.map +1 -1
  375. package/lib/typeorm/error/CannotAttachTreeChildrenEntityError.js +6 -9
  376. package/lib/typeorm/error/CannotAttachTreeChildrenEntityError.js.map +1 -1
  377. package/lib/typeorm/error/CannotConnectAlreadyConnectedError.js +5 -8
  378. package/lib/typeorm/error/CannotConnectAlreadyConnectedError.js.map +1 -1
  379. package/lib/typeorm/error/CannotCreateEntityIdMapError.js +7 -11
  380. package/lib/typeorm/error/CannotCreateEntityIdMapError.js.map +1 -1
  381. package/lib/typeorm/error/CannotDetermineEntityError.js +6 -9
  382. package/lib/typeorm/error/CannotDetermineEntityError.js.map +1 -1
  383. package/lib/typeorm/error/CannotExecuteNotConnectedError.js +5 -8
  384. package/lib/typeorm/error/CannotExecuteNotConnectedError.js.map +1 -1
  385. package/lib/typeorm/error/CannotGetEntityManagerNotConnectedError.js +5 -8
  386. package/lib/typeorm/error/CannotGetEntityManagerNotConnectedError.js.map +1 -1
  387. package/lib/typeorm/error/CannotReflectMethodParameterTypeError.js +7 -10
  388. package/lib/typeorm/error/CannotReflectMethodParameterTypeError.js.map +1 -1
  389. package/lib/typeorm/error/CircularRelationsError.js +6 -9
  390. package/lib/typeorm/error/CircularRelationsError.js.map +1 -1
  391. package/lib/typeorm/error/ColumnTypeUndefinedError.js +8 -11
  392. package/lib/typeorm/error/ColumnTypeUndefinedError.js.map +1 -1
  393. package/lib/typeorm/error/ConnectionIsNotSetError.js +5 -8
  394. package/lib/typeorm/error/ConnectionIsNotSetError.js.map +1 -1
  395. package/lib/typeorm/error/ConnectionNotFoundError.js +5 -8
  396. package/lib/typeorm/error/ConnectionNotFoundError.js.map +1 -1
  397. package/lib/typeorm/error/CustomRepositoryCannotInheritRepositoryError.js +7 -10
  398. package/lib/typeorm/error/CustomRepositoryCannotInheritRepositoryError.js.map +1 -1
  399. package/lib/typeorm/error/CustomRepositoryDoesNotHaveEntityError.js +7 -10
  400. package/lib/typeorm/error/CustomRepositoryDoesNotHaveEntityError.js.map +1 -1
  401. package/lib/typeorm/error/CustomRepositoryNotFoundError.js +7 -10
  402. package/lib/typeorm/error/CustomRepositoryNotFoundError.js.map +1 -1
  403. package/lib/typeorm/error/DataTypeNotSupportedError.js +7 -11
  404. package/lib/typeorm/error/DataTypeNotSupportedError.js.map +1 -1
  405. package/lib/typeorm/error/DriverOptionNotSetError.js +6 -9
  406. package/lib/typeorm/error/DriverOptionNotSetError.js.map +1 -1
  407. package/lib/typeorm/error/DriverPackageNotInstalledError.js +6 -9
  408. package/lib/typeorm/error/DriverPackageNotInstalledError.js.map +1 -1
  409. package/lib/typeorm/error/EntityMetadataNotFoundError.js +10 -14
  410. package/lib/typeorm/error/EntityMetadataNotFoundError.js.map +1 -1
  411. package/lib/typeorm/error/EntityNotFoundError.js +13 -17
  412. package/lib/typeorm/error/EntityNotFoundError.js.map +1 -1
  413. package/lib/typeorm/error/EntityPropertyNotFoundError.js +7 -11
  414. package/lib/typeorm/error/EntityPropertyNotFoundError.js.map +1 -1
  415. package/lib/typeorm/error/FindRelationsNotFoundError.js +9 -13
  416. package/lib/typeorm/error/FindRelationsNotFoundError.js.map +1 -1
  417. package/lib/typeorm/error/ForbiddenTransactionModeOverrideError.js +6 -9
  418. package/lib/typeorm/error/ForbiddenTransactionModeOverrideError.js.map +1 -1
  419. package/lib/typeorm/error/InitializedRelationError.js +7 -10
  420. package/lib/typeorm/error/InitializedRelationError.js.map +1 -1
  421. package/lib/typeorm/error/InsertValuesMissingError.js +6 -9
  422. package/lib/typeorm/error/InsertValuesMissingError.js.map +1 -1
  423. package/lib/typeorm/error/LimitOnUpdateNotSupportedError.js +5 -8
  424. package/lib/typeorm/error/LimitOnUpdateNotSupportedError.js.map +1 -1
  425. package/lib/typeorm/error/LockNotSupportedOnGivenDriverError.js +5 -8
  426. package/lib/typeorm/error/LockNotSupportedOnGivenDriverError.js.map +1 -1
  427. package/lib/typeorm/error/MetadataAlreadyExistsError.js +6 -9
  428. package/lib/typeorm/error/MetadataAlreadyExistsError.js.map +1 -1
  429. package/lib/typeorm/error/MetadataWithSuchNameAlreadyExistsError.js +6 -9
  430. package/lib/typeorm/error/MetadataWithSuchNameAlreadyExistsError.js.map +1 -1
  431. package/lib/typeorm/error/MissingDeleteDateColumnError.js +5 -8
  432. package/lib/typeorm/error/MissingDeleteDateColumnError.js.map +1 -1
  433. package/lib/typeorm/error/MissingDriverError.js +6 -10
  434. package/lib/typeorm/error/MissingDriverError.js.map +1 -1
  435. package/lib/typeorm/error/MissingJoinColumnError.js +12 -16
  436. package/lib/typeorm/error/MissingJoinColumnError.js.map +1 -1
  437. package/lib/typeorm/error/MissingJoinTableError.js +12 -16
  438. package/lib/typeorm/error/MissingJoinTableError.js.map +1 -1
  439. package/lib/typeorm/error/MissingPrimaryColumnError.js +6 -9
  440. package/lib/typeorm/error/MissingPrimaryColumnError.js.map +1 -1
  441. package/lib/typeorm/error/MustBeEntityError.js +5 -8
  442. package/lib/typeorm/error/MustBeEntityError.js.map +1 -1
  443. package/lib/typeorm/error/NamingStrategyNotFoundError.js +9 -13
  444. package/lib/typeorm/error/NamingStrategyNotFoundError.js.map +1 -1
  445. package/lib/typeorm/error/NestedSetMultipleRootError.js +5 -8
  446. package/lib/typeorm/error/NestedSetMultipleRootError.js.map +1 -1
  447. package/lib/typeorm/error/NoConnectionForRepositoryError.js +6 -9
  448. package/lib/typeorm/error/NoConnectionForRepositoryError.js.map +1 -1
  449. package/lib/typeorm/error/NoConnectionOptionError.js +6 -9
  450. package/lib/typeorm/error/NoConnectionOptionError.js.map +1 -1
  451. package/lib/typeorm/error/NoNeedToReleaseEntityManagerError.js +7 -10
  452. package/lib/typeorm/error/NoNeedToReleaseEntityManagerError.js.map +1 -1
  453. package/lib/typeorm/error/NoVersionOrUpdateDateColumnError.js +5 -8
  454. package/lib/typeorm/error/NoVersionOrUpdateDateColumnError.js.map +1 -1
  455. package/lib/typeorm/error/OffsetWithoutLimitNotSupportedError.js +7 -10
  456. package/lib/typeorm/error/OffsetWithoutLimitNotSupportedError.js.map +1 -1
  457. package/lib/typeorm/error/OptimisticLockCanNotBeUsedError.js +5 -8
  458. package/lib/typeorm/error/OptimisticLockCanNotBeUsedError.js.map +1 -1
  459. package/lib/typeorm/error/OptimisticLockVersionMismatchError.js +5 -8
  460. package/lib/typeorm/error/OptimisticLockVersionMismatchError.js.map +1 -1
  461. package/lib/typeorm/error/PersistedEntityNotFoundError.js +5 -8
  462. package/lib/typeorm/error/PersistedEntityNotFoundError.js.map +1 -1
  463. package/lib/typeorm/error/PessimisticLockTransactionRequiredError.js +5 -8
  464. package/lib/typeorm/error/PessimisticLockTransactionRequiredError.js.map +1 -1
  465. package/lib/typeorm/error/PrimaryColumnCannotBeNullableError.js +6 -9
  466. package/lib/typeorm/error/PrimaryColumnCannotBeNullableError.js.map +1 -1
  467. package/lib/typeorm/error/QueryFailedError.js +18 -17
  468. package/lib/typeorm/error/QueryFailedError.js.map +1 -1
  469. package/lib/typeorm/error/QueryRunnerAlreadyReleasedError.js +5 -8
  470. package/lib/typeorm/error/QueryRunnerAlreadyReleasedError.js.map +1 -1
  471. package/lib/typeorm/error/QueryRunnerProviderAlreadyReleasedError.js +6 -9
  472. package/lib/typeorm/error/QueryRunnerProviderAlreadyReleasedError.js.map +1 -1
  473. package/lib/typeorm/error/RepositoryNotTreeError.js +9 -13
  474. package/lib/typeorm/error/RepositoryNotTreeError.js.map +1 -1
  475. package/lib/typeorm/error/ReturningStatementNotSupportedError.js +5 -8
  476. package/lib/typeorm/error/ReturningStatementNotSupportedError.js.map +1 -1
  477. package/lib/typeorm/error/SubjectRemovedAndUpdatedError.js +6 -9
  478. package/lib/typeorm/error/SubjectRemovedAndUpdatedError.js.map +1 -1
  479. package/lib/typeorm/error/SubjectWithoutIdentifierError.js +5 -8
  480. package/lib/typeorm/error/SubjectWithoutIdentifierError.js.map +1 -1
  481. package/lib/typeorm/error/TransactionAlreadyStartedError.js +5 -8
  482. package/lib/typeorm/error/TransactionAlreadyStartedError.js.map +1 -1
  483. package/lib/typeorm/error/TransactionNotStartedError.js +5 -8
  484. package/lib/typeorm/error/TransactionNotStartedError.js.map +1 -1
  485. package/lib/typeorm/error/TreeRepositoryNotSupportedError.js +5 -8
  486. package/lib/typeorm/error/TreeRepositoryNotSupportedError.js.map +1 -1
  487. package/lib/typeorm/error/TypeORMError.js +9 -18
  488. package/lib/typeorm/error/TypeORMError.js.map +1 -1
  489. package/lib/typeorm/error/UpdateValuesMissingError.js +5 -8
  490. package/lib/typeorm/error/UpdateValuesMissingError.js.map +1 -1
  491. package/lib/typeorm/error/UsingJoinColumnIsNotAllowedError.js +6 -9
  492. package/lib/typeorm/error/UsingJoinColumnIsNotAllowedError.js.map +1 -1
  493. package/lib/typeorm/error/UsingJoinColumnOnlyOnOneSideAllowedError.js +7 -10
  494. package/lib/typeorm/error/UsingJoinColumnOnlyOnOneSideAllowedError.js.map +1 -1
  495. package/lib/typeorm/error/UsingJoinTableIsNotAllowedError.js +7 -10
  496. package/lib/typeorm/error/UsingJoinTableIsNotAllowedError.js.map +1 -1
  497. package/lib/typeorm/error/UsingJoinTableOnlyOnOneSideAllowedError.js +7 -10
  498. package/lib/typeorm/error/UsingJoinTableOnlyOnOneSideAllowedError.js.map +1 -1
  499. package/lib/typeorm/error/index.js +75 -62
  500. package/lib/typeorm/error/index.js.map +1 -1
  501. package/lib/typeorm/find-options/EqualOperator.js +6 -10
  502. package/lib/typeorm/find-options/EqualOperator.js.map +1 -1
  503. package/lib/typeorm/find-options/FindManyOptions.js.map +1 -1
  504. package/lib/typeorm/find-options/FindOneOptions.js.map +1 -1
  505. package/lib/typeorm/find-options/FindOperator.js +90 -94
  506. package/lib/typeorm/find-options/FindOperator.js.map +1 -1
  507. package/lib/typeorm/find-options/FindOperatorType.js.map +1 -1
  508. package/lib/typeorm/find-options/FindOptionsOrder.js.map +1 -1
  509. package/lib/typeorm/find-options/FindOptionsRelations.js.map +1 -1
  510. package/lib/typeorm/find-options/FindOptionsSelect.js.map +1 -1
  511. package/lib/typeorm/find-options/FindOptionsUtils.js +56 -87
  512. package/lib/typeorm/find-options/FindOptionsUtils.js.map +1 -1
  513. package/lib/typeorm/find-options/FindOptionsWhere.js.map +1 -1
  514. package/lib/typeorm/find-options/FindTreeOptions.js.map +1 -1
  515. package/lib/typeorm/find-options/JoinOptions.js.map +1 -1
  516. package/lib/typeorm/find-options/OrderByCondition.js.map +1 -1
  517. package/lib/typeorm/find-options/mongodb/MongoFindManyOptions.js.map +1 -1
  518. package/lib/typeorm/find-options/mongodb/MongoFindOneOptions.js.map +1 -1
  519. package/lib/typeorm/find-options/operator/And.js +2 -6
  520. package/lib/typeorm/find-options/operator/And.js.map +1 -1
  521. package/lib/typeorm/find-options/operator/Any.js +1 -1
  522. package/lib/typeorm/find-options/operator/Any.js.map +1 -1
  523. package/lib/typeorm/find-options/operator/ArrayContainedBy.js +1 -1
  524. package/lib/typeorm/find-options/operator/ArrayContainedBy.js.map +1 -1
  525. package/lib/typeorm/find-options/operator/ArrayContains.js +1 -1
  526. package/lib/typeorm/find-options/operator/ArrayContains.js.map +1 -1
  527. package/lib/typeorm/find-options/operator/ArrayOverlap.js +1 -1
  528. package/lib/typeorm/find-options/operator/ArrayOverlap.js.map +1 -1
  529. package/lib/typeorm/find-options/operator/Between.js +1 -1
  530. package/lib/typeorm/find-options/operator/Between.js.map +1 -1
  531. package/lib/typeorm/find-options/operator/Equal.js +1 -1
  532. package/lib/typeorm/find-options/operator/Equal.js.map +1 -1
  533. package/lib/typeorm/find-options/operator/ILike.js +1 -1
  534. package/lib/typeorm/find-options/operator/ILike.js.map +1 -1
  535. package/lib/typeorm/find-options/operator/In.js +1 -1
  536. package/lib/typeorm/find-options/operator/In.js.map +1 -1
  537. package/lib/typeorm/find-options/operator/IsNull.js +1 -1
  538. package/lib/typeorm/find-options/operator/IsNull.js.map +1 -1
  539. package/lib/typeorm/find-options/operator/LessThan.js +1 -1
  540. package/lib/typeorm/find-options/operator/LessThan.js.map +1 -1
  541. package/lib/typeorm/find-options/operator/LessThanOrEqual.js +1 -1
  542. package/lib/typeorm/find-options/operator/LessThanOrEqual.js.map +1 -1
  543. package/lib/typeorm/find-options/operator/Like.js +1 -1
  544. package/lib/typeorm/find-options/operator/Like.js.map +1 -1
  545. package/lib/typeorm/find-options/operator/MoreThan.js +1 -1
  546. package/lib/typeorm/find-options/operator/MoreThan.js.map +1 -1
  547. package/lib/typeorm/find-options/operator/MoreThanOrEqual.js +1 -1
  548. package/lib/typeorm/find-options/operator/MoreThanOrEqual.js.map +1 -1
  549. package/lib/typeorm/find-options/operator/Not.js +1 -1
  550. package/lib/typeorm/find-options/operator/Not.js.map +1 -1
  551. package/lib/typeorm/find-options/operator/Raw.js +1 -1
  552. package/lib/typeorm/find-options/operator/Raw.js.map +1 -1
  553. package/lib/typeorm/globals.js +33 -99
  554. package/lib/typeorm/globals.js.map +1 -1
  555. package/lib/typeorm/index.d.ts +0 -1
  556. package/lib/typeorm/index.js +136 -126
  557. package/lib/typeorm/index.js.map +1 -1
  558. package/lib/typeorm/logger/AdvancedConsoleLogger.js +26 -26
  559. package/lib/typeorm/logger/AdvancedConsoleLogger.js.map +1 -1
  560. package/lib/typeorm/logger/DebugLogger.js +24 -27
  561. package/lib/typeorm/logger/DebugLogger.js.map +1 -1
  562. package/lib/typeorm/logger/FileLogger.js +31 -30
  563. package/lib/typeorm/logger/FileLogger.js.map +1 -1
  564. package/lib/typeorm/logger/Logger.js.map +1 -1
  565. package/lib/typeorm/logger/LoggerFactory.js +9 -12
  566. package/lib/typeorm/logger/LoggerFactory.js.map +1 -1
  567. package/lib/typeorm/logger/LoggerOptions.js.map +1 -1
  568. package/lib/typeorm/logger/SimpleConsoleLogger.js +25 -25
  569. package/lib/typeorm/logger/SimpleConsoleLogger.js.map +1 -1
  570. package/lib/typeorm/metadata/CheckMetadata.js +30 -6
  571. package/lib/typeorm/metadata/CheckMetadata.js.map +1 -1
  572. package/lib/typeorm/metadata/ColumnMetadata.js +343 -199
  573. package/lib/typeorm/metadata/ColumnMetadata.js.map +1 -1
  574. package/lib/typeorm/metadata/EmbeddedMetadata.js +174 -153
  575. package/lib/typeorm/metadata/EmbeddedMetadata.js.map +1 -1
  576. package/lib/typeorm/metadata/EntityListenerMetadata.js +35 -15
  577. package/lib/typeorm/metadata/EntityListenerMetadata.js.map +1 -1
  578. package/lib/typeorm/metadata/EntityMetadata.js +516 -372
  579. package/lib/typeorm/metadata/EntityMetadata.js.map +1 -1
  580. package/lib/typeorm/metadata/ExclusionMetadata.js +30 -6
  581. package/lib/typeorm/metadata/ExclusionMetadata.js.map +1 -1
  582. package/lib/typeorm/metadata/ForeignKeyMetadata.js +60 -24
  583. package/lib/typeorm/metadata/ForeignKeyMetadata.js.map +1 -1
  584. package/lib/typeorm/metadata/IndexMetadata.js +119 -73
  585. package/lib/typeorm/metadata/IndexMetadata.js.map +1 -1
  586. package/lib/typeorm/metadata/RelationCountMetadata.js +40 -10
  587. package/lib/typeorm/metadata/RelationCountMetadata.js.map +1 -1
  588. package/lib/typeorm/metadata/RelationIdMetadata.js +47 -18
  589. package/lib/typeorm/metadata/RelationIdMetadata.js.map +1 -1
  590. package/lib/typeorm/metadata/RelationMetadata.js +270 -187
  591. package/lib/typeorm/metadata/RelationMetadata.js.map +1 -1
  592. package/lib/typeorm/metadata/UniqueMetadata.js +72 -47
  593. package/lib/typeorm/metadata/UniqueMetadata.js.map +1 -1
  594. package/lib/typeorm/metadata/types/ClosureTreeOptions.js.map +1 -1
  595. package/lib/typeorm/metadata/types/DeferrableType.js.map +1 -1
  596. package/lib/typeorm/metadata/types/EventListenerTypes.js +13 -16
  597. package/lib/typeorm/metadata/types/EventListenerTypes.js.map +1 -1
  598. package/lib/typeorm/metadata/types/OnDeleteType.js.map +1 -1
  599. package/lib/typeorm/metadata/types/OnUpdateType.js.map +1 -1
  600. package/lib/typeorm/metadata/types/PropertyTypeInFunction.js.map +1 -1
  601. package/lib/typeorm/metadata/types/RelationTypeInFunction.js.map +1 -1
  602. package/lib/typeorm/metadata/types/RelationTypes.js.map +1 -1
  603. package/lib/typeorm/metadata/types/TableTypes.js.map +1 -1
  604. package/lib/typeorm/metadata/types/TreeTypes.js.map +1 -1
  605. package/lib/typeorm/metadata-args/CheckMetadataArgs.js.map +1 -1
  606. package/lib/typeorm/metadata-args/ColumnMetadataArgs.js.map +1 -1
  607. package/lib/typeorm/metadata-args/DiscriminatorValueMetadataArgs.js.map +1 -1
  608. package/lib/typeorm/metadata-args/EmbeddedMetadataArgs.js.map +1 -1
  609. package/lib/typeorm/metadata-args/EntityListenerMetadataArgs.js.map +1 -1
  610. package/lib/typeorm/metadata-args/EntityRepositoryMetadataArgs.js.map +1 -1
  611. package/lib/typeorm/metadata-args/EntitySubscriberMetadataArgs.js.map +1 -1
  612. package/lib/typeorm/metadata-args/ExclusionMetadataArgs.js.map +1 -1
  613. package/lib/typeorm/metadata-args/GeneratedMetadataArgs.js.map +1 -1
  614. package/lib/typeorm/metadata-args/IndexMetadataArgs.js.map +1 -1
  615. package/lib/typeorm/metadata-args/InheritanceMetadataArgs.js.map +1 -1
  616. package/lib/typeorm/metadata-args/JoinColumnMetadataArgs.js.map +1 -1
  617. package/lib/typeorm/metadata-args/JoinTableMetadataArgs.js.map +1 -1
  618. package/lib/typeorm/metadata-args/MetadataArgsStorage.js +108 -113
  619. package/lib/typeorm/metadata-args/MetadataArgsStorage.js.map +1 -1
  620. package/lib/typeorm/metadata-args/NamingStrategyMetadataArgs.js.map +1 -1
  621. package/lib/typeorm/metadata-args/RelationCountMetadataArgs.js.map +1 -1
  622. package/lib/typeorm/metadata-args/RelationIdMetadataArgs.js.map +1 -1
  623. package/lib/typeorm/metadata-args/RelationMetadataArgs.js.map +1 -1
  624. package/lib/typeorm/metadata-args/TableMetadataArgs.js.map +1 -1
  625. package/lib/typeorm/metadata-args/TransactionEntityMetadataArgs.js.map +1 -1
  626. package/lib/typeorm/metadata-args/TransactionRepositoryMetadataArgs.js.map +1 -1
  627. package/lib/typeorm/metadata-args/TreeMetadataArgs.js.map +1 -1
  628. package/lib/typeorm/metadata-args/UniqueMetadataArgs.js.map +1 -1
  629. package/lib/typeorm/metadata-args/types/ColumnMode.js.map +1 -1
  630. package/lib/typeorm/metadata-builder/ClosureJunctionEntityMetadataBuilder.js +14 -15
  631. package/lib/typeorm/metadata-builder/ClosureJunctionEntityMetadataBuilder.js.map +1 -1
  632. package/lib/typeorm/metadata-builder/EntityMetadataBuilder.js +291 -347
  633. package/lib/typeorm/metadata-builder/EntityMetadataBuilder.js.map +1 -1
  634. package/lib/typeorm/metadata-builder/EntityMetadataValidator.js +63 -77
  635. package/lib/typeorm/metadata-builder/EntityMetadataValidator.js.map +1 -1
  636. package/lib/typeorm/metadata-builder/JunctionEntityMetadataBuilder.js +64 -69
  637. package/lib/typeorm/metadata-builder/JunctionEntityMetadataBuilder.js.map +1 -1
  638. package/lib/typeorm/metadata-builder/MetadataUtils.js +12 -15
  639. package/lib/typeorm/metadata-builder/MetadataUtils.js.map +1 -1
  640. package/lib/typeorm/metadata-builder/RelationJoinColumnBuilder.js +43 -49
  641. package/lib/typeorm/metadata-builder/RelationJoinColumnBuilder.js.map +1 -1
  642. package/lib/typeorm/migration/Migration.js +23 -4
  643. package/lib/typeorm/migration/Migration.js.map +1 -1
  644. package/lib/typeorm/migration/MigrationExecutor.js +432 -691
  645. package/lib/typeorm/migration/MigrationExecutor.js.map +1 -1
  646. package/lib/typeorm/migration/MigrationInterface.js.map +1 -1
  647. package/lib/typeorm/naming-strategy/DefaultNamingStrategy.js +80 -84
  648. package/lib/typeorm/naming-strategy/DefaultNamingStrategy.js.map +1 -1
  649. package/lib/typeorm/naming-strategy/NamingStrategyInterface.js.map +1 -1
  650. package/lib/typeorm/persistence/EntityPersistExecutor.js +154 -212
  651. package/lib/typeorm/persistence/EntityPersistExecutor.js.map +1 -1
  652. package/lib/typeorm/persistence/Subject.js +162 -149
  653. package/lib/typeorm/persistence/Subject.js.map +1 -1
  654. package/lib/typeorm/persistence/SubjectChangeMap.js.map +1 -1
  655. package/lib/typeorm/persistence/SubjectChangedColumnsComputer.js +29 -35
  656. package/lib/typeorm/persistence/SubjectChangedColumnsComputer.js.map +1 -1
  657. package/lib/typeorm/persistence/SubjectDatabaseEntityLoader.js +99 -130
  658. package/lib/typeorm/persistence/SubjectDatabaseEntityLoader.js.map +1 -1
  659. package/lib/typeorm/persistence/SubjectExecutor.js +635 -879
  660. package/lib/typeorm/persistence/SubjectExecutor.js.map +1 -1
  661. package/lib/typeorm/persistence/SubjectTopoligicalSorter.js +62 -58
  662. package/lib/typeorm/persistence/SubjectTopoligicalSorter.js.map +1 -1
  663. package/lib/typeorm/persistence/subject-builder/CascadesSubjectBuilder.js +16 -19
  664. package/lib/typeorm/persistence/subject-builder/CascadesSubjectBuilder.js.map +1 -1
  665. package/lib/typeorm/persistence/subject-builder/ManyToManySubjectBuilder.js +50 -53
  666. package/lib/typeorm/persistence/subject-builder/ManyToManySubjectBuilder.js.map +1 -1
  667. package/lib/typeorm/persistence/subject-builder/OneToManySubjectBuilder.js +28 -33
  668. package/lib/typeorm/persistence/subject-builder/OneToManySubjectBuilder.js.map +1 -1
  669. package/lib/typeorm/persistence/subject-builder/OneToOneInverseSideSubjectBuilder.js +19 -20
  670. package/lib/typeorm/persistence/subject-builder/OneToOneInverseSideSubjectBuilder.js.map +1 -1
  671. package/lib/typeorm/persistence/tree/ClosureSubjectExecutor.js +202 -271
  672. package/lib/typeorm/persistence/tree/ClosureSubjectExecutor.js.map +1 -1
  673. package/lib/typeorm/persistence/tree/MaterializedPathSubjectExecutor.js +79 -121
  674. package/lib/typeorm/persistence/tree/MaterializedPathSubjectExecutor.js.map +1 -1
  675. package/lib/typeorm/persistence/tree/NestedSetSubjectExecutor.js +220 -353
  676. package/lib/typeorm/persistence/tree/NestedSetSubjectExecutor.js.map +1 -1
  677. package/lib/typeorm/platform/PlatformTools.js +66 -78
  678. package/lib/typeorm/platform/PlatformTools.js.map +1 -1
  679. package/lib/typeorm/query-builder/Alias.js +31 -32
  680. package/lib/typeorm/query-builder/Alias.js.map +1 -1
  681. package/lib/typeorm/query-builder/Brackets.js +8 -5
  682. package/lib/typeorm/query-builder/Brackets.js.map +1 -1
  683. package/lib/typeorm/query-builder/DeleteQueryBuilder.js +96 -120
  684. package/lib/typeorm/query-builder/DeleteQueryBuilder.js.map +1 -1
  685. package/lib/typeorm/query-builder/InsertOrUpdateOptions.js.map +1 -1
  686. package/lib/typeorm/query-builder/InsertQueryBuilder.js +321 -367
  687. package/lib/typeorm/query-builder/InsertQueryBuilder.js.map +1 -1
  688. package/lib/typeorm/query-builder/JoinAttribute.js +175 -206
  689. package/lib/typeorm/query-builder/JoinAttribute.js.map +1 -1
  690. package/lib/typeorm/query-builder/JoinOptions.js.map +1 -1
  691. package/lib/typeorm/query-builder/NotBrackets.js +4 -11
  692. package/lib/typeorm/query-builder/NotBrackets.js.map +1 -1
  693. package/lib/typeorm/query-builder/QueryBuilder.js +400 -646
  694. package/lib/typeorm/query-builder/QueryBuilder.js.map +1 -1
  695. package/lib/typeorm/query-builder/QueryBuilderCte.js.map +1 -1
  696. package/lib/typeorm/query-builder/QueryBuilderUtils.js +5 -9
  697. package/lib/typeorm/query-builder/QueryBuilderUtils.js.map +1 -1
  698. package/lib/typeorm/query-builder/QueryExpressionMap.js +304 -233
  699. package/lib/typeorm/query-builder/QueryExpressionMap.js.map +1 -1
  700. package/lib/typeorm/query-builder/QueryPartialEntity.js.map +1 -1
  701. package/lib/typeorm/query-builder/RelationIdLoader.js +166 -189
  702. package/lib/typeorm/query-builder/RelationIdLoader.js.map +1 -1
  703. package/lib/typeorm/query-builder/RelationLoader.js +81 -94
  704. package/lib/typeorm/query-builder/RelationLoader.js.map +1 -1
  705. package/lib/typeorm/query-builder/RelationQueryBuilder.js +91 -127
  706. package/lib/typeorm/query-builder/RelationQueryBuilder.js.map +1 -1
  707. package/lib/typeorm/query-builder/RelationRemover.js +121 -124
  708. package/lib/typeorm/query-builder/RelationRemover.js.map +1 -1
  709. package/lib/typeorm/query-builder/RelationUpdater.js +130 -148
  710. package/lib/typeorm/query-builder/RelationUpdater.js.map +1 -1
  711. package/lib/typeorm/query-builder/ReturningResultsEntityUpdator.js +131 -159
  712. package/lib/typeorm/query-builder/ReturningResultsEntityUpdator.js.map +1 -1
  713. package/lib/typeorm/query-builder/SelectQuery.js.map +1 -1
  714. package/lib/typeorm/query-builder/SelectQueryBuilder.js +955 -1211
  715. package/lib/typeorm/query-builder/SelectQueryBuilder.js.map +1 -1
  716. package/lib/typeorm/query-builder/SelectQueryBuilderOption.js.map +1 -1
  717. package/lib/typeorm/query-builder/SoftDeleteQueryBuilder.js +155 -194
  718. package/lib/typeorm/query-builder/SoftDeleteQueryBuilder.js.map +1 -1
  719. package/lib/typeorm/query-builder/UpdateQueryBuilder.js +204 -246
  720. package/lib/typeorm/query-builder/UpdateQueryBuilder.js.map +1 -1
  721. package/lib/typeorm/query-builder/WhereClause.js.map +1 -1
  722. package/lib/typeorm/query-builder/WhereExpressionBuilder.js.map +1 -1
  723. package/lib/typeorm/query-builder/relation-count/RelationCountAttribute.js +85 -98
  724. package/lib/typeorm/query-builder/relation-count/RelationCountAttribute.js.map +1 -1
  725. package/lib/typeorm/query-builder/relation-count/RelationCountLoadResult.js.map +1 -1
  726. package/lib/typeorm/query-builder/relation-count/RelationCountLoader.js +153 -172
  727. package/lib/typeorm/query-builder/relation-count/RelationCountLoader.js.map +1 -1
  728. package/lib/typeorm/query-builder/relation-count/RelationCountMetadataToAttributeTransformer.js +16 -17
  729. package/lib/typeorm/query-builder/relation-count/RelationCountMetadataToAttributeTransformer.js.map +1 -1
  730. package/lib/typeorm/query-builder/relation-id/RelationIdAttribute.js +93 -107
  731. package/lib/typeorm/query-builder/relation-id/RelationIdAttribute.js.map +1 -1
  732. package/lib/typeorm/query-builder/relation-id/RelationIdLoadResult.js.map +1 -1
  733. package/lib/typeorm/query-builder/relation-id/RelationIdLoader.js +259 -267
  734. package/lib/typeorm/query-builder/relation-id/RelationIdLoader.js.map +1 -1
  735. package/lib/typeorm/query-builder/relation-id/RelationIdMetadataToAttributeTransformer.js +16 -17
  736. package/lib/typeorm/query-builder/relation-id/RelationIdMetadataToAttributeTransformer.js.map +1 -1
  737. package/lib/typeorm/query-builder/result/DeleteResult.js +14 -8
  738. package/lib/typeorm/query-builder/result/DeleteResult.js.map +1 -1
  739. package/lib/typeorm/query-builder/result/InsertResult.js +19 -18
  740. package/lib/typeorm/query-builder/result/InsertResult.js.map +1 -1
  741. package/lib/typeorm/query-builder/result/UpdateResult.js +24 -18
  742. package/lib/typeorm/query-builder/result/UpdateResult.js.map +1 -1
  743. package/lib/typeorm/query-builder/transformer/DocumentToEntityTransformer.js +24 -26
  744. package/lib/typeorm/query-builder/transformer/DocumentToEntityTransformer.js.map +1 -1
  745. package/lib/typeorm/query-builder/transformer/PlainObjectToDatabaseEntityTransformer.js +77 -112
  746. package/lib/typeorm/query-builder/transformer/PlainObjectToDatabaseEntityTransformer.js.map +1 -1
  747. package/lib/typeorm/query-builder/transformer/PlainObjectToNewEntityTransformer.js +16 -22
  748. package/lib/typeorm/query-builder/transformer/PlainObjectToNewEntityTransformer.js.map +1 -1
  749. package/lib/typeorm/query-builder/transformer/RawSqlResultsToEntityTransformer.js +117 -132
  750. package/lib/typeorm/query-builder/transformer/RawSqlResultsToEntityTransformer.js.map +1 -1
  751. package/lib/typeorm/query-runner/BaseQueryRunner.js +227 -393
  752. package/lib/typeorm/query-runner/BaseQueryRunner.js.map +1 -1
  753. package/lib/typeorm/query-runner/QueryLock.js +19 -32
  754. package/lib/typeorm/query-runner/QueryLock.js.map +1 -1
  755. package/lib/typeorm/query-runner/QueryResult.js +14 -9
  756. package/lib/typeorm/query-runner/QueryResult.js.map +1 -1
  757. package/lib/typeorm/query-runner/QueryRunner.js.map +1 -1
  758. package/lib/typeorm/repository/AbstractRepository.js +46 -50
  759. package/lib/typeorm/repository/AbstractRepository.js.map +1 -1
  760. package/lib/typeorm/repository/BaseEntity.js +106 -123
  761. package/lib/typeorm/repository/BaseEntity.js.map +1 -1
  762. package/lib/typeorm/repository/EntityId.js.map +1 -1
  763. package/lib/typeorm/repository/FindTreesOptions.js.map +1 -1
  764. package/lib/typeorm/repository/MongoRepository.js +109 -135
  765. package/lib/typeorm/repository/MongoRepository.js.map +1 -1
  766. package/lib/typeorm/repository/RemoveOptions.js.map +1 -1
  767. package/lib/typeorm/repository/Repository.js +108 -140
  768. package/lib/typeorm/repository/Repository.js.map +1 -1
  769. package/lib/typeorm/repository/SaveOptions.js.map +1 -1
  770. package/lib/typeorm/repository/TreeRepository.js +107 -154
  771. package/lib/typeorm/repository/TreeRepository.js.map +1 -1
  772. package/lib/typeorm/repository/UpsertOptions.js.map +1 -1
  773. package/lib/typeorm/schema-builder/MongoSchemaBuilder.js +30 -42
  774. package/lib/typeorm/schema-builder/MongoSchemaBuilder.js.map +1 -1
  775. package/lib/typeorm/schema-builder/RdbmsSchemaBuilder.js +727 -1938
  776. package/lib/typeorm/schema-builder/RdbmsSchemaBuilder.js.map +1 -1
  777. package/lib/typeorm/schema-builder/SchemaBuilder.js.map +1 -1
  778. package/lib/typeorm/schema-builder/options/TableCheckOptions.js.map +1 -1
  779. package/lib/typeorm/schema-builder/options/TableColumnOptions.js.map +1 -1
  780. package/lib/typeorm/schema-builder/options/TableExclusionOptions.js.map +1 -1
  781. package/lib/typeorm/schema-builder/options/TableForeignKeyOptions.js.map +1 -1
  782. package/lib/typeorm/schema-builder/options/TableIndexOptions.js.map +1 -1
  783. package/lib/typeorm/schema-builder/options/TableOptions.js.map +1 -1
  784. package/lib/typeorm/schema-builder/options/TableUniqueOptions.js.map +1 -1
  785. package/lib/typeorm/schema-builder/options/ViewOptions.js.map +1 -1
  786. package/lib/typeorm/schema-builder/table/Table.js +160 -157
  787. package/lib/typeorm/schema-builder/table/Table.js.map +1 -1
  788. package/lib/typeorm/schema-builder/table/TableCheck.js +24 -15
  789. package/lib/typeorm/schema-builder/table/TableCheck.js.map +1 -1
  790. package/lib/typeorm/schema-builder/table/TableColumn.js +123 -41
  791. package/lib/typeorm/schema-builder/table/TableColumn.js.map +1 -1
  792. package/lib/typeorm/schema-builder/table/TableExclusion.js +19 -9
  793. package/lib/typeorm/schema-builder/table/TableExclusion.js.map +1 -1
  794. package/lib/typeorm/schema-builder/table/TableForeignKey.js +52 -20
  795. package/lib/typeorm/schema-builder/table/TableForeignKey.js.map +1 -1
  796. package/lib/typeorm/schema-builder/table/TableIndex.js +52 -16
  797. package/lib/typeorm/schema-builder/table/TableIndex.js.map +1 -1
  798. package/lib/typeorm/schema-builder/table/TableUnique.js +26 -16
  799. package/lib/typeorm/schema-builder/table/TableUnique.js.map +1 -1
  800. package/lib/typeorm/schema-builder/util/TableUtils.js +5 -8
  801. package/lib/typeorm/schema-builder/util/TableUtils.js.map +1 -1
  802. package/lib/typeorm/schema-builder/util/ViewUtils.js +4 -7
  803. package/lib/typeorm/schema-builder/util/ViewUtils.js.map +1 -1
  804. package/lib/typeorm/schema-builder/view/View.js +32 -10
  805. package/lib/typeorm/schema-builder/view/View.js.map +1 -1
  806. package/lib/typeorm/subscriber/Broadcaster.js +180 -216
  807. package/lib/typeorm/subscriber/Broadcaster.js.map +1 -1
  808. package/lib/typeorm/subscriber/BroadcasterResult.js +16 -29
  809. package/lib/typeorm/subscriber/BroadcasterResult.js.map +1 -1
  810. package/lib/typeorm/subscriber/EntitySubscriberInterface.js.map +1 -1
  811. package/lib/typeorm/subscriber/event/InsertEvent.js.map +1 -1
  812. package/lib/typeorm/subscriber/event/LoadEvent.js.map +1 -1
  813. package/lib/typeorm/subscriber/event/RecoverEvent.js.map +1 -1
  814. package/lib/typeorm/subscriber/event/RemoveEvent.js.map +1 -1
  815. package/lib/typeorm/subscriber/event/SoftRemoveEvent.js.map +1 -1
  816. package/lib/typeorm/subscriber/event/TransactionCommitEvent.js.map +1 -1
  817. package/lib/typeorm/subscriber/event/TransactionRollbackEvent.js.map +1 -1
  818. package/lib/typeorm/subscriber/event/TransactionStartEvent.js.map +1 -1
  819. package/lib/typeorm/subscriber/event/UpdateEvent.js.map +1 -1
  820. package/lib/typeorm/util/ApplyValueTransformers.js +9 -12
  821. package/lib/typeorm/util/ApplyValueTransformers.js.map +1 -1
  822. package/lib/typeorm/util/DateUtils.js +44 -53
  823. package/lib/typeorm/util/DateUtils.js.map +1 -1
  824. package/lib/typeorm/util/DepGraph.js +50 -53
  825. package/lib/typeorm/util/DepGraph.js.map +1 -1
  826. package/lib/typeorm/util/DirectoryExportedClassesLoader.js +48 -70
  827. package/lib/typeorm/util/DirectoryExportedClassesLoader.js.map +1 -1
  828. package/lib/typeorm/util/ImportUtils.js +43 -65
  829. package/lib/typeorm/util/ImportUtils.js.map +1 -1
  830. package/lib/typeorm/util/InstanceChecker.js +64 -67
  831. package/lib/typeorm/util/InstanceChecker.js.map +1 -1
  832. package/lib/typeorm/util/ObjectUtils.js +13 -42
  833. package/lib/typeorm/util/ObjectUtils.js.map +1 -1
  834. package/lib/typeorm/util/OrmUtils.js +91 -158
  835. package/lib/typeorm/util/OrmUtils.js.map +1 -1
  836. package/lib/typeorm/util/PathUtils.js +8 -8
  837. package/lib/typeorm/util/PathUtils.js.map +1 -1
  838. package/lib/typeorm/util/RandomGenerator.js +22 -25
  839. package/lib/typeorm/util/RandomGenerator.js.map +1 -1
  840. package/lib/typeorm/util/StringUtils.js +17 -21
  841. package/lib/typeorm/util/StringUtils.js.map +1 -1
  842. package/lib/typeorm/util/TreeRepositoryUtils.js +27 -30
  843. package/lib/typeorm/util/TreeRepositoryUtils.js.map +1 -1
  844. package/lib/typeorm/util/VersionUtils.js +9 -13
  845. package/lib/typeorm/util/VersionUtils.js.map +1 -1
  846. package/lib/typeorm/util/escapeRegExp.js +2 -2
  847. package/lib/typeorm/util/escapeRegExp.js.map +1 -1
  848. package/migrations/index.js +15 -2
  849. package/migrations/index.js.map +1 -1
  850. package/migrations/migrations_index._auto-generated_.d.ts +1 -0
  851. package/migrations/migrations_index._auto-generated_.js.map +1 -1
  852. package/package.json +8 -44
  853. package/src.d.ts +1 -1
  854. package/taon.jsonc +3 -30
  855. package/tmp-environment.json +8 -370
  856. package/websql/esm2022/lib/typeorm/driver/cordova/CordovaDriver.mjs +1 -1
  857. package/websql/esm2022/lib/typeorm/driver/cordova/CordovaQueryRunner.mjs +1 -1
  858. package/websql/esm2022/lib/typeorm/driver/nativescript/NativescriptDriver.mjs +1 -1
  859. package/websql/esm2022/lib/typeorm/driver/nativescript/NativescriptQueryRunner.mjs +1 -1
  860. package/websql/esm2022/lib/typeorm/driver/react-native/ReactNativeDriver.mjs +1 -1
  861. package/websql/esm2022/lib/typeorm/driver/react-native/ReactNativeQueryRunner.mjs +1 -1
  862. package/websql/esm2022/lib/typeorm/driver/sqljs/SqljsDriver.mjs +1 -1
  863. package/websql/esm2022/lib/typeorm/driver/sqljs/SqljsQueryRunner.mjs +1 -1
  864. package/websql/esm2022/lib/typeorm/index.mjs +1 -3
  865. package/websql/fesm2022/taon-typeorm.mjs.map +1 -1
  866. package/browser/package.json +0 -25
  867. package/websql/package.json +0 -25
@@ -1,41 +1,52 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MysqlQueryRunner = void 0;
4
- var tslib_1 = require("tslib");
5
4
  //#region @backend
6
- var QueryResult_1 = require("../../query-runner/QueryResult");
7
- var TransactionNotStartedError_1 = require("../../error/TransactionNotStartedError");
8
- var TableColumn_1 = require("../../schema-builder/table/TableColumn");
9
- var Table_1 = require("../../schema-builder/table/Table");
10
- var TableForeignKey_1 = require("../../schema-builder/table/TableForeignKey");
11
- var TableIndex_1 = require("../../schema-builder/table/TableIndex");
12
- var QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
13
- var View_1 = require("../../schema-builder/view/View");
14
- var Query_1 = require("../Query");
15
- var OrmUtils_1 = require("../../util/OrmUtils");
16
- var QueryFailedError_1 = require("../../error/QueryFailedError");
17
- var TableUnique_1 = require("../../schema-builder/table/TableUnique");
18
- var BaseQueryRunner_1 = require("../../query-runner/BaseQueryRunner");
19
- var Broadcaster_1 = require("../../subscriber/Broadcaster");
20
- var VersionUtils_1 = require("../../util/VersionUtils");
21
- var error_1 = require("../../error");
22
- var MetadataTableType_1 = require("../types/MetadataTableType");
23
- var InstanceChecker_1 = require("../../util/InstanceChecker");
5
+ const QueryResult_1 = require("../../query-runner/QueryResult");
6
+ const TransactionNotStartedError_1 = require("../../error/TransactionNotStartedError");
7
+ const TableColumn_1 = require("../../schema-builder/table/TableColumn");
8
+ const Table_1 = require("../../schema-builder/table/Table");
9
+ const TableForeignKey_1 = require("../../schema-builder/table/TableForeignKey");
10
+ const TableIndex_1 = require("../../schema-builder/table/TableIndex");
11
+ const QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
12
+ const View_1 = require("../../schema-builder/view/View");
13
+ const Query_1 = require("../Query");
14
+ const OrmUtils_1 = require("../../util/OrmUtils");
15
+ const QueryFailedError_1 = require("../../error/QueryFailedError");
16
+ const TableUnique_1 = require("../../schema-builder/table/TableUnique");
17
+ const BaseQueryRunner_1 = require("../../query-runner/BaseQueryRunner");
18
+ const Broadcaster_1 = require("../../subscriber/Broadcaster");
19
+ const VersionUtils_1 = require("../../util/VersionUtils");
20
+ const error_1 = require("../../error");
21
+ const MetadataTableType_1 = require("../types/MetadataTableType");
22
+ const InstanceChecker_1 = require("../../util/InstanceChecker");
24
23
  /**
25
24
  * Runs queries on a single mysql database connection.
26
25
  */
27
- var MysqlQueryRunner = /** @class */ (function (_super) {
28
- tslib_1.__extends(MysqlQueryRunner, _super);
26
+ class MysqlQueryRunner extends BaseQueryRunner_1.BaseQueryRunner {
27
+ // -------------------------------------------------------------------------
28
+ // Public Implemented Properties
29
+ // -------------------------------------------------------------------------
30
+ /**
31
+ * Database driver used by connection.
32
+ */
33
+ driver;
34
+ // -------------------------------------------------------------------------
35
+ // Protected Properties
36
+ // -------------------------------------------------------------------------
37
+ /**
38
+ * Promise used to obtain a database connection from a pool for a first time.
39
+ */
40
+ databaseConnectionPromise;
29
41
  // -------------------------------------------------------------------------
30
42
  // Constructor
31
43
  // -------------------------------------------------------------------------
32
- function MysqlQueryRunner(driver, mode) {
33
- var _this = _super.call(this) || this;
34
- _this.driver = driver;
35
- _this.connection = driver.connection;
36
- _this.broadcaster = new Broadcaster_1.Broadcaster(_this);
37
- _this.mode = mode;
38
- return _this;
44
+ constructor(driver, mode) {
45
+ super();
46
+ this.driver = driver;
47
+ this.connection = driver.connection;
48
+ this.broadcaster = new Broadcaster_1.Broadcaster(this);
49
+ this.mode = mode;
39
50
  }
40
51
  // -------------------------------------------------------------------------
41
52
  // Public Methods
@@ -44,8 +55,7 @@ var MysqlQueryRunner = /** @class */ (function (_super) {
44
55
  * Creates/uses database connection from the connection pool to perform further operations.
45
56
  * Returns obtained database connection.
46
57
  */
47
- MysqlQueryRunner.prototype.connect = function () {
48
- var _this = this;
58
+ connect() {
49
59
  if (this.databaseConnection)
50
60
  return Promise.resolve(this.databaseConnection);
51
61
  if (this.databaseConnectionPromise)
@@ -53,2508 +63,1753 @@ var MysqlQueryRunner = /** @class */ (function (_super) {
53
63
  if (this.mode === "slave" && this.driver.isReplicated) {
54
64
  this.databaseConnectionPromise = this.driver
55
65
  .obtainSlaveConnection()
56
- .then(function (connection) {
57
- _this.databaseConnection = connection;
58
- return _this.databaseConnection;
66
+ .then((connection) => {
67
+ this.databaseConnection = connection;
68
+ return this.databaseConnection;
59
69
  });
60
70
  }
61
71
  else {
62
72
  // master
63
73
  this.databaseConnectionPromise = this.driver
64
74
  .obtainMasterConnection()
65
- .then(function (connection) {
66
- _this.databaseConnection = connection;
67
- return _this.databaseConnection;
75
+ .then((connection) => {
76
+ this.databaseConnection = connection;
77
+ return this.databaseConnection;
68
78
  });
69
79
  }
70
80
  return this.databaseConnectionPromise;
71
- };
81
+ }
72
82
  /**
73
83
  * Releases used database connection.
74
84
  * You cannot use query runner methods once its released.
75
85
  */
76
- MysqlQueryRunner.prototype.release = function () {
86
+ release() {
77
87
  this.isReleased = true;
78
88
  if (this.databaseConnection)
79
89
  this.databaseConnection.release();
80
90
  return Promise.resolve();
81
- };
91
+ }
82
92
  /**
83
93
  * Starts transaction on the current connection.
84
94
  */
85
- MysqlQueryRunner.prototype.startTransaction = function (isolationLevel) {
86
- return tslib_1.__awaiter(this, void 0, void 0, function () {
87
- var err_1;
88
- return tslib_1.__generator(this, function (_a) {
89
- switch (_a.label) {
90
- case 0:
91
- this.isTransactionActive = true;
92
- _a.label = 1;
93
- case 1:
94
- _a.trys.push([1, 3, , 4]);
95
- return [4 /*yield*/, this.broadcaster.broadcast("BeforeTransactionStart")];
96
- case 2:
97
- _a.sent();
98
- return [3 /*break*/, 4];
99
- case 3:
100
- err_1 = _a.sent();
101
- this.isTransactionActive = false;
102
- throw err_1;
103
- case 4:
104
- if (!(this.transactionDepth === 0)) return [3 /*break*/, 8];
105
- if (!isolationLevel) return [3 /*break*/, 6];
106
- return [4 /*yield*/, this.query("SET TRANSACTION ISOLATION LEVEL " + isolationLevel)];
107
- case 5:
108
- _a.sent();
109
- _a.label = 6;
110
- case 6: return [4 /*yield*/, this.query("START TRANSACTION")];
111
- case 7:
112
- _a.sent();
113
- return [3 /*break*/, 10];
114
- case 8: return [4 /*yield*/, this.query("SAVEPOINT typeorm_".concat(this.transactionDepth))];
115
- case 9:
116
- _a.sent();
117
- _a.label = 10;
118
- case 10:
119
- this.transactionDepth += 1;
120
- return [4 /*yield*/, this.broadcaster.broadcast("AfterTransactionStart")];
121
- case 11:
122
- _a.sent();
123
- return [2 /*return*/];
124
- }
125
- });
126
- });
127
- };
95
+ async startTransaction(isolationLevel) {
96
+ this.isTransactionActive = true;
97
+ try {
98
+ await this.broadcaster.broadcast("BeforeTransactionStart");
99
+ }
100
+ catch (err) {
101
+ this.isTransactionActive = false;
102
+ throw err;
103
+ }
104
+ if (this.transactionDepth === 0) {
105
+ if (isolationLevel) {
106
+ await this.query("SET TRANSACTION ISOLATION LEVEL " + isolationLevel);
107
+ }
108
+ await this.query("START TRANSACTION");
109
+ }
110
+ else {
111
+ await this.query(`SAVEPOINT typeorm_${this.transactionDepth}`);
112
+ }
113
+ this.transactionDepth += 1;
114
+ await this.broadcaster.broadcast("AfterTransactionStart");
115
+ }
128
116
  /**
129
117
  * Commits transaction.
130
118
  * Error will be thrown if transaction was not started.
131
119
  */
132
- MysqlQueryRunner.prototype.commitTransaction = function () {
133
- return tslib_1.__awaiter(this, void 0, void 0, function () {
134
- return tslib_1.__generator(this, function (_a) {
135
- switch (_a.label) {
136
- case 0:
137
- if (!this.isTransactionActive)
138
- throw new TransactionNotStartedError_1.TransactionNotStartedError();
139
- return [4 /*yield*/, this.broadcaster.broadcast("BeforeTransactionCommit")];
140
- case 1:
141
- _a.sent();
142
- if (!(this.transactionDepth > 1)) return [3 /*break*/, 3];
143
- return [4 /*yield*/, this.query("RELEASE SAVEPOINT typeorm_".concat(this.transactionDepth - 1))];
144
- case 2:
145
- _a.sent();
146
- return [3 /*break*/, 5];
147
- case 3: return [4 /*yield*/, this.query("COMMIT")];
148
- case 4:
149
- _a.sent();
150
- this.isTransactionActive = false;
151
- _a.label = 5;
152
- case 5:
153
- this.transactionDepth -= 1;
154
- return [4 /*yield*/, this.broadcaster.broadcast("AfterTransactionCommit")];
155
- case 6:
156
- _a.sent();
157
- return [2 /*return*/];
158
- }
159
- });
160
- });
161
- };
120
+ async commitTransaction() {
121
+ if (!this.isTransactionActive)
122
+ throw new TransactionNotStartedError_1.TransactionNotStartedError();
123
+ await this.broadcaster.broadcast("BeforeTransactionCommit");
124
+ if (this.transactionDepth > 1) {
125
+ await this.query(`RELEASE SAVEPOINT typeorm_${this.transactionDepth - 1}`);
126
+ }
127
+ else {
128
+ await this.query("COMMIT");
129
+ this.isTransactionActive = false;
130
+ }
131
+ this.transactionDepth -= 1;
132
+ await this.broadcaster.broadcast("AfterTransactionCommit");
133
+ }
162
134
  /**
163
135
  * Rollbacks transaction.
164
136
  * Error will be thrown if transaction was not started.
165
137
  */
166
- MysqlQueryRunner.prototype.rollbackTransaction = function () {
167
- return tslib_1.__awaiter(this, void 0, void 0, function () {
168
- return tslib_1.__generator(this, function (_a) {
169
- switch (_a.label) {
170
- case 0:
171
- if (!this.isTransactionActive)
172
- throw new TransactionNotStartedError_1.TransactionNotStartedError();
173
- return [4 /*yield*/, this.broadcaster.broadcast("BeforeTransactionRollback")];
174
- case 1:
175
- _a.sent();
176
- if (!(this.transactionDepth > 1)) return [3 /*break*/, 3];
177
- return [4 /*yield*/, this.query("ROLLBACK TO SAVEPOINT typeorm_".concat(this.transactionDepth - 1))];
178
- case 2:
179
- _a.sent();
180
- return [3 /*break*/, 5];
181
- case 3: return [4 /*yield*/, this.query("ROLLBACK")];
182
- case 4:
183
- _a.sent();
184
- this.isTransactionActive = false;
185
- _a.label = 5;
186
- case 5:
187
- this.transactionDepth -= 1;
188
- return [4 /*yield*/, this.broadcaster.broadcast("AfterTransactionRollback")];
189
- case 6:
190
- _a.sent();
191
- return [2 /*return*/];
192
- }
193
- });
194
- });
195
- };
138
+ async rollbackTransaction() {
139
+ if (!this.isTransactionActive)
140
+ throw new TransactionNotStartedError_1.TransactionNotStartedError();
141
+ await this.broadcaster.broadcast("BeforeTransactionRollback");
142
+ if (this.transactionDepth > 1) {
143
+ await this.query(`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth - 1}`);
144
+ }
145
+ else {
146
+ await this.query("ROLLBACK");
147
+ this.isTransactionActive = false;
148
+ }
149
+ this.transactionDepth -= 1;
150
+ await this.broadcaster.broadcast("AfterTransactionRollback");
151
+ }
196
152
  /**
197
153
  * Executes a raw SQL query.
198
154
  */
199
- MysqlQueryRunner.prototype.query = function (query_1, parameters_1) {
200
- return tslib_1.__awaiter(this, arguments, void 0, function (query, parameters, useStructuredResult) {
201
- var _this = this;
202
- if (useStructuredResult === void 0) { useStructuredResult = false; }
203
- return tslib_1.__generator(this, function (_a) {
204
- if (this.isReleased)
205
- throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
206
- return [2 /*return*/, new Promise(function (ok, fail) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
207
- var databaseConnection, queryStartTime_1, err_2;
208
- var _this = this;
209
- return tslib_1.__generator(this, function (_a) {
210
- switch (_a.label) {
211
- case 0:
212
- _a.trys.push([0, 2, , 3]);
213
- return [4 /*yield*/, this.connect()];
214
- case 1:
215
- databaseConnection = _a.sent();
216
- this.driver.connection.logger.logQuery(query, parameters, this);
217
- queryStartTime_1 = +new Date();
218
- databaseConnection.query(query, parameters, function (err, raw) {
219
- // log slow queries if maxQueryExecution time is set
220
- var maxQueryExecutionTime = _this.driver.options.maxQueryExecutionTime;
221
- var queryEndTime = +new Date();
222
- var queryExecutionTime = queryEndTime - queryStartTime_1;
223
- if (maxQueryExecutionTime &&
224
- queryExecutionTime > maxQueryExecutionTime)
225
- _this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, _this);
226
- if (err) {
227
- _this.driver.connection.logger.logQueryError(err, query, parameters, _this);
228
- return fail(new QueryFailedError_1.QueryFailedError(query, parameters, err));
229
- }
230
- var result = new QueryResult_1.QueryResult();
231
- result.raw = raw;
232
- try {
233
- result.records = Array.from(raw);
234
- }
235
- catch (_a) {
236
- // Do nothing.
237
- }
238
- if (raw === null || raw === void 0 ? void 0 : raw.hasOwnProperty("affectedRows")) {
239
- result.affected = raw.affectedRows;
240
- }
241
- if (useStructuredResult) {
242
- ok(result);
243
- }
244
- else {
245
- ok(result.raw);
246
- }
247
- });
248
- return [3 /*break*/, 3];
249
- case 2:
250
- err_2 = _a.sent();
251
- fail(err_2);
252
- return [3 /*break*/, 3];
253
- case 3: return [2 /*return*/];
254
- }
255
- });
256
- }); })];
257
- });
155
+ async query(query, parameters, useStructuredResult = false) {
156
+ if (this.isReleased)
157
+ throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
158
+ return new Promise(async (ok, fail) => {
159
+ try {
160
+ const databaseConnection = await this.connect();
161
+ this.driver.connection.logger.logQuery(query, parameters, this);
162
+ const queryStartTime = +new Date();
163
+ databaseConnection.query(query, parameters, (err, raw) => {
164
+ // log slow queries if maxQueryExecution time is set
165
+ const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;
166
+ const queryEndTime = +new Date();
167
+ const queryExecutionTime = queryEndTime - queryStartTime;
168
+ if (maxQueryExecutionTime &&
169
+ queryExecutionTime > maxQueryExecutionTime)
170
+ this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);
171
+ if (err) {
172
+ this.driver.connection.logger.logQueryError(err, query, parameters, this);
173
+ return fail(new QueryFailedError_1.QueryFailedError(query, parameters, err));
174
+ }
175
+ const result = new QueryResult_1.QueryResult();
176
+ result.raw = raw;
177
+ try {
178
+ result.records = Array.from(raw);
179
+ }
180
+ catch {
181
+ // Do nothing.
182
+ }
183
+ if (raw?.hasOwnProperty("affectedRows")) {
184
+ result.affected = raw.affectedRows;
185
+ }
186
+ if (useStructuredResult) {
187
+ ok(result);
188
+ }
189
+ else {
190
+ ok(result.raw);
191
+ }
192
+ });
193
+ }
194
+ catch (err) {
195
+ fail(err);
196
+ }
258
197
  });
259
- };
198
+ }
260
199
  /**
261
200
  * Returns raw data stream.
262
201
  */
263
- MysqlQueryRunner.prototype.stream = function (query, parameters, onEnd, onError) {
264
- var _this = this;
202
+ stream(query, parameters, onEnd, onError) {
265
203
  if (this.isReleased)
266
204
  throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
267
- return new Promise(function (ok, fail) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
268
- var databaseConnection, databaseQuery, err_3;
269
- return tslib_1.__generator(this, function (_a) {
270
- switch (_a.label) {
271
- case 0:
272
- _a.trys.push([0, 2, , 3]);
273
- return [4 /*yield*/, this.connect()];
274
- case 1:
275
- databaseConnection = _a.sent();
276
- this.driver.connection.logger.logQuery(query, parameters, this);
277
- databaseQuery = databaseConnection.query(query, parameters);
278
- if (onEnd)
279
- databaseQuery.on("end", onEnd);
280
- if (onError)
281
- databaseQuery.on("error", onError);
282
- ok(databaseQuery.stream());
283
- return [3 /*break*/, 3];
284
- case 2:
285
- err_3 = _a.sent();
286
- fail(err_3);
287
- return [3 /*break*/, 3];
288
- case 3: return [2 /*return*/];
289
- }
290
- });
291
- }); });
292
- };
205
+ return new Promise(async (ok, fail) => {
206
+ try {
207
+ const databaseConnection = await this.connect();
208
+ this.driver.connection.logger.logQuery(query, parameters, this);
209
+ const databaseQuery = databaseConnection.query(query, parameters);
210
+ if (onEnd)
211
+ databaseQuery.on("end", onEnd);
212
+ if (onError)
213
+ databaseQuery.on("error", onError);
214
+ ok(databaseQuery.stream());
215
+ }
216
+ catch (err) {
217
+ fail(err);
218
+ }
219
+ });
220
+ }
293
221
  /**
294
222
  * Returns all available database names including system databases.
295
223
  */
296
- MysqlQueryRunner.prototype.getDatabases = function () {
297
- return tslib_1.__awaiter(this, void 0, void 0, function () {
298
- return tslib_1.__generator(this, function (_a) {
299
- return [2 /*return*/, Promise.resolve([])];
300
- });
301
- });
302
- };
224
+ async getDatabases() {
225
+ return Promise.resolve([]);
226
+ }
303
227
  /**
304
228
  * Returns all available schema names including system schemas.
305
229
  * If database parameter specified, returns schemas of that database.
306
230
  */
307
- MysqlQueryRunner.prototype.getSchemas = function (database) {
308
- return tslib_1.__awaiter(this, void 0, void 0, function () {
309
- return tslib_1.__generator(this, function (_a) {
310
- throw new error_1.TypeORMError("MySql driver does not support table schemas");
311
- });
312
- });
313
- };
231
+ async getSchemas(database) {
232
+ throw new error_1.TypeORMError(`MySql driver does not support table schemas`);
233
+ }
314
234
  /**
315
235
  * Checks if database with the given name exist.
316
236
  */
317
- MysqlQueryRunner.prototype.hasDatabase = function (database) {
318
- return tslib_1.__awaiter(this, void 0, void 0, function () {
319
- var result;
320
- return tslib_1.__generator(this, function (_a) {
321
- switch (_a.label) {
322
- case 0: return [4 /*yield*/, this.query("SELECT * FROM `INFORMATION_SCHEMA`.`SCHEMATA` WHERE `SCHEMA_NAME` = '".concat(database, "'"))];
323
- case 1:
324
- result = _a.sent();
325
- return [2 /*return*/, result.length ? true : false];
326
- }
327
- });
328
- });
329
- };
237
+ async hasDatabase(database) {
238
+ const result = await this.query(`SELECT * FROM \`INFORMATION_SCHEMA\`.\`SCHEMATA\` WHERE \`SCHEMA_NAME\` = '${database}'`);
239
+ return result.length ? true : false;
240
+ }
330
241
  /**
331
242
  * Loads currently using database
332
243
  */
333
- MysqlQueryRunner.prototype.getCurrentDatabase = function () {
334
- return tslib_1.__awaiter(this, void 0, void 0, function () {
335
- var query;
336
- return tslib_1.__generator(this, function (_a) {
337
- switch (_a.label) {
338
- case 0: return [4 /*yield*/, this.query("SELECT DATABASE() AS `db_name`")];
339
- case 1:
340
- query = _a.sent();
341
- return [2 /*return*/, query[0]["db_name"]];
342
- }
343
- });
344
- });
345
- };
244
+ async getCurrentDatabase() {
245
+ const query = await this.query(`SELECT DATABASE() AS \`db_name\``);
246
+ return query[0]["db_name"];
247
+ }
346
248
  /**
347
249
  * Checks if schema with the given name exist.
348
250
  */
349
- MysqlQueryRunner.prototype.hasSchema = function (schema) {
350
- return tslib_1.__awaiter(this, void 0, void 0, function () {
351
- return tslib_1.__generator(this, function (_a) {
352
- throw new error_1.TypeORMError("MySql driver does not support table schemas");
353
- });
354
- });
355
- };
251
+ async hasSchema(schema) {
252
+ throw new error_1.TypeORMError(`MySql driver does not support table schemas`);
253
+ }
356
254
  /**
357
255
  * Loads currently using database schema
358
256
  */
359
- MysqlQueryRunner.prototype.getCurrentSchema = function () {
360
- return tslib_1.__awaiter(this, void 0, void 0, function () {
361
- var query;
362
- return tslib_1.__generator(this, function (_a) {
363
- switch (_a.label) {
364
- case 0: return [4 /*yield*/, this.query("SELECT SCHEMA() AS `schema_name`")];
365
- case 1:
366
- query = _a.sent();
367
- return [2 /*return*/, query[0]["schema_name"]];
368
- }
369
- });
370
- });
371
- };
257
+ async getCurrentSchema() {
258
+ const query = await this.query(`SELECT SCHEMA() AS \`schema_name\``);
259
+ return query[0]["schema_name"];
260
+ }
372
261
  /**
373
262
  * Checks if table with the given name exist in the database.
374
263
  */
375
- MysqlQueryRunner.prototype.hasTable = function (tableOrName) {
376
- return tslib_1.__awaiter(this, void 0, void 0, function () {
377
- var parsedTableName, sql, result;
378
- return tslib_1.__generator(this, function (_a) {
379
- switch (_a.label) {
380
- case 0:
381
- parsedTableName = this.driver.parseTableName(tableOrName);
382
- sql = "SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = '".concat(parsedTableName.database, "' AND `TABLE_NAME` = '").concat(parsedTableName.tableName, "'");
383
- return [4 /*yield*/, this.query(sql)];
384
- case 1:
385
- result = _a.sent();
386
- return [2 /*return*/, result.length ? true : false];
387
- }
388
- });
389
- });
390
- };
264
+ async hasTable(tableOrName) {
265
+ const parsedTableName = this.driver.parseTableName(tableOrName);
266
+ const sql = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = '${parsedTableName.database}' AND \`TABLE_NAME\` = '${parsedTableName.tableName}'`;
267
+ const result = await this.query(sql);
268
+ return result.length ? true : false;
269
+ }
391
270
  /**
392
271
  * Checks if column with the given name exist in the given table.
393
272
  */
394
- MysqlQueryRunner.prototype.hasColumn = function (tableOrName, column) {
395
- return tslib_1.__awaiter(this, void 0, void 0, function () {
396
- var parsedTableName, columnName, sql, result;
397
- return tslib_1.__generator(this, function (_a) {
398
- switch (_a.label) {
399
- case 0:
400
- parsedTableName = this.driver.parseTableName(tableOrName);
401
- columnName = InstanceChecker_1.InstanceChecker.isTableColumn(column)
402
- ? column.name
403
- : column;
404
- sql = "SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = '".concat(parsedTableName.database, "' AND `TABLE_NAME` = '").concat(parsedTableName.tableName, "' AND `COLUMN_NAME` = '").concat(columnName, "'");
405
- return [4 /*yield*/, this.query(sql)];
406
- case 1:
407
- result = _a.sent();
408
- return [2 /*return*/, result.length ? true : false];
409
- }
410
- });
411
- });
412
- };
273
+ async hasColumn(tableOrName, column) {
274
+ const parsedTableName = this.driver.parseTableName(tableOrName);
275
+ const columnName = InstanceChecker_1.InstanceChecker.isTableColumn(column)
276
+ ? column.name
277
+ : column;
278
+ const sql = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = '${parsedTableName.database}' AND \`TABLE_NAME\` = '${parsedTableName.tableName}' AND \`COLUMN_NAME\` = '${columnName}'`;
279
+ const result = await this.query(sql);
280
+ return result.length ? true : false;
281
+ }
413
282
  /**
414
283
  * Creates a new database.
415
284
  */
416
- MysqlQueryRunner.prototype.createDatabase = function (database, ifNotExist) {
417
- return tslib_1.__awaiter(this, void 0, void 0, function () {
418
- var up, down;
419
- return tslib_1.__generator(this, function (_a) {
420
- switch (_a.label) {
421
- case 0:
422
- up = ifNotExist
423
- ? "CREATE DATABASE IF NOT EXISTS `".concat(database, "`")
424
- : "CREATE DATABASE `".concat(database, "`");
425
- down = "DROP DATABASE `".concat(database, "`");
426
- return [4 /*yield*/, this.executeQueries(new Query_1.Query(up), new Query_1.Query(down))];
427
- case 1:
428
- _a.sent();
429
- return [2 /*return*/];
430
- }
431
- });
432
- });
433
- };
285
+ async createDatabase(database, ifNotExist) {
286
+ const up = ifNotExist
287
+ ? `CREATE DATABASE IF NOT EXISTS \`${database}\``
288
+ : `CREATE DATABASE \`${database}\``;
289
+ const down = `DROP DATABASE \`${database}\``;
290
+ await this.executeQueries(new Query_1.Query(up), new Query_1.Query(down));
291
+ }
434
292
  /**
435
293
  * Drops database.
436
294
  */
437
- MysqlQueryRunner.prototype.dropDatabase = function (database, ifExist) {
438
- return tslib_1.__awaiter(this, void 0, void 0, function () {
439
- var up, down;
440
- return tslib_1.__generator(this, function (_a) {
441
- switch (_a.label) {
442
- case 0:
443
- up = ifExist
444
- ? "DROP DATABASE IF EXISTS `".concat(database, "`")
445
- : "DROP DATABASE `".concat(database, "`");
446
- down = "CREATE DATABASE `".concat(database, "`");
447
- return [4 /*yield*/, this.executeQueries(new Query_1.Query(up), new Query_1.Query(down))];
448
- case 1:
449
- _a.sent();
450
- return [2 /*return*/];
451
- }
452
- });
453
- });
454
- };
295
+ async dropDatabase(database, ifExist) {
296
+ const up = ifExist
297
+ ? `DROP DATABASE IF EXISTS \`${database}\``
298
+ : `DROP DATABASE \`${database}\``;
299
+ const down = `CREATE DATABASE \`${database}\``;
300
+ await this.executeQueries(new Query_1.Query(up), new Query_1.Query(down));
301
+ }
455
302
  /**
456
303
  * Creates a new table schema.
457
304
  */
458
- MysqlQueryRunner.prototype.createSchema = function (schemaPath, ifNotExist) {
459
- return tslib_1.__awaiter(this, void 0, void 0, function () {
460
- return tslib_1.__generator(this, function (_a) {
461
- throw new error_1.TypeORMError("Schema create queries are not supported by MySql driver.");
462
- });
463
- });
464
- };
305
+ async createSchema(schemaPath, ifNotExist) {
306
+ throw new error_1.TypeORMError(`Schema create queries are not supported by MySql driver.`);
307
+ }
465
308
  /**
466
309
  * Drops table schema.
467
310
  */
468
- MysqlQueryRunner.prototype.dropSchema = function (schemaPath, ifExist) {
469
- return tslib_1.__awaiter(this, void 0, void 0, function () {
470
- return tslib_1.__generator(this, function (_a) {
471
- throw new error_1.TypeORMError("Schema drop queries are not supported by MySql driver.");
472
- });
473
- });
474
- };
311
+ async dropSchema(schemaPath, ifExist) {
312
+ throw new error_1.TypeORMError(`Schema drop queries are not supported by MySql driver.`);
313
+ }
475
314
  /**
476
315
  * Creates a new table.
477
316
  */
478
- MysqlQueryRunner.prototype.createTable = function (table_1) {
479
- return tslib_1.__awaiter(this, arguments, void 0, function (table, ifNotExist, createForeignKeys) {
480
- var isTableExist, upQueries, downQueries, generatedColumns, generatedColumns_1, generatedColumns_1_1, column, currentDatabase, insertQuery, deleteQuery, e_1_1;
481
- var e_1, _a;
482
- var _this = this;
483
- if (ifNotExist === void 0) { ifNotExist = false; }
484
- if (createForeignKeys === void 0) { createForeignKeys = true; }
485
- return tslib_1.__generator(this, function (_b) {
486
- switch (_b.label) {
487
- case 0:
488
- if (!ifNotExist) return [3 /*break*/, 2];
489
- return [4 /*yield*/, this.hasTable(table)];
490
- case 1:
491
- isTableExist = _b.sent();
492
- if (isTableExist)
493
- return [2 /*return*/, Promise.resolve()];
494
- _b.label = 2;
495
- case 2:
496
- upQueries = [];
497
- downQueries = [];
498
- upQueries.push(this.createTableSql(table, createForeignKeys));
499
- downQueries.push(this.dropTableSql(table));
500
- // we must first drop indices, than drop foreign keys, because drop queries runs in reversed order
501
- // and foreign keys will be dropped first as indices. This order is very important, because we can't drop index
502
- // if it related to the foreign key.
503
- // createTable does not need separate method to create indices, because it create indices in the same query with table creation.
504
- table.indices.forEach(function (index) {
505
- return downQueries.push(_this.dropIndexSql(table, index));
506
- });
507
- // if createForeignKeys is true, we must drop created foreign keys in down query.
508
- // createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation.
509
- if (createForeignKeys)
510
- table.foreignKeys.forEach(function (foreignKey) {
511
- return downQueries.push(_this.dropForeignKeySql(table, foreignKey));
512
- });
513
- generatedColumns = table.columns.filter(function (column) { return column.generatedType && column.asExpression; });
514
- _b.label = 3;
515
- case 3:
516
- _b.trys.push([3, 8, 9, 10]);
517
- generatedColumns_1 = tslib_1.__values(generatedColumns), generatedColumns_1_1 = generatedColumns_1.next();
518
- _b.label = 4;
519
- case 4:
520
- if (!!generatedColumns_1_1.done) return [3 /*break*/, 7];
521
- column = generatedColumns_1_1.value;
522
- return [4 /*yield*/, this.getCurrentDatabase()];
523
- case 5:
524
- currentDatabase = _b.sent();
525
- insertQuery = this.insertTypeormMetadataSql({
526
- schema: currentDatabase,
527
- table: table.name,
528
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
529
- name: column.name,
530
- value: column.asExpression,
531
- });
532
- deleteQuery = this.deleteTypeormMetadataSql({
533
- schema: currentDatabase,
534
- table: table.name,
535
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
536
- name: column.name,
537
- });
538
- upQueries.push(insertQuery);
539
- downQueries.push(deleteQuery);
540
- _b.label = 6;
541
- case 6:
542
- generatedColumns_1_1 = generatedColumns_1.next();
543
- return [3 /*break*/, 4];
544
- case 7: return [3 /*break*/, 10];
545
- case 8:
546
- e_1_1 = _b.sent();
547
- e_1 = { error: e_1_1 };
548
- return [3 /*break*/, 10];
549
- case 9:
550
- try {
551
- if (generatedColumns_1_1 && !generatedColumns_1_1.done && (_a = generatedColumns_1.return)) _a.call(generatedColumns_1);
552
- }
553
- finally { if (e_1) throw e_1.error; }
554
- return [7 /*endfinally*/];
555
- case 10: return [2 /*return*/, this.executeQueries(upQueries, downQueries)];
556
- }
557
- });
558
- });
559
- };
317
+ async createTable(table, ifNotExist = false, createForeignKeys = true) {
318
+ if (ifNotExist) {
319
+ const isTableExist = await this.hasTable(table);
320
+ if (isTableExist)
321
+ return Promise.resolve();
322
+ }
323
+ const upQueries = [];
324
+ const downQueries = [];
325
+ upQueries.push(this.createTableSql(table, createForeignKeys));
326
+ downQueries.push(this.dropTableSql(table));
327
+ // we must first drop indices, than drop foreign keys, because drop queries runs in reversed order
328
+ // and foreign keys will be dropped first as indices. This order is very important, because we can't drop index
329
+ // if it related to the foreign key.
330
+ // createTable does not need separate method to create indices, because it create indices in the same query with table creation.
331
+ table.indices.forEach((index) => downQueries.push(this.dropIndexSql(table, index)));
332
+ // if createForeignKeys is true, we must drop created foreign keys in down query.
333
+ // createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation.
334
+ if (createForeignKeys)
335
+ table.foreignKeys.forEach((foreignKey) => downQueries.push(this.dropForeignKeySql(table, foreignKey)));
336
+ // if table has column with generated type, we must add the expression to the metadata table
337
+ const generatedColumns = table.columns.filter((column) => column.generatedType && column.asExpression);
338
+ for (const column of generatedColumns) {
339
+ const currentDatabase = await this.getCurrentDatabase();
340
+ const insertQuery = this.insertTypeormMetadataSql({
341
+ schema: currentDatabase,
342
+ table: table.name,
343
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
344
+ name: column.name,
345
+ value: column.asExpression,
346
+ });
347
+ const deleteQuery = this.deleteTypeormMetadataSql({
348
+ schema: currentDatabase,
349
+ table: table.name,
350
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
351
+ name: column.name,
352
+ });
353
+ upQueries.push(insertQuery);
354
+ downQueries.push(deleteQuery);
355
+ }
356
+ return this.executeQueries(upQueries, downQueries);
357
+ }
560
358
  /**
561
359
  * Drop the table.
562
360
  */
563
- MysqlQueryRunner.prototype.dropTable = function (target_1, ifExist_1) {
564
- return tslib_1.__awaiter(this, arguments, void 0, function (target, ifExist, dropForeignKeys) {
565
- var isTableExist, createForeignKeys, tablePath, table, upQueries, downQueries, generatedColumns, generatedColumns_2, generatedColumns_2_1, column, currentDatabase, deleteQuery, insertQuery, e_2_1;
566
- var e_2, _a;
567
- var _this = this;
568
- if (dropForeignKeys === void 0) { dropForeignKeys = true; }
569
- return tslib_1.__generator(this, function (_b) {
570
- switch (_b.label) {
571
- case 0:
572
- if (!ifExist) return [3 /*break*/, 2];
573
- return [4 /*yield*/, this.hasTable(target)];
574
- case 1:
575
- isTableExist = _b.sent();
576
- if (!isTableExist)
577
- return [2 /*return*/, Promise.resolve()];
578
- _b.label = 2;
579
- case 2:
580
- createForeignKeys = dropForeignKeys;
581
- tablePath = this.getTablePath(target);
582
- return [4 /*yield*/, this.getCachedTable(tablePath)];
583
- case 3:
584
- table = _b.sent();
585
- upQueries = [];
586
- downQueries = [];
587
- if (dropForeignKeys)
588
- table.foreignKeys.forEach(function (foreignKey) {
589
- return upQueries.push(_this.dropForeignKeySql(table, foreignKey));
590
- });
591
- table.indices.forEach(function (index) {
592
- return upQueries.push(_this.dropIndexSql(table, index));
593
- });
594
- upQueries.push(this.dropTableSql(table));
595
- downQueries.push(this.createTableSql(table, createForeignKeys));
596
- generatedColumns = table.columns.filter(function (column) { return column.generatedType && column.asExpression; });
597
- _b.label = 4;
598
- case 4:
599
- _b.trys.push([4, 9, 10, 11]);
600
- generatedColumns_2 = tslib_1.__values(generatedColumns), generatedColumns_2_1 = generatedColumns_2.next();
601
- _b.label = 5;
602
- case 5:
603
- if (!!generatedColumns_2_1.done) return [3 /*break*/, 8];
604
- column = generatedColumns_2_1.value;
605
- return [4 /*yield*/, this.getCurrentDatabase()];
606
- case 6:
607
- currentDatabase = _b.sent();
608
- deleteQuery = this.deleteTypeormMetadataSql({
609
- schema: currentDatabase,
610
- table: table.name,
611
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
612
- name: column.name,
613
- });
614
- insertQuery = this.insertTypeormMetadataSql({
615
- schema: currentDatabase,
616
- table: table.name,
617
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
618
- name: column.name,
619
- value: column.asExpression,
620
- });
621
- upQueries.push(deleteQuery);
622
- downQueries.push(insertQuery);
623
- _b.label = 7;
624
- case 7:
625
- generatedColumns_2_1 = generatedColumns_2.next();
626
- return [3 /*break*/, 5];
627
- case 8: return [3 /*break*/, 11];
628
- case 9:
629
- e_2_1 = _b.sent();
630
- e_2 = { error: e_2_1 };
631
- return [3 /*break*/, 11];
632
- case 10:
633
- try {
634
- if (generatedColumns_2_1 && !generatedColumns_2_1.done && (_a = generatedColumns_2.return)) _a.call(generatedColumns_2);
635
- }
636
- finally { if (e_2) throw e_2.error; }
637
- return [7 /*endfinally*/];
638
- case 11: return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
639
- case 12:
640
- _b.sent();
641
- return [2 /*return*/];
642
- }
643
- });
644
- });
645
- };
361
+ async dropTable(target, ifExist, dropForeignKeys = true) {
362
+ // It needs because if table does not exist and dropForeignKeys or dropIndices is true, we don't need
363
+ // to perform drop queries for foreign keys and indices.
364
+ if (ifExist) {
365
+ const isTableExist = await this.hasTable(target);
366
+ if (!isTableExist)
367
+ return Promise.resolve();
368
+ }
369
+ // if dropTable called with dropForeignKeys = true, we must create foreign keys in down query.
370
+ const createForeignKeys = dropForeignKeys;
371
+ const tablePath = this.getTablePath(target);
372
+ const table = await this.getCachedTable(tablePath);
373
+ const upQueries = [];
374
+ const downQueries = [];
375
+ if (dropForeignKeys)
376
+ table.foreignKeys.forEach((foreignKey) => upQueries.push(this.dropForeignKeySql(table, foreignKey)));
377
+ table.indices.forEach((index) => upQueries.push(this.dropIndexSql(table, index)));
378
+ upQueries.push(this.dropTableSql(table));
379
+ downQueries.push(this.createTableSql(table, createForeignKeys));
380
+ // if table had columns with generated type, we must remove the expression from the metadata table
381
+ const generatedColumns = table.columns.filter((column) => column.generatedType && column.asExpression);
382
+ for (const column of generatedColumns) {
383
+ const currentDatabase = await this.getCurrentDatabase();
384
+ const deleteQuery = this.deleteTypeormMetadataSql({
385
+ schema: currentDatabase,
386
+ table: table.name,
387
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
388
+ name: column.name,
389
+ });
390
+ const insertQuery = this.insertTypeormMetadataSql({
391
+ schema: currentDatabase,
392
+ table: table.name,
393
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
394
+ name: column.name,
395
+ value: column.asExpression,
396
+ });
397
+ upQueries.push(deleteQuery);
398
+ downQueries.push(insertQuery);
399
+ }
400
+ await this.executeQueries(upQueries, downQueries);
401
+ }
646
402
  /**
647
403
  * Creates a new view.
648
404
  */
649
- MysqlQueryRunner.prototype.createView = function (view_1) {
650
- return tslib_1.__awaiter(this, arguments, void 0, function (view, syncWithMetadata) {
651
- var upQueries, downQueries, _a, _b, _c, _d;
652
- if (syncWithMetadata === void 0) { syncWithMetadata = false; }
653
- return tslib_1.__generator(this, function (_e) {
654
- switch (_e.label) {
655
- case 0:
656
- upQueries = [];
657
- downQueries = [];
658
- upQueries.push(this.createViewSql(view));
659
- if (!syncWithMetadata) return [3 /*break*/, 2];
660
- _b = (_a = upQueries).push;
661
- return [4 /*yield*/, this.insertViewDefinitionSql(view)];
662
- case 1:
663
- _b.apply(_a, [_e.sent()]);
664
- _e.label = 2;
665
- case 2:
666
- downQueries.push(this.dropViewSql(view));
667
- if (!syncWithMetadata) return [3 /*break*/, 4];
668
- _d = (_c = downQueries).push;
669
- return [4 /*yield*/, this.deleteViewDefinitionSql(view)];
670
- case 3:
671
- _d.apply(_c, [_e.sent()]);
672
- _e.label = 4;
673
- case 4: return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
674
- case 5:
675
- _e.sent();
676
- return [2 /*return*/];
677
- }
678
- });
679
- });
680
- };
405
+ async createView(view, syncWithMetadata = false) {
406
+ const upQueries = [];
407
+ const downQueries = [];
408
+ upQueries.push(this.createViewSql(view));
409
+ if (syncWithMetadata)
410
+ upQueries.push(await this.insertViewDefinitionSql(view));
411
+ downQueries.push(this.dropViewSql(view));
412
+ if (syncWithMetadata)
413
+ downQueries.push(await this.deleteViewDefinitionSql(view));
414
+ await this.executeQueries(upQueries, downQueries);
415
+ }
681
416
  /**
682
417
  * Drops the view.
683
418
  */
684
- MysqlQueryRunner.prototype.dropView = function (target) {
685
- return tslib_1.__awaiter(this, void 0, void 0, function () {
686
- var viewName, view, upQueries, downQueries, _a, _b, _c, _d;
687
- return tslib_1.__generator(this, function (_e) {
688
- switch (_e.label) {
689
- case 0:
690
- viewName = InstanceChecker_1.InstanceChecker.isView(target) ? target.name : target;
691
- return [4 /*yield*/, this.getCachedView(viewName)];
692
- case 1:
693
- view = _e.sent();
694
- upQueries = [];
695
- downQueries = [];
696
- _b = (_a = upQueries).push;
697
- return [4 /*yield*/, this.deleteViewDefinitionSql(view)];
698
- case 2:
699
- _b.apply(_a, [_e.sent()]);
700
- upQueries.push(this.dropViewSql(view));
701
- _d = (_c = downQueries).push;
702
- return [4 /*yield*/, this.insertViewDefinitionSql(view)];
703
- case 3:
704
- _d.apply(_c, [_e.sent()]);
705
- downQueries.push(this.createViewSql(view));
706
- return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
707
- case 4:
708
- _e.sent();
709
- return [2 /*return*/];
710
- }
711
- });
712
- });
713
- };
419
+ async dropView(target) {
420
+ const viewName = InstanceChecker_1.InstanceChecker.isView(target) ? target.name : target;
421
+ const view = await this.getCachedView(viewName);
422
+ const upQueries = [];
423
+ const downQueries = [];
424
+ upQueries.push(await this.deleteViewDefinitionSql(view));
425
+ upQueries.push(this.dropViewSql(view));
426
+ downQueries.push(await this.insertViewDefinitionSql(view));
427
+ downQueries.push(this.createViewSql(view));
428
+ await this.executeQueries(upQueries, downQueries);
429
+ }
714
430
  /**
715
431
  * Renames a table.
716
432
  */
717
- MysqlQueryRunner.prototype.renameTable = function (oldTableOrName, newTableName) {
718
- return tslib_1.__awaiter(this, void 0, void 0, function () {
719
- var upQueries, downQueries, oldTable, _a, newTable, database;
720
- var _this = this;
721
- return tslib_1.__generator(this, function (_b) {
722
- switch (_b.label) {
723
- case 0:
724
- upQueries = [];
725
- downQueries = [];
726
- if (!InstanceChecker_1.InstanceChecker.isTable(oldTableOrName)) return [3 /*break*/, 1];
727
- _a = oldTableOrName;
728
- return [3 /*break*/, 3];
729
- case 1: return [4 /*yield*/, this.getCachedTable(oldTableOrName)];
730
- case 2:
731
- _a = _b.sent();
732
- _b.label = 3;
733
- case 3:
734
- oldTable = _a;
735
- newTable = oldTable.clone();
736
- database = this.driver.parseTableName(oldTable).database;
737
- newTable.name = database ? "".concat(database, ".").concat(newTableName) : newTableName;
738
- // rename table
739
- upQueries.push(new Query_1.Query("RENAME TABLE ".concat(this.escapePath(oldTable), " TO ").concat(this.escapePath(newTable))));
740
- downQueries.push(new Query_1.Query("RENAME TABLE ".concat(this.escapePath(newTable), " TO ").concat(this.escapePath(oldTable))));
741
- // rename index constraints
742
- newTable.indices.forEach(function (index) {
743
- var oldIndexName = _this.connection.namingStrategy.indexName(oldTable, index.columnNames);
744
- // Skip renaming if Index has user defined constraint name
745
- if (index.name !== oldIndexName)
746
- return;
747
- // build new constraint name
748
- var columnNames = index.columnNames
749
- .map(function (column) { return "`".concat(column, "`"); })
750
- .join(", ");
751
- var newIndexName = _this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where);
752
- // build queries
753
- var indexType = "";
754
- if (index.isUnique)
755
- indexType += "UNIQUE ";
756
- if (index.isSpatial)
757
- indexType += "SPATIAL ";
758
- if (index.isFulltext)
759
- indexType += "FULLTEXT ";
760
- var indexParser = index.isFulltext && index.parser
761
- ? " WITH PARSER ".concat(index.parser)
762
- : "";
763
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(_this.escapePath(newTable), " DROP INDEX `").concat(index.name, "`, ADD ").concat(indexType, "INDEX `").concat(newIndexName, "` (").concat(columnNames, ")").concat(indexParser)));
764
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(_this.escapePath(newTable), " DROP INDEX `").concat(newIndexName, "`, ADD ").concat(indexType, "INDEX `").concat(index.name, "` (").concat(columnNames, ")").concat(indexParser)));
765
- // replace constraint name
766
- index.name = newIndexName;
767
- });
768
- // rename foreign key constraint
769
- newTable.foreignKeys.forEach(function (foreignKey) {
770
- var oldForeignKeyName = _this.connection.namingStrategy.foreignKeyName(oldTable, foreignKey.columnNames, _this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
771
- // Skip renaming if foreign key has user defined constraint name
772
- if (foreignKey.name !== oldForeignKeyName)
773
- return;
774
- // build new constraint name
775
- var columnNames = foreignKey.columnNames
776
- .map(function (column) { return "`".concat(column, "`"); })
777
- .join(", ");
778
- var referencedColumnNames = foreignKey.referencedColumnNames
779
- .map(function (column) { return "`".concat(column, "`"); })
780
- .join(",");
781
- var newForeignKeyName = _this.connection.namingStrategy.foreignKeyName(newTable, foreignKey.columnNames, _this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
782
- // build queries
783
- var up = "ALTER TABLE ".concat(_this.escapePath(newTable), " DROP FOREIGN KEY `").concat(foreignKey.name, "`, ADD CONSTRAINT `").concat(newForeignKeyName, "` FOREIGN KEY (").concat(columnNames, ") ") +
784
- "REFERENCES ".concat(_this.escapePath(_this.getTablePath(foreignKey)), "(").concat(referencedColumnNames, ")");
785
- if (foreignKey.onDelete)
786
- up += " ON DELETE ".concat(foreignKey.onDelete);
787
- if (foreignKey.onUpdate)
788
- up += " ON UPDATE ".concat(foreignKey.onUpdate);
789
- var down = "ALTER TABLE ".concat(_this.escapePath(newTable), " DROP FOREIGN KEY `").concat(newForeignKeyName, "`, ADD CONSTRAINT `").concat(foreignKey.name, "` FOREIGN KEY (").concat(columnNames, ") ") +
790
- "REFERENCES ".concat(_this.escapePath(_this.getTablePath(foreignKey)), "(").concat(referencedColumnNames, ")");
791
- if (foreignKey.onDelete)
792
- down += " ON DELETE ".concat(foreignKey.onDelete);
793
- if (foreignKey.onUpdate)
794
- down += " ON UPDATE ".concat(foreignKey.onUpdate);
795
- upQueries.push(new Query_1.Query(up));
796
- downQueries.push(new Query_1.Query(down));
797
- // replace constraint name
798
- foreignKey.name = newForeignKeyName;
799
- });
800
- return [4 /*yield*/, this.executeQueries(upQueries, downQueries)
801
- // rename old table and replace it in cached tabled;
802
- ];
803
- case 4:
804
- _b.sent();
805
- // rename old table and replace it in cached tabled;
806
- oldTable.name = newTable.name;
807
- this.replaceCachedTable(oldTable, newTable);
808
- return [2 /*return*/];
809
- }
810
- });
433
+ async renameTable(oldTableOrName, newTableName) {
434
+ const upQueries = [];
435
+ const downQueries = [];
436
+ const oldTable = InstanceChecker_1.InstanceChecker.isTable(oldTableOrName)
437
+ ? oldTableOrName
438
+ : await this.getCachedTable(oldTableOrName);
439
+ const newTable = oldTable.clone();
440
+ const { database } = this.driver.parseTableName(oldTable);
441
+ newTable.name = database ? `${database}.${newTableName}` : newTableName;
442
+ // rename table
443
+ upQueries.push(new Query_1.Query(`RENAME TABLE ${this.escapePath(oldTable)} TO ${this.escapePath(newTable)}`));
444
+ downQueries.push(new Query_1.Query(`RENAME TABLE ${this.escapePath(newTable)} TO ${this.escapePath(oldTable)}`));
445
+ // rename index constraints
446
+ newTable.indices.forEach((index) => {
447
+ const oldIndexName = this.connection.namingStrategy.indexName(oldTable, index.columnNames);
448
+ // Skip renaming if Index has user defined constraint name
449
+ if (index.name !== oldIndexName)
450
+ return;
451
+ // build new constraint name
452
+ const columnNames = index.columnNames
453
+ .map((column) => `\`${column}\``)
454
+ .join(", ");
455
+ const newIndexName = this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where);
456
+ // build queries
457
+ let indexType = "";
458
+ if (index.isUnique)
459
+ indexType += "UNIQUE ";
460
+ if (index.isSpatial)
461
+ indexType += "SPATIAL ";
462
+ if (index.isFulltext)
463
+ indexType += "FULLTEXT ";
464
+ const indexParser = index.isFulltext && index.parser
465
+ ? ` WITH PARSER ${index.parser}`
466
+ : "";
467
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(newTable)} DROP INDEX \`${index.name}\`, ADD ${indexType}INDEX \`${newIndexName}\` (${columnNames})${indexParser}`));
468
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(newTable)} DROP INDEX \`${newIndexName}\`, ADD ${indexType}INDEX \`${index.name}\` (${columnNames})${indexParser}`));
469
+ // replace constraint name
470
+ index.name = newIndexName;
471
+ });
472
+ // rename foreign key constraint
473
+ newTable.foreignKeys.forEach((foreignKey) => {
474
+ const oldForeignKeyName = this.connection.namingStrategy.foreignKeyName(oldTable, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
475
+ // Skip renaming if foreign key has user defined constraint name
476
+ if (foreignKey.name !== oldForeignKeyName)
477
+ return;
478
+ // build new constraint name
479
+ const columnNames = foreignKey.columnNames
480
+ .map((column) => `\`${column}\``)
481
+ .join(", ");
482
+ const referencedColumnNames = foreignKey.referencedColumnNames
483
+ .map((column) => `\`${column}\``)
484
+ .join(",");
485
+ const newForeignKeyName = this.connection.namingStrategy.foreignKeyName(newTable, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
486
+ // build queries
487
+ let up = `ALTER TABLE ${this.escapePath(newTable)} DROP FOREIGN KEY \`${foreignKey.name}\`, ADD CONSTRAINT \`${newForeignKeyName}\` FOREIGN KEY (${columnNames}) ` +
488
+ `REFERENCES ${this.escapePath(this.getTablePath(foreignKey))}(${referencedColumnNames})`;
489
+ if (foreignKey.onDelete)
490
+ up += ` ON DELETE ${foreignKey.onDelete}`;
491
+ if (foreignKey.onUpdate)
492
+ up += ` ON UPDATE ${foreignKey.onUpdate}`;
493
+ let down = `ALTER TABLE ${this.escapePath(newTable)} DROP FOREIGN KEY \`${newForeignKeyName}\`, ADD CONSTRAINT \`${foreignKey.name}\` FOREIGN KEY (${columnNames}) ` +
494
+ `REFERENCES ${this.escapePath(this.getTablePath(foreignKey))}(${referencedColumnNames})`;
495
+ if (foreignKey.onDelete)
496
+ down += ` ON DELETE ${foreignKey.onDelete}`;
497
+ if (foreignKey.onUpdate)
498
+ down += ` ON UPDATE ${foreignKey.onUpdate}`;
499
+ upQueries.push(new Query_1.Query(up));
500
+ downQueries.push(new Query_1.Query(down));
501
+ // replace constraint name
502
+ foreignKey.name = newForeignKeyName;
811
503
  });
812
- };
504
+ await this.executeQueries(upQueries, downQueries);
505
+ // rename old table and replace it in cached tabled;
506
+ oldTable.name = newTable.name;
507
+ this.replaceCachedTable(oldTable, newTable);
508
+ }
813
509
  /**
814
510
  * Creates a new column from the column in the table.
815
511
  */
816
- MysqlQueryRunner.prototype.addColumn = function (tableOrName, column) {
817
- return tslib_1.__awaiter(this, void 0, void 0, function () {
818
- var table, _a, clonedTable, upQueries, downQueries, skipColumnLevelPrimary, generatedColumn, nonGeneratedColumn, primaryColumns, columnNames, nonGeneratedColumn, currentDatabase, insertQuery, deleteQuery, columnIndex, uniqueIndex;
819
- return tslib_1.__generator(this, function (_b) {
820
- switch (_b.label) {
821
- case 0:
822
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
823
- _a = tableOrName;
824
- return [3 /*break*/, 3];
825
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
826
- case 2:
827
- _a = _b.sent();
828
- _b.label = 3;
829
- case 3:
830
- table = _a;
831
- clonedTable = table.clone();
832
- upQueries = [];
833
- downQueries = [];
834
- skipColumnLevelPrimary = clonedTable.primaryColumns.length > 0;
835
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD ").concat(this.buildCreateColumnSql(column, skipColumnLevelPrimary, false))));
836
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP COLUMN `").concat(column.name, "`")));
837
- // create or update primary key constraint
838
- if (column.isPrimary && skipColumnLevelPrimary) {
839
- generatedColumn = clonedTable.columns.find(function (column) {
840
- return column.isGenerated &&
841
- column.generationStrategy === "increment";
842
- });
843
- if (generatedColumn) {
844
- nonGeneratedColumn = generatedColumn.clone();
845
- nonGeneratedColumn.isGenerated = false;
846
- nonGeneratedColumn.generationStrategy = undefined;
847
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(column.name, "` ").concat(this.buildCreateColumnSql(nonGeneratedColumn, true))));
848
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(nonGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(column, true))));
849
- }
850
- primaryColumns = clonedTable.primaryColumns;
851
- columnNames = primaryColumns
852
- .map(function (column) { return "`".concat(column.name, "`"); })
853
- .join(", ");
854
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP PRIMARY KEY")));
855
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD PRIMARY KEY (").concat(columnNames, ")")));
856
- primaryColumns.push(column);
857
- columnNames = primaryColumns
858
- .map(function (column) { return "`".concat(column.name, "`"); })
859
- .join(", ");
860
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD PRIMARY KEY (").concat(columnNames, ")")));
861
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP PRIMARY KEY")));
862
- // if we previously dropped AUTO_INCREMENT property, we must bring it back
863
- if (generatedColumn) {
864
- nonGeneratedColumn = generatedColumn.clone();
865
- nonGeneratedColumn.isGenerated = false;
866
- nonGeneratedColumn.generationStrategy = undefined;
867
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(nonGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(column, true))));
868
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(column.name, "` ").concat(this.buildCreateColumnSql(nonGeneratedColumn, true))));
869
- }
870
- }
871
- if (!(column.generatedType && column.asExpression)) return [3 /*break*/, 5];
872
- return [4 /*yield*/, this.getCurrentDatabase()];
873
- case 4:
874
- currentDatabase = _b.sent();
875
- insertQuery = this.insertTypeormMetadataSql({
876
- schema: currentDatabase,
877
- table: table.name,
878
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
879
- name: column.name,
880
- value: column.asExpression,
881
- });
882
- deleteQuery = this.deleteTypeormMetadataSql({
883
- schema: currentDatabase,
884
- table: table.name,
885
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
886
- name: column.name,
887
- });
888
- upQueries.push(insertQuery);
889
- downQueries.push(deleteQuery);
890
- _b.label = 5;
891
- case 5:
892
- columnIndex = clonedTable.indices.find(function (index) {
893
- return index.columnNames.length === 1 &&
894
- index.columnNames[0] === column.name;
895
- });
896
- if (columnIndex) {
897
- upQueries.push(this.createIndexSql(table, columnIndex));
898
- downQueries.push(this.dropIndexSql(table, columnIndex));
899
- }
900
- else if (column.isUnique) {
901
- uniqueIndex = new TableIndex_1.TableIndex({
902
- name: this.connection.namingStrategy.indexName(table, [
903
- column.name,
904
- ]),
905
- columnNames: [column.name],
906
- isUnique: true,
907
- });
908
- clonedTable.indices.push(uniqueIndex);
909
- clonedTable.uniques.push(new TableUnique_1.TableUnique({
910
- name: uniqueIndex.name,
911
- columnNames: uniqueIndex.columnNames,
912
- }));
913
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD UNIQUE INDEX `").concat(uniqueIndex.name, "` (`").concat(column.name, "`)")));
914
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP INDEX `").concat(uniqueIndex.name, "`")));
915
- }
916
- return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
917
- case 6:
918
- _b.sent();
919
- clonedTable.addColumn(column);
920
- this.replaceCachedTable(table, clonedTable);
921
- return [2 /*return*/];
922
- }
923
- });
924
- });
925
- };
512
+ async addColumn(tableOrName, column) {
513
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
514
+ ? tableOrName
515
+ : await this.getCachedTable(tableOrName);
516
+ const clonedTable = table.clone();
517
+ const upQueries = [];
518
+ const downQueries = [];
519
+ const skipColumnLevelPrimary = clonedTable.primaryColumns.length > 0;
520
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD ${this.buildCreateColumnSql(column, skipColumnLevelPrimary, false)}`));
521
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP COLUMN \`${column.name}\``));
522
+ // create or update primary key constraint
523
+ if (column.isPrimary && skipColumnLevelPrimary) {
524
+ // if we already have generated column, we must temporary drop AUTO_INCREMENT property.
525
+ const generatedColumn = clonedTable.columns.find((column) => column.isGenerated &&
526
+ column.generationStrategy === "increment");
527
+ if (generatedColumn) {
528
+ const nonGeneratedColumn = generatedColumn.clone();
529
+ nonGeneratedColumn.isGenerated = false;
530
+ nonGeneratedColumn.generationStrategy = undefined;
531
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${column.name}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`));
532
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${nonGeneratedColumn.name}\` ${this.buildCreateColumnSql(column, true)}`));
533
+ }
534
+ const primaryColumns = clonedTable.primaryColumns;
535
+ let columnNames = primaryColumns
536
+ .map((column) => `\`${column.name}\``)
537
+ .join(", ");
538
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`));
539
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD PRIMARY KEY (${columnNames})`));
540
+ primaryColumns.push(column);
541
+ columnNames = primaryColumns
542
+ .map((column) => `\`${column.name}\``)
543
+ .join(", ");
544
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD PRIMARY KEY (${columnNames})`));
545
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`));
546
+ // if we previously dropped AUTO_INCREMENT property, we must bring it back
547
+ if (generatedColumn) {
548
+ const nonGeneratedColumn = generatedColumn.clone();
549
+ nonGeneratedColumn.isGenerated = false;
550
+ nonGeneratedColumn.generationStrategy = undefined;
551
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${nonGeneratedColumn.name}\` ${this.buildCreateColumnSql(column, true)}`));
552
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${column.name}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`));
553
+ }
554
+ }
555
+ if (column.generatedType && column.asExpression) {
556
+ const currentDatabase = await this.getCurrentDatabase();
557
+ const insertQuery = this.insertTypeormMetadataSql({
558
+ schema: currentDatabase,
559
+ table: table.name,
560
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
561
+ name: column.name,
562
+ value: column.asExpression,
563
+ });
564
+ const deleteQuery = this.deleteTypeormMetadataSql({
565
+ schema: currentDatabase,
566
+ table: table.name,
567
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
568
+ name: column.name,
569
+ });
570
+ upQueries.push(insertQuery);
571
+ downQueries.push(deleteQuery);
572
+ }
573
+ // create column index
574
+ const columnIndex = clonedTable.indices.find((index) => index.columnNames.length === 1 &&
575
+ index.columnNames[0] === column.name);
576
+ if (columnIndex) {
577
+ upQueries.push(this.createIndexSql(table, columnIndex));
578
+ downQueries.push(this.dropIndexSql(table, columnIndex));
579
+ }
580
+ else if (column.isUnique) {
581
+ const uniqueIndex = new TableIndex_1.TableIndex({
582
+ name: this.connection.namingStrategy.indexName(table, [
583
+ column.name,
584
+ ]),
585
+ columnNames: [column.name],
586
+ isUnique: true,
587
+ });
588
+ clonedTable.indices.push(uniqueIndex);
589
+ clonedTable.uniques.push(new TableUnique_1.TableUnique({
590
+ name: uniqueIndex.name,
591
+ columnNames: uniqueIndex.columnNames,
592
+ }));
593
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD UNIQUE INDEX \`${uniqueIndex.name}\` (\`${column.name}\`)`));
594
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP INDEX \`${uniqueIndex.name}\``));
595
+ }
596
+ await this.executeQueries(upQueries, downQueries);
597
+ clonedTable.addColumn(column);
598
+ this.replaceCachedTable(table, clonedTable);
599
+ }
926
600
  /**
927
601
  * Creates a new columns from the column in the table.
928
602
  */
929
- MysqlQueryRunner.prototype.addColumns = function (tableOrName, columns) {
930
- return tslib_1.__awaiter(this, void 0, void 0, function () {
931
- var columns_1, columns_1_1, column, e_3_1;
932
- var e_3, _a;
933
- return tslib_1.__generator(this, function (_b) {
934
- switch (_b.label) {
935
- case 0:
936
- _b.trys.push([0, 5, 6, 7]);
937
- columns_1 = tslib_1.__values(columns), columns_1_1 = columns_1.next();
938
- _b.label = 1;
939
- case 1:
940
- if (!!columns_1_1.done) return [3 /*break*/, 4];
941
- column = columns_1_1.value;
942
- return [4 /*yield*/, this.addColumn(tableOrName, column)];
943
- case 2:
944
- _b.sent();
945
- _b.label = 3;
946
- case 3:
947
- columns_1_1 = columns_1.next();
948
- return [3 /*break*/, 1];
949
- case 4: return [3 /*break*/, 7];
950
- case 5:
951
- e_3_1 = _b.sent();
952
- e_3 = { error: e_3_1 };
953
- return [3 /*break*/, 7];
954
- case 6:
955
- try {
956
- if (columns_1_1 && !columns_1_1.done && (_a = columns_1.return)) _a.call(columns_1);
957
- }
958
- finally { if (e_3) throw e_3.error; }
959
- return [7 /*endfinally*/];
960
- case 7: return [2 /*return*/];
961
- }
962
- });
963
- });
964
- };
603
+ async addColumns(tableOrName, columns) {
604
+ for (const column of columns) {
605
+ await this.addColumn(tableOrName, column);
606
+ }
607
+ }
965
608
  /**
966
609
  * Renames column in the given table.
967
610
  */
968
- MysqlQueryRunner.prototype.renameColumn = function (tableOrName, oldTableColumnOrName, newTableColumnOrName) {
969
- return tslib_1.__awaiter(this, void 0, void 0, function () {
970
- var table, _a, oldColumn, newColumn;
971
- return tslib_1.__generator(this, function (_b) {
972
- switch (_b.label) {
973
- case 0:
974
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
975
- _a = tableOrName;
976
- return [3 /*break*/, 3];
977
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
978
- case 2:
979
- _a = _b.sent();
980
- _b.label = 3;
981
- case 3:
982
- table = _a;
983
- oldColumn = InstanceChecker_1.InstanceChecker.isTableColumn(oldTableColumnOrName)
984
- ? oldTableColumnOrName
985
- : table.columns.find(function (c) { return c.name === oldTableColumnOrName; });
986
- if (!oldColumn)
987
- throw new error_1.TypeORMError("Column \"".concat(oldTableColumnOrName, "\" was not found in the \"").concat(table.name, "\" table."));
988
- newColumn = undefined;
989
- if (InstanceChecker_1.InstanceChecker.isTableColumn(newTableColumnOrName)) {
990
- newColumn = newTableColumnOrName;
991
- }
992
- else {
993
- newColumn = oldColumn.clone();
994
- newColumn.name = newTableColumnOrName;
995
- }
996
- return [4 /*yield*/, this.changeColumn(table, oldColumn, newColumn)];
997
- case 4:
998
- _b.sent();
999
- return [2 /*return*/];
1000
- }
1001
- });
1002
- });
1003
- };
611
+ async renameColumn(tableOrName, oldTableColumnOrName, newTableColumnOrName) {
612
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
613
+ ? tableOrName
614
+ : await this.getCachedTable(tableOrName);
615
+ const oldColumn = InstanceChecker_1.InstanceChecker.isTableColumn(oldTableColumnOrName)
616
+ ? oldTableColumnOrName
617
+ : table.columns.find((c) => c.name === oldTableColumnOrName);
618
+ if (!oldColumn)
619
+ throw new error_1.TypeORMError(`Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`);
620
+ let newColumn = undefined;
621
+ if (InstanceChecker_1.InstanceChecker.isTableColumn(newTableColumnOrName)) {
622
+ newColumn = newTableColumnOrName;
623
+ }
624
+ else {
625
+ newColumn = oldColumn.clone();
626
+ newColumn.name = newTableColumnOrName;
627
+ }
628
+ await this.changeColumn(table, oldColumn, newColumn);
629
+ }
1004
630
  /**
1005
631
  * Changes a column in the table.
1006
632
  */
1007
- MysqlQueryRunner.prototype.changeColumn = function (tableOrName, oldColumnOrName, newColumn) {
1008
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1009
- var table, _a, clonedTable, upQueries, downQueries, oldColumn, oldTableColumn, currentDatabase, deleteQuery, insertQuery, currentDatabase, insertQuery, deleteQuery, currentDatabase, updateQuery, revertUpdateQuery, generatedColumn, nonGeneratedColumn, primaryColumns, columnNames, column, columnNames, primaryColumn, column, columnNames, nonGeneratedColumn, uniqueIndex, uniqueIndex_1, tableUnique;
1010
- var _this = this;
1011
- return tslib_1.__generator(this, function (_b) {
1012
- switch (_b.label) {
1013
- case 0:
1014
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1015
- _a = tableOrName;
1016
- return [3 /*break*/, 3];
1017
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
1018
- case 2:
1019
- _a = _b.sent();
1020
- _b.label = 3;
1021
- case 3:
1022
- table = _a;
1023
- clonedTable = table.clone();
1024
- upQueries = [];
1025
- downQueries = [];
1026
- oldColumn = InstanceChecker_1.InstanceChecker.isTableColumn(oldColumnOrName)
1027
- ? oldColumnOrName
1028
- : table.columns.find(function (column) { return column.name === oldColumnOrName; });
1029
- if (!oldColumn)
1030
- throw new error_1.TypeORMError("Column \"".concat(oldColumnOrName, "\" was not found in the \"").concat(table.name, "\" table."));
1031
- if (!((newColumn.isGenerated !== oldColumn.isGenerated &&
1032
- newColumn.generationStrategy !== "uuid") ||
1033
- oldColumn.type !== newColumn.type ||
1034
- oldColumn.length !== newColumn.length ||
1035
- (oldColumn.generatedType &&
1036
- newColumn.generatedType &&
1037
- oldColumn.generatedType !== newColumn.generatedType) ||
1038
- (!oldColumn.generatedType &&
1039
- newColumn.generatedType === "VIRTUAL") ||
1040
- (oldColumn.generatedType === "VIRTUAL" && !newColumn.generatedType))) return [3 /*break*/, 6];
1041
- return [4 /*yield*/, this.dropColumn(table, oldColumn)];
1042
- case 4:
1043
- _b.sent();
1044
- return [4 /*yield*/, this.addColumn(table, newColumn)
1045
- // update cloned table
1046
- ];
1047
- case 5:
1048
- _b.sent();
1049
- // update cloned table
1050
- clonedTable = table.clone();
1051
- return [3 /*break*/, 13];
1052
- case 6:
1053
- if (newColumn.name !== oldColumn.name) {
1054
- // We don't change any column properties, just rename it.
1055
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(oldColumn.name, "` `").concat(newColumn.name, "` ").concat(this.buildCreateColumnSql(oldColumn, true, true))));
1056
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(newColumn.name, "` `").concat(oldColumn.name, "` ").concat(this.buildCreateColumnSql(oldColumn, true, true))));
1057
- // rename index constraints
1058
- clonedTable.findColumnIndices(oldColumn).forEach(function (index) {
1059
- var oldUniqueName = _this.connection.namingStrategy.indexName(clonedTable, index.columnNames);
1060
- // Skip renaming if Index has user defined constraint name
1061
- if (index.name !== oldUniqueName)
1062
- return;
1063
- // build new constraint name
1064
- index.columnNames.splice(index.columnNames.indexOf(oldColumn.name), 1);
1065
- index.columnNames.push(newColumn.name);
1066
- var columnNames = index.columnNames
1067
- .map(function (column) { return "`".concat(column, "`"); })
1068
- .join(", ");
1069
- var newIndexName = _this.connection.namingStrategy.indexName(clonedTable, index.columnNames, index.where);
1070
- // build queries
1071
- var indexType = "";
1072
- if (index.isUnique)
1073
- indexType += "UNIQUE ";
1074
- if (index.isSpatial)
1075
- indexType += "SPATIAL ";
1076
- if (index.isFulltext)
1077
- indexType += "FULLTEXT ";
1078
- var indexParser = index.isFulltext && index.parser
1079
- ? " WITH PARSER ".concat(index.parser)
1080
- : "";
1081
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(_this.escapePath(table), " DROP INDEX `").concat(index.name, "`, ADD ").concat(indexType, "INDEX `").concat(newIndexName, "` (").concat(columnNames, ")").concat(indexParser)));
1082
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(_this.escapePath(table), " DROP INDEX `").concat(newIndexName, "`, ADD ").concat(indexType, "INDEX `").concat(index.name, "` (").concat(columnNames, ")").concat(indexParser)));
1083
- // replace constraint name
1084
- index.name = newIndexName;
1085
- });
1086
- // rename foreign key constraints
1087
- clonedTable
1088
- .findColumnForeignKeys(oldColumn)
1089
- .forEach(function (foreignKey) {
1090
- var foreignKeyName = _this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames, _this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
1091
- // Skip renaming if foreign key has user defined constraint name
1092
- if (foreignKey.name !== foreignKeyName)
1093
- return;
1094
- // build new constraint name
1095
- foreignKey.columnNames.splice(foreignKey.columnNames.indexOf(oldColumn.name), 1);
1096
- foreignKey.columnNames.push(newColumn.name);
1097
- var columnNames = foreignKey.columnNames
1098
- .map(function (column) { return "`".concat(column, "`"); })
1099
- .join(", ");
1100
- var referencedColumnNames = foreignKey.referencedColumnNames
1101
- .map(function (column) { return "`".concat(column, "`"); })
1102
- .join(",");
1103
- var newForeignKeyName = _this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames, _this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
1104
- // build queries
1105
- var up = "ALTER TABLE ".concat(_this.escapePath(table), " DROP FOREIGN KEY `").concat(foreignKey.name, "`, ADD CONSTRAINT `").concat(newForeignKeyName, "` FOREIGN KEY (").concat(columnNames, ") ") +
1106
- "REFERENCES ".concat(_this.escapePath(_this.getTablePath(foreignKey)), "(").concat(referencedColumnNames, ")");
1107
- if (foreignKey.onDelete)
1108
- up += " ON DELETE ".concat(foreignKey.onDelete);
1109
- if (foreignKey.onUpdate)
1110
- up += " ON UPDATE ".concat(foreignKey.onUpdate);
1111
- var down = "ALTER TABLE ".concat(_this.escapePath(table), " DROP FOREIGN KEY `").concat(newForeignKeyName, "`, ADD CONSTRAINT `").concat(foreignKey.name, "` FOREIGN KEY (").concat(columnNames, ") ") +
1112
- "REFERENCES ".concat(_this.escapePath(_this.getTablePath(foreignKey)), "(").concat(referencedColumnNames, ")");
1113
- if (foreignKey.onDelete)
1114
- down += " ON DELETE ".concat(foreignKey.onDelete);
1115
- if (foreignKey.onUpdate)
1116
- down += " ON UPDATE ".concat(foreignKey.onUpdate);
1117
- upQueries.push(new Query_1.Query(up));
1118
- downQueries.push(new Query_1.Query(down));
1119
- // replace constraint name
1120
- foreignKey.name = newForeignKeyName;
1121
- });
1122
- oldTableColumn = clonedTable.columns.find(function (column) { return column.name === oldColumn.name; });
1123
- clonedTable.columns[clonedTable.columns.indexOf(oldTableColumn)].name = newColumn.name;
1124
- oldColumn.name = newColumn.name;
1125
- }
1126
- if (!this.isColumnChanged(oldColumn, newColumn, true, true)) return [3 /*break*/, 12];
1127
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(oldColumn.name, "` ").concat(this.buildCreateColumnSql(newColumn, true))));
1128
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(newColumn.name, "` ").concat(this.buildCreateColumnSql(oldColumn, true))));
1129
- if (!(oldColumn.generatedType && !newColumn.generatedType)) return [3 /*break*/, 8];
1130
- return [4 /*yield*/, this.getCurrentDatabase()];
1131
- case 7:
1132
- currentDatabase = _b.sent();
1133
- deleteQuery = this.deleteTypeormMetadataSql({
1134
- schema: currentDatabase,
1135
- table: table.name,
1136
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1137
- name: oldColumn.name,
1138
- });
1139
- insertQuery = this.insertTypeormMetadataSql({
1140
- schema: currentDatabase,
1141
- table: table.name,
1142
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1143
- name: oldColumn.name,
1144
- value: oldColumn.asExpression,
1145
- });
1146
- upQueries.push(deleteQuery);
1147
- downQueries.push(insertQuery);
1148
- return [3 /*break*/, 12];
1149
- case 8:
1150
- if (!(!oldColumn.generatedType &&
1151
- newColumn.generatedType)) return [3 /*break*/, 10];
1152
- return [4 /*yield*/, this.getCurrentDatabase()];
1153
- case 9:
1154
- currentDatabase = _b.sent();
1155
- insertQuery = this.insertTypeormMetadataSql({
1156
- schema: currentDatabase,
1157
- table: table.name,
1158
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1159
- name: newColumn.name,
1160
- value: newColumn.asExpression,
1161
- });
1162
- deleteQuery = this.deleteTypeormMetadataSql({
1163
- schema: currentDatabase,
1164
- table: table.name,
1165
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1166
- name: newColumn.name,
1167
- });
1168
- upQueries.push(insertQuery);
1169
- downQueries.push(deleteQuery);
1170
- return [3 /*break*/, 12];
1171
- case 10:
1172
- if (!(oldColumn.asExpression !== newColumn.asExpression)) return [3 /*break*/, 12];
1173
- return [4 /*yield*/, this.getCurrentDatabase()];
1174
- case 11:
1175
- currentDatabase = _b.sent();
1176
- updateQuery = this.connection
1177
- .createQueryBuilder()
1178
- .update(this.getTypeormMetadataTableName())
1179
- .set({ value: newColumn.asExpression })
1180
- .where("`type` = :type", {
1181
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1182
- })
1183
- .andWhere("`name` = :name", { name: oldColumn.name })
1184
- .andWhere("`schema` = :schema", {
1185
- schema: currentDatabase,
1186
- })
1187
- .andWhere("`table` = :table", { table: table.name })
1188
- .getQueryAndParameters();
1189
- revertUpdateQuery = this.connection
1190
- .createQueryBuilder()
1191
- .update(this.getTypeormMetadataTableName())
1192
- .set({ value: oldColumn.asExpression })
1193
- .where("`type` = :type", {
1194
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1195
- })
1196
- .andWhere("`name` = :name", { name: newColumn.name })
1197
- .andWhere("`schema` = :schema", {
1198
- schema: currentDatabase,
1199
- })
1200
- .andWhere("`table` = :table", { table: table.name })
1201
- .getQueryAndParameters();
1202
- upQueries.push(new Query_1.Query(updateQuery[0], updateQuery[1]));
1203
- downQueries.push(new Query_1.Query(revertUpdateQuery[0], revertUpdateQuery[1]));
1204
- _b.label = 12;
1205
- case 12:
1206
- if (newColumn.isPrimary !== oldColumn.isPrimary) {
1207
- generatedColumn = clonedTable.columns.find(function (column) {
1208
- return column.isGenerated &&
1209
- column.generationStrategy === "increment";
1210
- });
1211
- if (generatedColumn) {
1212
- nonGeneratedColumn = generatedColumn.clone();
1213
- nonGeneratedColumn.isGenerated = false;
1214
- nonGeneratedColumn.generationStrategy = undefined;
1215
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(generatedColumn.name, "` ").concat(this.buildCreateColumnSql(nonGeneratedColumn, true))));
1216
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(nonGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(generatedColumn, true))));
1217
- }
1218
- primaryColumns = clonedTable.primaryColumns;
1219
- // if primary column state changed, we must always drop existed constraint.
1220
- if (primaryColumns.length > 0) {
1221
- columnNames = primaryColumns
1222
- .map(function (column) { return "`".concat(column.name, "`"); })
1223
- .join(", ");
1224
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP PRIMARY KEY")));
1225
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD PRIMARY KEY (").concat(columnNames, ")")));
1226
- }
1227
- if (newColumn.isPrimary === true) {
1228
- primaryColumns.push(newColumn);
1229
- column = clonedTable.columns.find(function (column) { return column.name === newColumn.name; });
1230
- column.isPrimary = true;
1231
- columnNames = primaryColumns
1232
- .map(function (column) { return "`".concat(column.name, "`"); })
1233
- .join(", ");
1234
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD PRIMARY KEY (").concat(columnNames, ")")));
1235
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP PRIMARY KEY")));
1236
- }
1237
- else {
1238
- primaryColumn = primaryColumns.find(function (c) { return c.name === newColumn.name; });
1239
- primaryColumns.splice(primaryColumns.indexOf(primaryColumn), 1);
1240
- column = clonedTable.columns.find(function (column) { return column.name === newColumn.name; });
1241
- column.isPrimary = false;
1242
- // if we have another primary keys, we must recreate constraint.
1243
- if (primaryColumns.length > 0) {
1244
- columnNames = primaryColumns
1245
- .map(function (column) { return "`".concat(column.name, "`"); })
1246
- .join(", ");
1247
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD PRIMARY KEY (").concat(columnNames, ")")));
1248
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP PRIMARY KEY")));
1249
- }
1250
- }
1251
- // if we have generated column, and we dropped AUTO_INCREMENT property before, we must bring it back
1252
- if (generatedColumn) {
1253
- nonGeneratedColumn = generatedColumn.clone();
1254
- nonGeneratedColumn.isGenerated = false;
1255
- nonGeneratedColumn.generationStrategy = undefined;
1256
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(nonGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(generatedColumn, true))));
1257
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(generatedColumn.name, "` ").concat(this.buildCreateColumnSql(nonGeneratedColumn, true))));
1258
- }
1259
- }
1260
- if (newColumn.isUnique !== oldColumn.isUnique) {
1261
- if (newColumn.isUnique === true) {
1262
- uniqueIndex = new TableIndex_1.TableIndex({
1263
- name: this.connection.namingStrategy.indexName(table, [
1264
- newColumn.name,
1265
- ]),
1266
- columnNames: [newColumn.name],
1267
- isUnique: true,
1268
- });
1269
- clonedTable.indices.push(uniqueIndex);
1270
- clonedTable.uniques.push(new TableUnique_1.TableUnique({
1271
- name: uniqueIndex.name,
1272
- columnNames: uniqueIndex.columnNames,
1273
- }));
1274
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD UNIQUE INDEX `").concat(uniqueIndex.name, "` (`").concat(newColumn.name, "`)")));
1275
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP INDEX `").concat(uniqueIndex.name, "`")));
1276
- }
1277
- else {
1278
- uniqueIndex_1 = clonedTable.indices.find(function (index) {
1279
- return (index.columnNames.length === 1 &&
1280
- index.isUnique === true &&
1281
- !!index.columnNames.find(function (columnName) { return columnName === newColumn.name; }));
1282
- });
1283
- clonedTable.indices.splice(clonedTable.indices.indexOf(uniqueIndex_1), 1);
1284
- tableUnique = clonedTable.uniques.find(function (unique) { return unique.name === uniqueIndex_1.name; });
1285
- clonedTable.uniques.splice(clonedTable.uniques.indexOf(tableUnique), 1);
1286
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP INDEX `").concat(uniqueIndex_1.name, "`")));
1287
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD UNIQUE INDEX `").concat(uniqueIndex_1.name, "` (`").concat(newColumn.name, "`)")));
1288
- }
1289
- }
1290
- _b.label = 13;
1291
- case 13: return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
1292
- case 14:
1293
- _b.sent();
1294
- this.replaceCachedTable(table, clonedTable);
1295
- return [2 /*return*/];
633
+ async changeColumn(tableOrName, oldColumnOrName, newColumn) {
634
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
635
+ ? tableOrName
636
+ : await this.getCachedTable(tableOrName);
637
+ let clonedTable = table.clone();
638
+ const upQueries = [];
639
+ const downQueries = [];
640
+ const oldColumn = InstanceChecker_1.InstanceChecker.isTableColumn(oldColumnOrName)
641
+ ? oldColumnOrName
642
+ : table.columns.find((column) => column.name === oldColumnOrName);
643
+ if (!oldColumn)
644
+ throw new error_1.TypeORMError(`Column "${oldColumnOrName}" was not found in the "${table.name}" table.`);
645
+ if ((newColumn.isGenerated !== oldColumn.isGenerated &&
646
+ newColumn.generationStrategy !== "uuid") ||
647
+ oldColumn.type !== newColumn.type ||
648
+ oldColumn.length !== newColumn.length ||
649
+ (oldColumn.generatedType &&
650
+ newColumn.generatedType &&
651
+ oldColumn.generatedType !== newColumn.generatedType) ||
652
+ (!oldColumn.generatedType &&
653
+ newColumn.generatedType === "VIRTUAL") ||
654
+ (oldColumn.generatedType === "VIRTUAL" && !newColumn.generatedType)) {
655
+ await this.dropColumn(table, oldColumn);
656
+ await this.addColumn(table, newColumn);
657
+ // update cloned table
658
+ clonedTable = table.clone();
659
+ }
660
+ else {
661
+ if (newColumn.name !== oldColumn.name) {
662
+ // We don't change any column properties, just rename it.
663
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${oldColumn.name}\` \`${newColumn.name}\` ${this.buildCreateColumnSql(oldColumn, true, true)}`));
664
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${newColumn.name}\` \`${oldColumn.name}\` ${this.buildCreateColumnSql(oldColumn, true, true)}`));
665
+ // rename index constraints
666
+ clonedTable.findColumnIndices(oldColumn).forEach((index) => {
667
+ const oldUniqueName = this.connection.namingStrategy.indexName(clonedTable, index.columnNames);
668
+ // Skip renaming if Index has user defined constraint name
669
+ if (index.name !== oldUniqueName)
670
+ return;
671
+ // build new constraint name
672
+ index.columnNames.splice(index.columnNames.indexOf(oldColumn.name), 1);
673
+ index.columnNames.push(newColumn.name);
674
+ const columnNames = index.columnNames
675
+ .map((column) => `\`${column}\``)
676
+ .join(", ");
677
+ const newIndexName = this.connection.namingStrategy.indexName(clonedTable, index.columnNames, index.where);
678
+ // build queries
679
+ let indexType = "";
680
+ if (index.isUnique)
681
+ indexType += "UNIQUE ";
682
+ if (index.isSpatial)
683
+ indexType += "SPATIAL ";
684
+ if (index.isFulltext)
685
+ indexType += "FULLTEXT ";
686
+ const indexParser = index.isFulltext && index.parser
687
+ ? ` WITH PARSER ${index.parser}`
688
+ : "";
689
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP INDEX \`${index.name}\`, ADD ${indexType}INDEX \`${newIndexName}\` (${columnNames})${indexParser}`));
690
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP INDEX \`${newIndexName}\`, ADD ${indexType}INDEX \`${index.name}\` (${columnNames})${indexParser}`));
691
+ // replace constraint name
692
+ index.name = newIndexName;
693
+ });
694
+ // rename foreign key constraints
695
+ clonedTable
696
+ .findColumnForeignKeys(oldColumn)
697
+ .forEach((foreignKey) => {
698
+ const foreignKeyName = this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
699
+ // Skip renaming if foreign key has user defined constraint name
700
+ if (foreignKey.name !== foreignKeyName)
701
+ return;
702
+ // build new constraint name
703
+ foreignKey.columnNames.splice(foreignKey.columnNames.indexOf(oldColumn.name), 1);
704
+ foreignKey.columnNames.push(newColumn.name);
705
+ const columnNames = foreignKey.columnNames
706
+ .map((column) => `\`${column}\``)
707
+ .join(", ");
708
+ const referencedColumnNames = foreignKey.referencedColumnNames
709
+ .map((column) => `\`${column}\``)
710
+ .join(",");
711
+ const newForeignKeyName = this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
712
+ // build queries
713
+ let up = `ALTER TABLE ${this.escapePath(table)} DROP FOREIGN KEY \`${foreignKey.name}\`, ADD CONSTRAINT \`${newForeignKeyName}\` FOREIGN KEY (${columnNames}) ` +
714
+ `REFERENCES ${this.escapePath(this.getTablePath(foreignKey))}(${referencedColumnNames})`;
715
+ if (foreignKey.onDelete)
716
+ up += ` ON DELETE ${foreignKey.onDelete}`;
717
+ if (foreignKey.onUpdate)
718
+ up += ` ON UPDATE ${foreignKey.onUpdate}`;
719
+ let down = `ALTER TABLE ${this.escapePath(table)} DROP FOREIGN KEY \`${newForeignKeyName}\`, ADD CONSTRAINT \`${foreignKey.name}\` FOREIGN KEY (${columnNames}) ` +
720
+ `REFERENCES ${this.escapePath(this.getTablePath(foreignKey))}(${referencedColumnNames})`;
721
+ if (foreignKey.onDelete)
722
+ down += ` ON DELETE ${foreignKey.onDelete}`;
723
+ if (foreignKey.onUpdate)
724
+ down += ` ON UPDATE ${foreignKey.onUpdate}`;
725
+ upQueries.push(new Query_1.Query(up));
726
+ downQueries.push(new Query_1.Query(down));
727
+ // replace constraint name
728
+ foreignKey.name = newForeignKeyName;
729
+ });
730
+ // rename old column in the Table object
731
+ const oldTableColumn = clonedTable.columns.find((column) => column.name === oldColumn.name);
732
+ clonedTable.columns[clonedTable.columns.indexOf(oldTableColumn)].name = newColumn.name;
733
+ oldColumn.name = newColumn.name;
734
+ }
735
+ if (this.isColumnChanged(oldColumn, newColumn, true, true)) {
736
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${oldColumn.name}\` ${this.buildCreateColumnSql(newColumn, true)}`));
737
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${newColumn.name}\` ${this.buildCreateColumnSql(oldColumn, true)}`));
738
+ if (oldColumn.generatedType && !newColumn.generatedType) {
739
+ // if column changed from generated to non-generated, delete record from typeorm metadata
740
+ const currentDatabase = await this.getCurrentDatabase();
741
+ const deleteQuery = this.deleteTypeormMetadataSql({
742
+ schema: currentDatabase,
743
+ table: table.name,
744
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
745
+ name: oldColumn.name,
746
+ });
747
+ const insertQuery = this.insertTypeormMetadataSql({
748
+ schema: currentDatabase,
749
+ table: table.name,
750
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
751
+ name: oldColumn.name,
752
+ value: oldColumn.asExpression,
753
+ });
754
+ upQueries.push(deleteQuery);
755
+ downQueries.push(insertQuery);
1296
756
  }
1297
- });
1298
- });
1299
- };
757
+ else if (!oldColumn.generatedType &&
758
+ newColumn.generatedType) {
759
+ // if column changed from non-generated to generated, insert record into typeorm metadata
760
+ const currentDatabase = await this.getCurrentDatabase();
761
+ const insertQuery = this.insertTypeormMetadataSql({
762
+ schema: currentDatabase,
763
+ table: table.name,
764
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
765
+ name: newColumn.name,
766
+ value: newColumn.asExpression,
767
+ });
768
+ const deleteQuery = this.deleteTypeormMetadataSql({
769
+ schema: currentDatabase,
770
+ table: table.name,
771
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
772
+ name: newColumn.name,
773
+ });
774
+ upQueries.push(insertQuery);
775
+ downQueries.push(deleteQuery);
776
+ }
777
+ else if (oldColumn.asExpression !== newColumn.asExpression) {
778
+ // if only expression changed, just update it in typeorm_metadata table
779
+ const currentDatabase = await this.getCurrentDatabase();
780
+ const updateQuery = this.connection
781
+ .createQueryBuilder()
782
+ .update(this.getTypeormMetadataTableName())
783
+ .set({ value: newColumn.asExpression })
784
+ .where("`type` = :type", {
785
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
786
+ })
787
+ .andWhere("`name` = :name", { name: oldColumn.name })
788
+ .andWhere("`schema` = :schema", {
789
+ schema: currentDatabase,
790
+ })
791
+ .andWhere("`table` = :table", { table: table.name })
792
+ .getQueryAndParameters();
793
+ const revertUpdateQuery = this.connection
794
+ .createQueryBuilder()
795
+ .update(this.getTypeormMetadataTableName())
796
+ .set({ value: oldColumn.asExpression })
797
+ .where("`type` = :type", {
798
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
799
+ })
800
+ .andWhere("`name` = :name", { name: newColumn.name })
801
+ .andWhere("`schema` = :schema", {
802
+ schema: currentDatabase,
803
+ })
804
+ .andWhere("`table` = :table", { table: table.name })
805
+ .getQueryAndParameters();
806
+ upQueries.push(new Query_1.Query(updateQuery[0], updateQuery[1]));
807
+ downQueries.push(new Query_1.Query(revertUpdateQuery[0], revertUpdateQuery[1]));
808
+ }
809
+ }
810
+ if (newColumn.isPrimary !== oldColumn.isPrimary) {
811
+ // if table have generated column, we must drop AUTO_INCREMENT before changing primary constraints.
812
+ const generatedColumn = clonedTable.columns.find((column) => column.isGenerated &&
813
+ column.generationStrategy === "increment");
814
+ if (generatedColumn) {
815
+ const nonGeneratedColumn = generatedColumn.clone();
816
+ nonGeneratedColumn.isGenerated = false;
817
+ nonGeneratedColumn.generationStrategy = undefined;
818
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${generatedColumn.name}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`));
819
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${nonGeneratedColumn.name}\` ${this.buildCreateColumnSql(generatedColumn, true)}`));
820
+ }
821
+ const primaryColumns = clonedTable.primaryColumns;
822
+ // if primary column state changed, we must always drop existed constraint.
823
+ if (primaryColumns.length > 0) {
824
+ const columnNames = primaryColumns
825
+ .map((column) => `\`${column.name}\``)
826
+ .join(", ");
827
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`));
828
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD PRIMARY KEY (${columnNames})`));
829
+ }
830
+ if (newColumn.isPrimary === true) {
831
+ primaryColumns.push(newColumn);
832
+ // update column in table
833
+ const column = clonedTable.columns.find((column) => column.name === newColumn.name);
834
+ column.isPrimary = true;
835
+ const columnNames = primaryColumns
836
+ .map((column) => `\`${column.name}\``)
837
+ .join(", ");
838
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD PRIMARY KEY (${columnNames})`));
839
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`));
840
+ }
841
+ else {
842
+ const primaryColumn = primaryColumns.find((c) => c.name === newColumn.name);
843
+ primaryColumns.splice(primaryColumns.indexOf(primaryColumn), 1);
844
+ // update column in table
845
+ const column = clonedTable.columns.find((column) => column.name === newColumn.name);
846
+ column.isPrimary = false;
847
+ // if we have another primary keys, we must recreate constraint.
848
+ if (primaryColumns.length > 0) {
849
+ const columnNames = primaryColumns
850
+ .map((column) => `\`${column.name}\``)
851
+ .join(", ");
852
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD PRIMARY KEY (${columnNames})`));
853
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`));
854
+ }
855
+ }
856
+ // if we have generated column, and we dropped AUTO_INCREMENT property before, we must bring it back
857
+ if (generatedColumn) {
858
+ const nonGeneratedColumn = generatedColumn.clone();
859
+ nonGeneratedColumn.isGenerated = false;
860
+ nonGeneratedColumn.generationStrategy = undefined;
861
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${nonGeneratedColumn.name}\` ${this.buildCreateColumnSql(generatedColumn, true)}`));
862
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${generatedColumn.name}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`));
863
+ }
864
+ }
865
+ if (newColumn.isUnique !== oldColumn.isUnique) {
866
+ if (newColumn.isUnique === true) {
867
+ const uniqueIndex = new TableIndex_1.TableIndex({
868
+ name: this.connection.namingStrategy.indexName(table, [
869
+ newColumn.name,
870
+ ]),
871
+ columnNames: [newColumn.name],
872
+ isUnique: true,
873
+ });
874
+ clonedTable.indices.push(uniqueIndex);
875
+ clonedTable.uniques.push(new TableUnique_1.TableUnique({
876
+ name: uniqueIndex.name,
877
+ columnNames: uniqueIndex.columnNames,
878
+ }));
879
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD UNIQUE INDEX \`${uniqueIndex.name}\` (\`${newColumn.name}\`)`));
880
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP INDEX \`${uniqueIndex.name}\``));
881
+ }
882
+ else {
883
+ const uniqueIndex = clonedTable.indices.find((index) => {
884
+ return (index.columnNames.length === 1 &&
885
+ index.isUnique === true &&
886
+ !!index.columnNames.find((columnName) => columnName === newColumn.name));
887
+ });
888
+ clonedTable.indices.splice(clonedTable.indices.indexOf(uniqueIndex), 1);
889
+ const tableUnique = clonedTable.uniques.find((unique) => unique.name === uniqueIndex.name);
890
+ clonedTable.uniques.splice(clonedTable.uniques.indexOf(tableUnique), 1);
891
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP INDEX \`${uniqueIndex.name}\``));
892
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD UNIQUE INDEX \`${uniqueIndex.name}\` (\`${newColumn.name}\`)`));
893
+ }
894
+ }
895
+ }
896
+ await this.executeQueries(upQueries, downQueries);
897
+ this.replaceCachedTable(table, clonedTable);
898
+ }
1300
899
  /**
1301
900
  * Changes a column in the table.
1302
901
  */
1303
- MysqlQueryRunner.prototype.changeColumns = function (tableOrName, changedColumns) {
1304
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1305
- var changedColumns_1, changedColumns_1_1, _a, oldColumn, newColumn, e_4_1;
1306
- var e_4, _b;
1307
- return tslib_1.__generator(this, function (_c) {
1308
- switch (_c.label) {
1309
- case 0:
1310
- _c.trys.push([0, 5, 6, 7]);
1311
- changedColumns_1 = tslib_1.__values(changedColumns), changedColumns_1_1 = changedColumns_1.next();
1312
- _c.label = 1;
1313
- case 1:
1314
- if (!!changedColumns_1_1.done) return [3 /*break*/, 4];
1315
- _a = changedColumns_1_1.value, oldColumn = _a.oldColumn, newColumn = _a.newColumn;
1316
- return [4 /*yield*/, this.changeColumn(tableOrName, oldColumn, newColumn)];
1317
- case 2:
1318
- _c.sent();
1319
- _c.label = 3;
1320
- case 3:
1321
- changedColumns_1_1 = changedColumns_1.next();
1322
- return [3 /*break*/, 1];
1323
- case 4: return [3 /*break*/, 7];
1324
- case 5:
1325
- e_4_1 = _c.sent();
1326
- e_4 = { error: e_4_1 };
1327
- return [3 /*break*/, 7];
1328
- case 6:
1329
- try {
1330
- if (changedColumns_1_1 && !changedColumns_1_1.done && (_b = changedColumns_1.return)) _b.call(changedColumns_1);
1331
- }
1332
- finally { if (e_4) throw e_4.error; }
1333
- return [7 /*endfinally*/];
1334
- case 7: return [2 /*return*/];
1335
- }
1336
- });
1337
- });
1338
- };
902
+ async changeColumns(tableOrName, changedColumns) {
903
+ for (const { oldColumn, newColumn } of changedColumns) {
904
+ await this.changeColumn(tableOrName, oldColumn, newColumn);
905
+ }
906
+ }
1339
907
  /**
1340
908
  * Drops column in the table.
1341
909
  */
1342
- MysqlQueryRunner.prototype.dropColumn = function (tableOrName, columnOrName) {
1343
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1344
- var table, _a, column, clonedTable, upQueries, downQueries, generatedColumn, nonGeneratedColumn, columnNames, tableColumn, columnNames_1, nonGeneratedColumn, columnIndex, uniqueName_1, foundUnique, indexName_1, foundIndex, currentDatabase, deleteQuery, insertQuery;
1345
- return tslib_1.__generator(this, function (_b) {
1346
- switch (_b.label) {
1347
- case 0:
1348
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1349
- _a = tableOrName;
1350
- return [3 /*break*/, 3];
1351
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
1352
- case 2:
1353
- _a = _b.sent();
1354
- _b.label = 3;
1355
- case 3:
1356
- table = _a;
1357
- column = InstanceChecker_1.InstanceChecker.isTableColumn(columnOrName)
1358
- ? columnOrName
1359
- : table.findColumnByName(columnOrName);
1360
- if (!column)
1361
- throw new error_1.TypeORMError("Column \"".concat(columnOrName, "\" was not found in table \"").concat(table.name, "\""));
1362
- clonedTable = table.clone();
1363
- upQueries = [];
1364
- downQueries = [];
1365
- // drop primary key constraint
1366
- if (column.isPrimary) {
1367
- generatedColumn = clonedTable.columns.find(function (column) {
1368
- return column.isGenerated &&
1369
- column.generationStrategy === "increment";
1370
- });
1371
- if (generatedColumn) {
1372
- nonGeneratedColumn = generatedColumn.clone();
1373
- nonGeneratedColumn.isGenerated = false;
1374
- nonGeneratedColumn.generationStrategy = undefined;
1375
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(generatedColumn.name, "` ").concat(this.buildCreateColumnSql(nonGeneratedColumn, true))));
1376
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(nonGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(generatedColumn, true))));
1377
- }
1378
- columnNames = clonedTable.primaryColumns
1379
- .map(function (primaryColumn) { return "`".concat(primaryColumn.name, "`"); })
1380
- .join(", ");
1381
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(clonedTable), " DROP PRIMARY KEY")));
1382
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(clonedTable), " ADD PRIMARY KEY (").concat(columnNames, ")")));
1383
- tableColumn = clonedTable.findColumnByName(column.name);
1384
- tableColumn.isPrimary = false;
1385
- // if primary key have multiple columns, we must recreate it without dropped column
1386
- if (clonedTable.primaryColumns.length > 0) {
1387
- columnNames_1 = clonedTable.primaryColumns
1388
- .map(function (primaryColumn) { return "`".concat(primaryColumn.name, "`"); })
1389
- .join(", ");
1390
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(clonedTable), " ADD PRIMARY KEY (").concat(columnNames_1, ")")));
1391
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(clonedTable), " DROP PRIMARY KEY")));
1392
- }
1393
- // if we have generated column, and we dropped AUTO_INCREMENT property before, and this column is not current dropping column, we must bring it back
1394
- if (generatedColumn && generatedColumn.name !== column.name) {
1395
- nonGeneratedColumn = generatedColumn.clone();
1396
- nonGeneratedColumn.isGenerated = false;
1397
- nonGeneratedColumn.generationStrategy = undefined;
1398
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(nonGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(generatedColumn, true))));
1399
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(generatedColumn.name, "` ").concat(this.buildCreateColumnSql(nonGeneratedColumn, true))));
1400
- }
1401
- }
1402
- columnIndex = clonedTable.indices.find(function (index) {
1403
- return index.columnNames.length === 1 &&
1404
- index.columnNames[0] === column.name;
1405
- });
1406
- if (columnIndex) {
1407
- clonedTable.indices.splice(clonedTable.indices.indexOf(columnIndex), 1);
1408
- upQueries.push(this.dropIndexSql(table, columnIndex));
1409
- downQueries.push(this.createIndexSql(table, columnIndex));
1410
- }
1411
- else if (column.isUnique) {
1412
- uniqueName_1 = this.connection.namingStrategy.uniqueConstraintName(table, [
1413
- column.name,
1414
- ]);
1415
- foundUnique = clonedTable.uniques.find(function (unique) { return unique.name === uniqueName_1; });
1416
- if (foundUnique)
1417
- clonedTable.uniques.splice(clonedTable.uniques.indexOf(foundUnique), 1);
1418
- indexName_1 = this.connection.namingStrategy.indexName(table, [
1419
- column.name,
1420
- ]);
1421
- foundIndex = clonedTable.indices.find(function (index) { return index.name === indexName_1; });
1422
- if (foundIndex)
1423
- clonedTable.indices.splice(clonedTable.indices.indexOf(foundIndex), 1);
1424
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP INDEX `").concat(indexName_1, "`")));
1425
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD UNIQUE INDEX `").concat(indexName_1, "` (`").concat(column.name, "`)")));
1426
- }
1427
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP COLUMN `").concat(column.name, "`")));
1428
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD ").concat(this.buildCreateColumnSql(column, true))));
1429
- if (!(column.generatedType && column.asExpression)) return [3 /*break*/, 5];
1430
- return [4 /*yield*/, this.getCurrentDatabase()];
1431
- case 4:
1432
- currentDatabase = _b.sent();
1433
- deleteQuery = this.deleteTypeormMetadataSql({
1434
- schema: currentDatabase,
1435
- table: table.name,
1436
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1437
- name: column.name,
1438
- });
1439
- insertQuery = this.insertTypeormMetadataSql({
1440
- schema: currentDatabase,
1441
- table: table.name,
1442
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1443
- name: column.name,
1444
- value: column.asExpression,
1445
- });
1446
- upQueries.push(deleteQuery);
1447
- downQueries.push(insertQuery);
1448
- _b.label = 5;
1449
- case 5: return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
1450
- case 6:
1451
- _b.sent();
1452
- clonedTable.removeColumn(column);
1453
- this.replaceCachedTable(table, clonedTable);
1454
- return [2 /*return*/];
1455
- }
1456
- });
1457
- });
1458
- };
910
+ async dropColumn(tableOrName, columnOrName) {
911
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
912
+ ? tableOrName
913
+ : await this.getCachedTable(tableOrName);
914
+ const column = InstanceChecker_1.InstanceChecker.isTableColumn(columnOrName)
915
+ ? columnOrName
916
+ : table.findColumnByName(columnOrName);
917
+ if (!column)
918
+ throw new error_1.TypeORMError(`Column "${columnOrName}" was not found in table "${table.name}"`);
919
+ const clonedTable = table.clone();
920
+ const upQueries = [];
921
+ const downQueries = [];
922
+ // drop primary key constraint
923
+ if (column.isPrimary) {
924
+ // if table have generated column, we must drop AUTO_INCREMENT before changing primary constraints.
925
+ const generatedColumn = clonedTable.columns.find((column) => column.isGenerated &&
926
+ column.generationStrategy === "increment");
927
+ if (generatedColumn) {
928
+ const nonGeneratedColumn = generatedColumn.clone();
929
+ nonGeneratedColumn.isGenerated = false;
930
+ nonGeneratedColumn.generationStrategy = undefined;
931
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${generatedColumn.name}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`));
932
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${nonGeneratedColumn.name}\` ${this.buildCreateColumnSql(generatedColumn, true)}`));
933
+ }
934
+ // dropping primary key constraint
935
+ const columnNames = clonedTable.primaryColumns
936
+ .map((primaryColumn) => `\`${primaryColumn.name}\``)
937
+ .join(", ");
938
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(clonedTable)} DROP PRIMARY KEY`));
939
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(clonedTable)} ADD PRIMARY KEY (${columnNames})`));
940
+ // update column in table
941
+ const tableColumn = clonedTable.findColumnByName(column.name);
942
+ tableColumn.isPrimary = false;
943
+ // if primary key have multiple columns, we must recreate it without dropped column
944
+ if (clonedTable.primaryColumns.length > 0) {
945
+ const columnNames = clonedTable.primaryColumns
946
+ .map((primaryColumn) => `\`${primaryColumn.name}\``)
947
+ .join(", ");
948
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(clonedTable)} ADD PRIMARY KEY (${columnNames})`));
949
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(clonedTable)} DROP PRIMARY KEY`));
950
+ }
951
+ // if we have generated column, and we dropped AUTO_INCREMENT property before, and this column is not current dropping column, we must bring it back
952
+ if (generatedColumn && generatedColumn.name !== column.name) {
953
+ const nonGeneratedColumn = generatedColumn.clone();
954
+ nonGeneratedColumn.isGenerated = false;
955
+ nonGeneratedColumn.generationStrategy = undefined;
956
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${nonGeneratedColumn.name}\` ${this.buildCreateColumnSql(generatedColumn, true)}`));
957
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${generatedColumn.name}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`));
958
+ }
959
+ }
960
+ // drop column index
961
+ const columnIndex = clonedTable.indices.find((index) => index.columnNames.length === 1 &&
962
+ index.columnNames[0] === column.name);
963
+ if (columnIndex) {
964
+ clonedTable.indices.splice(clonedTable.indices.indexOf(columnIndex), 1);
965
+ upQueries.push(this.dropIndexSql(table, columnIndex));
966
+ downQueries.push(this.createIndexSql(table, columnIndex));
967
+ }
968
+ else if (column.isUnique) {
969
+ // we splice constraints both from table uniques and indices.
970
+ const uniqueName = this.connection.namingStrategy.uniqueConstraintName(table, [
971
+ column.name,
972
+ ]);
973
+ const foundUnique = clonedTable.uniques.find((unique) => unique.name === uniqueName);
974
+ if (foundUnique)
975
+ clonedTable.uniques.splice(clonedTable.uniques.indexOf(foundUnique), 1);
976
+ const indexName = this.connection.namingStrategy.indexName(table, [
977
+ column.name,
978
+ ]);
979
+ const foundIndex = clonedTable.indices.find((index) => index.name === indexName);
980
+ if (foundIndex)
981
+ clonedTable.indices.splice(clonedTable.indices.indexOf(foundIndex), 1);
982
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP INDEX \`${indexName}\``));
983
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD UNIQUE INDEX \`${indexName}\` (\`${column.name}\`)`));
984
+ }
985
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP COLUMN \`${column.name}\``));
986
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD ${this.buildCreateColumnSql(column, true)}`));
987
+ if (column.generatedType && column.asExpression) {
988
+ const currentDatabase = await this.getCurrentDatabase();
989
+ const deleteQuery = this.deleteTypeormMetadataSql({
990
+ schema: currentDatabase,
991
+ table: table.name,
992
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
993
+ name: column.name,
994
+ });
995
+ const insertQuery = this.insertTypeormMetadataSql({
996
+ schema: currentDatabase,
997
+ table: table.name,
998
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
999
+ name: column.name,
1000
+ value: column.asExpression,
1001
+ });
1002
+ upQueries.push(deleteQuery);
1003
+ downQueries.push(insertQuery);
1004
+ }
1005
+ await this.executeQueries(upQueries, downQueries);
1006
+ clonedTable.removeColumn(column);
1007
+ this.replaceCachedTable(table, clonedTable);
1008
+ }
1459
1009
  /**
1460
1010
  * Drops the columns in the table.
1461
1011
  */
1462
- MysqlQueryRunner.prototype.dropColumns = function (tableOrName, columns) {
1463
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1464
- var columns_2, columns_2_1, column, e_5_1;
1465
- var e_5, _a;
1466
- return tslib_1.__generator(this, function (_b) {
1467
- switch (_b.label) {
1468
- case 0:
1469
- _b.trys.push([0, 5, 6, 7]);
1470
- columns_2 = tslib_1.__values(columns), columns_2_1 = columns_2.next();
1471
- _b.label = 1;
1472
- case 1:
1473
- if (!!columns_2_1.done) return [3 /*break*/, 4];
1474
- column = columns_2_1.value;
1475
- return [4 /*yield*/, this.dropColumn(tableOrName, column)];
1476
- case 2:
1477
- _b.sent();
1478
- _b.label = 3;
1479
- case 3:
1480
- columns_2_1 = columns_2.next();
1481
- return [3 /*break*/, 1];
1482
- case 4: return [3 /*break*/, 7];
1483
- case 5:
1484
- e_5_1 = _b.sent();
1485
- e_5 = { error: e_5_1 };
1486
- return [3 /*break*/, 7];
1487
- case 6:
1488
- try {
1489
- if (columns_2_1 && !columns_2_1.done && (_a = columns_2.return)) _a.call(columns_2);
1490
- }
1491
- finally { if (e_5) throw e_5.error; }
1492
- return [7 /*endfinally*/];
1493
- case 7: return [2 /*return*/];
1494
- }
1495
- });
1496
- });
1497
- };
1012
+ async dropColumns(tableOrName, columns) {
1013
+ for (const column of columns) {
1014
+ await this.dropColumn(tableOrName, column);
1015
+ }
1016
+ }
1498
1017
  /**
1499
1018
  * Creates a new primary key.
1500
1019
  */
1501
- MysqlQueryRunner.prototype.createPrimaryKey = function (tableOrName, columnNames) {
1502
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1503
- var table, _a, clonedTable, up, down;
1504
- return tslib_1.__generator(this, function (_b) {
1505
- switch (_b.label) {
1506
- case 0:
1507
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1508
- _a = tableOrName;
1509
- return [3 /*break*/, 3];
1510
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
1511
- case 2:
1512
- _a = _b.sent();
1513
- _b.label = 3;
1514
- case 3:
1515
- table = _a;
1516
- clonedTable = table.clone();
1517
- up = this.createPrimaryKeySql(table, columnNames);
1518
- down = this.dropPrimaryKeySql(table);
1519
- return [4 /*yield*/, this.executeQueries(up, down)];
1520
- case 4:
1521
- _b.sent();
1522
- clonedTable.columns.forEach(function (column) {
1523
- if (columnNames.find(function (columnName) { return columnName === column.name; }))
1524
- column.isPrimary = true;
1525
- });
1526
- this.replaceCachedTable(table, clonedTable);
1527
- return [2 /*return*/];
1528
- }
1529
- });
1020
+ async createPrimaryKey(tableOrName, columnNames) {
1021
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
1022
+ ? tableOrName
1023
+ : await this.getCachedTable(tableOrName);
1024
+ const clonedTable = table.clone();
1025
+ const up = this.createPrimaryKeySql(table, columnNames);
1026
+ const down = this.dropPrimaryKeySql(table);
1027
+ await this.executeQueries(up, down);
1028
+ clonedTable.columns.forEach((column) => {
1029
+ if (columnNames.find((columnName) => columnName === column.name))
1030
+ column.isPrimary = true;
1530
1031
  });
1531
- };
1032
+ this.replaceCachedTable(table, clonedTable);
1033
+ }
1532
1034
  /**
1533
1035
  * Updates composite primary keys.
1534
1036
  */
1535
- MysqlQueryRunner.prototype.updatePrimaryKeys = function (tableOrName, columns) {
1536
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1537
- var table, _a, clonedTable, columnNames, upQueries, downQueries, generatedColumn, nonGeneratedColumn, primaryColumns, columnNames_2, columnNamesString, newOrExistGeneratedColumn, nonGeneratedColumn, changedGeneratedColumn;
1538
- return tslib_1.__generator(this, function (_b) {
1539
- switch (_b.label) {
1540
- case 0:
1541
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1542
- _a = tableOrName;
1543
- return [3 /*break*/, 3];
1544
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
1545
- case 2:
1546
- _a = _b.sent();
1547
- _b.label = 3;
1548
- case 3:
1549
- table = _a;
1550
- clonedTable = table.clone();
1551
- columnNames = columns.map(function (column) { return column.name; });
1552
- upQueries = [];
1553
- downQueries = [];
1554
- generatedColumn = clonedTable.columns.find(function (column) {
1555
- return column.isGenerated && column.generationStrategy === "increment";
1556
- });
1557
- if (generatedColumn) {
1558
- nonGeneratedColumn = generatedColumn.clone();
1559
- nonGeneratedColumn.isGenerated = false;
1560
- nonGeneratedColumn.generationStrategy = undefined;
1561
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(generatedColumn.name, "` ").concat(this.buildCreateColumnSql(nonGeneratedColumn, true))));
1562
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(nonGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(generatedColumn, true))));
1563
- }
1564
- primaryColumns = clonedTable.primaryColumns;
1565
- if (primaryColumns.length > 0) {
1566
- columnNames_2 = primaryColumns
1567
- .map(function (column) { return "`".concat(column.name, "`"); })
1568
- .join(", ");
1569
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP PRIMARY KEY")));
1570
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD PRIMARY KEY (").concat(columnNames_2, ")")));
1571
- }
1572
- // update columns in table.
1573
- clonedTable.columns
1574
- .filter(function (column) { return columnNames.indexOf(column.name) !== -1; })
1575
- .forEach(function (column) { return (column.isPrimary = true); });
1576
- columnNamesString = columnNames
1577
- .map(function (columnName) { return "`".concat(columnName, "`"); })
1578
- .join(", ");
1579
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD PRIMARY KEY (").concat(columnNamesString, ")")));
1580
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP PRIMARY KEY")));
1581
- newOrExistGeneratedColumn = generatedColumn
1582
- ? generatedColumn
1583
- : columns.find(function (column) {
1584
- return column.isGenerated &&
1585
- column.generationStrategy === "increment";
1586
- });
1587
- if (newOrExistGeneratedColumn) {
1588
- nonGeneratedColumn = newOrExistGeneratedColumn.clone();
1589
- nonGeneratedColumn.isGenerated = false;
1590
- nonGeneratedColumn.generationStrategy = undefined;
1591
- upQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(nonGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(newOrExistGeneratedColumn, true))));
1592
- downQueries.push(new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " CHANGE `").concat(newOrExistGeneratedColumn.name, "` ").concat(this.buildCreateColumnSql(nonGeneratedColumn, true))));
1593
- changedGeneratedColumn = clonedTable.columns.find(function (column) { return column.name === newOrExistGeneratedColumn.name; });
1594
- changedGeneratedColumn.isGenerated = true;
1595
- changedGeneratedColumn.generationStrategy = "increment";
1596
- }
1597
- return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
1598
- case 4:
1599
- _b.sent();
1600
- this.replaceCachedTable(table, clonedTable);
1601
- return [2 /*return*/];
1602
- }
1603
- });
1604
- });
1605
- };
1037
+ async updatePrimaryKeys(tableOrName, columns) {
1038
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
1039
+ ? tableOrName
1040
+ : await this.getCachedTable(tableOrName);
1041
+ const clonedTable = table.clone();
1042
+ const columnNames = columns.map((column) => column.name);
1043
+ const upQueries = [];
1044
+ const downQueries = [];
1045
+ // if table have generated column, we must drop AUTO_INCREMENT before changing primary constraints.
1046
+ const generatedColumn = clonedTable.columns.find((column) => column.isGenerated && column.generationStrategy === "increment");
1047
+ if (generatedColumn) {
1048
+ const nonGeneratedColumn = generatedColumn.clone();
1049
+ nonGeneratedColumn.isGenerated = false;
1050
+ nonGeneratedColumn.generationStrategy = undefined;
1051
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${generatedColumn.name}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`));
1052
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${nonGeneratedColumn.name}\` ${this.buildCreateColumnSql(generatedColumn, true)}`));
1053
+ }
1054
+ // if table already have primary columns, we must drop them.
1055
+ const primaryColumns = clonedTable.primaryColumns;
1056
+ if (primaryColumns.length > 0) {
1057
+ const columnNames = primaryColumns
1058
+ .map((column) => `\`${column.name}\``)
1059
+ .join(", ");
1060
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`));
1061
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD PRIMARY KEY (${columnNames})`));
1062
+ }
1063
+ // update columns in table.
1064
+ clonedTable.columns
1065
+ .filter((column) => columnNames.indexOf(column.name) !== -1)
1066
+ .forEach((column) => (column.isPrimary = true));
1067
+ const columnNamesString = columnNames
1068
+ .map((columnName) => `\`${columnName}\``)
1069
+ .join(", ");
1070
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD PRIMARY KEY (${columnNamesString})`));
1071
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`));
1072
+ // if we already have generated column or column is changed to generated, and we dropped AUTO_INCREMENT property before, we must bring it back
1073
+ const newOrExistGeneratedColumn = generatedColumn
1074
+ ? generatedColumn
1075
+ : columns.find((column) => column.isGenerated &&
1076
+ column.generationStrategy === "increment");
1077
+ if (newOrExistGeneratedColumn) {
1078
+ const nonGeneratedColumn = newOrExistGeneratedColumn.clone();
1079
+ nonGeneratedColumn.isGenerated = false;
1080
+ nonGeneratedColumn.generationStrategy = undefined;
1081
+ upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${nonGeneratedColumn.name}\` ${this.buildCreateColumnSql(newOrExistGeneratedColumn, true)}`));
1082
+ downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} CHANGE \`${newOrExistGeneratedColumn.name}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`));
1083
+ // if column changed to generated, we must update it in table
1084
+ const changedGeneratedColumn = clonedTable.columns.find((column) => column.name === newOrExistGeneratedColumn.name);
1085
+ changedGeneratedColumn.isGenerated = true;
1086
+ changedGeneratedColumn.generationStrategy = "increment";
1087
+ }
1088
+ await this.executeQueries(upQueries, downQueries);
1089
+ this.replaceCachedTable(table, clonedTable);
1090
+ }
1606
1091
  /**
1607
1092
  * Drops a primary key.
1608
1093
  */
1609
- MysqlQueryRunner.prototype.dropPrimaryKey = function (tableOrName) {
1610
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1611
- var table, _a, up, down;
1612
- return tslib_1.__generator(this, function (_b) {
1613
- switch (_b.label) {
1614
- case 0:
1615
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1616
- _a = tableOrName;
1617
- return [3 /*break*/, 3];
1618
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
1619
- case 2:
1620
- _a = _b.sent();
1621
- _b.label = 3;
1622
- case 3:
1623
- table = _a;
1624
- up = this.dropPrimaryKeySql(table);
1625
- down = this.createPrimaryKeySql(table, table.primaryColumns.map(function (column) { return column.name; }));
1626
- return [4 /*yield*/, this.executeQueries(up, down)];
1627
- case 4:
1628
- _b.sent();
1629
- table.primaryColumns.forEach(function (column) {
1630
- column.isPrimary = false;
1631
- });
1632
- return [2 /*return*/];
1633
- }
1634
- });
1094
+ async dropPrimaryKey(tableOrName) {
1095
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
1096
+ ? tableOrName
1097
+ : await this.getCachedTable(tableOrName);
1098
+ const up = this.dropPrimaryKeySql(table);
1099
+ const down = this.createPrimaryKeySql(table, table.primaryColumns.map((column) => column.name));
1100
+ await this.executeQueries(up, down);
1101
+ table.primaryColumns.forEach((column) => {
1102
+ column.isPrimary = false;
1635
1103
  });
1636
- };
1104
+ }
1637
1105
  /**
1638
1106
  * Creates a new unique constraint.
1639
1107
  */
1640
- MysqlQueryRunner.prototype.createUniqueConstraint = function (tableOrName, uniqueConstraint) {
1641
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1642
- return tslib_1.__generator(this, function (_a) {
1643
- throw new error_1.TypeORMError("MySql does not support unique constraints. Use unique index instead.");
1644
- });
1645
- });
1646
- };
1108
+ async createUniqueConstraint(tableOrName, uniqueConstraint) {
1109
+ throw new error_1.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
1110
+ }
1647
1111
  /**
1648
1112
  * Creates a new unique constraints.
1649
1113
  */
1650
- MysqlQueryRunner.prototype.createUniqueConstraints = function (tableOrName, uniqueConstraints) {
1651
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1652
- return tslib_1.__generator(this, function (_a) {
1653
- throw new error_1.TypeORMError("MySql does not support unique constraints. Use unique index instead.");
1654
- });
1655
- });
1656
- };
1114
+ async createUniqueConstraints(tableOrName, uniqueConstraints) {
1115
+ throw new error_1.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
1116
+ }
1657
1117
  /**
1658
1118
  * Drops an unique constraint.
1659
1119
  */
1660
- MysqlQueryRunner.prototype.dropUniqueConstraint = function (tableOrName, uniqueOrName) {
1661
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1662
- return tslib_1.__generator(this, function (_a) {
1663
- throw new error_1.TypeORMError("MySql does not support unique constraints. Use unique index instead.");
1664
- });
1665
- });
1666
- };
1120
+ async dropUniqueConstraint(tableOrName, uniqueOrName) {
1121
+ throw new error_1.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
1122
+ }
1667
1123
  /**
1668
1124
  * Drops an unique constraints.
1669
1125
  */
1670
- MysqlQueryRunner.prototype.dropUniqueConstraints = function (tableOrName, uniqueConstraints) {
1671
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1672
- return tslib_1.__generator(this, function (_a) {
1673
- throw new error_1.TypeORMError("MySql does not support unique constraints. Use unique index instead.");
1674
- });
1675
- });
1676
- };
1126
+ async dropUniqueConstraints(tableOrName, uniqueConstraints) {
1127
+ throw new error_1.TypeORMError(`MySql does not support unique constraints. Use unique index instead.`);
1128
+ }
1677
1129
  /**
1678
1130
  * Creates a new check constraint.
1679
1131
  */
1680
- MysqlQueryRunner.prototype.createCheckConstraint = function (tableOrName, checkConstraint) {
1681
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1682
- return tslib_1.__generator(this, function (_a) {
1683
- throw new error_1.TypeORMError("MySql does not support check constraints.");
1684
- });
1685
- });
1686
- };
1132
+ async createCheckConstraint(tableOrName, checkConstraint) {
1133
+ throw new error_1.TypeORMError(`MySql does not support check constraints.`);
1134
+ }
1687
1135
  /**
1688
1136
  * Creates a new check constraints.
1689
1137
  */
1690
- MysqlQueryRunner.prototype.createCheckConstraints = function (tableOrName, checkConstraints) {
1691
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1692
- return tslib_1.__generator(this, function (_a) {
1693
- throw new error_1.TypeORMError("MySql does not support check constraints.");
1694
- });
1695
- });
1696
- };
1138
+ async createCheckConstraints(tableOrName, checkConstraints) {
1139
+ throw new error_1.TypeORMError(`MySql does not support check constraints.`);
1140
+ }
1697
1141
  /**
1698
1142
  * Drops check constraint.
1699
1143
  */
1700
- MysqlQueryRunner.prototype.dropCheckConstraint = function (tableOrName, checkOrName) {
1701
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1702
- return tslib_1.__generator(this, function (_a) {
1703
- throw new error_1.TypeORMError("MySql does not support check constraints.");
1704
- });
1705
- });
1706
- };
1144
+ async dropCheckConstraint(tableOrName, checkOrName) {
1145
+ throw new error_1.TypeORMError(`MySql does not support check constraints.`);
1146
+ }
1707
1147
  /**
1708
1148
  * Drops check constraints.
1709
1149
  */
1710
- MysqlQueryRunner.prototype.dropCheckConstraints = function (tableOrName, checkConstraints) {
1711
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1712
- return tslib_1.__generator(this, function (_a) {
1713
- throw new error_1.TypeORMError("MySql does not support check constraints.");
1714
- });
1715
- });
1716
- };
1150
+ async dropCheckConstraints(tableOrName, checkConstraints) {
1151
+ throw new error_1.TypeORMError(`MySql does not support check constraints.`);
1152
+ }
1717
1153
  /**
1718
1154
  * Creates a new exclusion constraint.
1719
1155
  */
1720
- MysqlQueryRunner.prototype.createExclusionConstraint = function (tableOrName, exclusionConstraint) {
1721
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1722
- return tslib_1.__generator(this, function (_a) {
1723
- throw new error_1.TypeORMError("MySql does not support exclusion constraints.");
1724
- });
1725
- });
1726
- };
1156
+ async createExclusionConstraint(tableOrName, exclusionConstraint) {
1157
+ throw new error_1.TypeORMError(`MySql does not support exclusion constraints.`);
1158
+ }
1727
1159
  /**
1728
1160
  * Creates a new exclusion constraints.
1729
1161
  */
1730
- MysqlQueryRunner.prototype.createExclusionConstraints = function (tableOrName, exclusionConstraints) {
1731
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1732
- return tslib_1.__generator(this, function (_a) {
1733
- throw new error_1.TypeORMError("MySql does not support exclusion constraints.");
1734
- });
1735
- });
1736
- };
1162
+ async createExclusionConstraints(tableOrName, exclusionConstraints) {
1163
+ throw new error_1.TypeORMError(`MySql does not support exclusion constraints.`);
1164
+ }
1737
1165
  /**
1738
1166
  * Drops exclusion constraint.
1739
1167
  */
1740
- MysqlQueryRunner.prototype.dropExclusionConstraint = function (tableOrName, exclusionOrName) {
1741
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1742
- return tslib_1.__generator(this, function (_a) {
1743
- throw new error_1.TypeORMError("MySql does not support exclusion constraints.");
1744
- });
1745
- });
1746
- };
1168
+ async dropExclusionConstraint(tableOrName, exclusionOrName) {
1169
+ throw new error_1.TypeORMError(`MySql does not support exclusion constraints.`);
1170
+ }
1747
1171
  /**
1748
1172
  * Drops exclusion constraints.
1749
1173
  */
1750
- MysqlQueryRunner.prototype.dropExclusionConstraints = function (tableOrName, exclusionConstraints) {
1751
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1752
- return tslib_1.__generator(this, function (_a) {
1753
- throw new error_1.TypeORMError("MySql does not support exclusion constraints.");
1754
- });
1755
- });
1756
- };
1174
+ async dropExclusionConstraints(tableOrName, exclusionConstraints) {
1175
+ throw new error_1.TypeORMError(`MySql does not support exclusion constraints.`);
1176
+ }
1757
1177
  /**
1758
1178
  * Creates a new foreign key.
1759
1179
  */
1760
- MysqlQueryRunner.prototype.createForeignKey = function (tableOrName, foreignKey) {
1761
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1762
- var table, _a, up, down;
1763
- return tslib_1.__generator(this, function (_b) {
1764
- switch (_b.label) {
1765
- case 0:
1766
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1767
- _a = tableOrName;
1768
- return [3 /*break*/, 3];
1769
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)
1770
- // new FK may be passed without name. In this case we generate FK name manually.
1771
- ];
1772
- case 2:
1773
- _a = _b.sent();
1774
- _b.label = 3;
1775
- case 3:
1776
- table = _a;
1777
- // new FK may be passed without name. In this case we generate FK name manually.
1778
- if (!foreignKey.name)
1779
- foreignKey.name = this.connection.namingStrategy.foreignKeyName(table, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
1780
- up = this.createForeignKeySql(table, foreignKey);
1781
- down = this.dropForeignKeySql(table, foreignKey);
1782
- return [4 /*yield*/, this.executeQueries(up, down)];
1783
- case 4:
1784
- _b.sent();
1785
- table.addForeignKey(foreignKey);
1786
- return [2 /*return*/];
1787
- }
1788
- });
1789
- });
1790
- };
1180
+ async createForeignKey(tableOrName, foreignKey) {
1181
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
1182
+ ? tableOrName
1183
+ : await this.getCachedTable(tableOrName);
1184
+ // new FK may be passed without name. In this case we generate FK name manually.
1185
+ if (!foreignKey.name)
1186
+ foreignKey.name = this.connection.namingStrategy.foreignKeyName(table, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
1187
+ const up = this.createForeignKeySql(table, foreignKey);
1188
+ const down = this.dropForeignKeySql(table, foreignKey);
1189
+ await this.executeQueries(up, down);
1190
+ table.addForeignKey(foreignKey);
1191
+ }
1791
1192
  /**
1792
1193
  * Creates a new foreign keys.
1793
1194
  */
1794
- MysqlQueryRunner.prototype.createForeignKeys = function (tableOrName, foreignKeys) {
1795
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1796
- var promises;
1797
- var _this = this;
1798
- return tslib_1.__generator(this, function (_a) {
1799
- switch (_a.label) {
1800
- case 0:
1801
- promises = foreignKeys.map(function (foreignKey) {
1802
- return _this.createForeignKey(tableOrName, foreignKey);
1803
- });
1804
- return [4 /*yield*/, Promise.all(promises)];
1805
- case 1:
1806
- _a.sent();
1807
- return [2 /*return*/];
1808
- }
1809
- });
1810
- });
1811
- };
1195
+ async createForeignKeys(tableOrName, foreignKeys) {
1196
+ const promises = foreignKeys.map((foreignKey) => this.createForeignKey(tableOrName, foreignKey));
1197
+ await Promise.all(promises);
1198
+ }
1812
1199
  /**
1813
1200
  * Drops a foreign key.
1814
1201
  */
1815
- MysqlQueryRunner.prototype.dropForeignKey = function (tableOrName, foreignKeyOrName) {
1816
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1817
- var table, _a, foreignKey, up, down;
1818
- return tslib_1.__generator(this, function (_b) {
1819
- switch (_b.label) {
1820
- case 0:
1821
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1822
- _a = tableOrName;
1823
- return [3 /*break*/, 3];
1824
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
1825
- case 2:
1826
- _a = _b.sent();
1827
- _b.label = 3;
1828
- case 3:
1829
- table = _a;
1830
- foreignKey = InstanceChecker_1.InstanceChecker.isTableForeignKey(foreignKeyOrName)
1831
- ? foreignKeyOrName
1832
- : table.foreignKeys.find(function (fk) { return fk.name === foreignKeyOrName; });
1833
- if (!foreignKey)
1834
- throw new error_1.TypeORMError("Supplied foreign key was not found in table ".concat(table.name));
1835
- up = this.dropForeignKeySql(table, foreignKey);
1836
- down = this.createForeignKeySql(table, foreignKey);
1837
- return [4 /*yield*/, this.executeQueries(up, down)];
1838
- case 4:
1839
- _b.sent();
1840
- table.removeForeignKey(foreignKey);
1841
- return [2 /*return*/];
1842
- }
1843
- });
1844
- });
1845
- };
1202
+ async dropForeignKey(tableOrName, foreignKeyOrName) {
1203
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
1204
+ ? tableOrName
1205
+ : await this.getCachedTable(tableOrName);
1206
+ const foreignKey = InstanceChecker_1.InstanceChecker.isTableForeignKey(foreignKeyOrName)
1207
+ ? foreignKeyOrName
1208
+ : table.foreignKeys.find((fk) => fk.name === foreignKeyOrName);
1209
+ if (!foreignKey)
1210
+ throw new error_1.TypeORMError(`Supplied foreign key was not found in table ${table.name}`);
1211
+ const up = this.dropForeignKeySql(table, foreignKey);
1212
+ const down = this.createForeignKeySql(table, foreignKey);
1213
+ await this.executeQueries(up, down);
1214
+ table.removeForeignKey(foreignKey);
1215
+ }
1846
1216
  /**
1847
1217
  * Drops a foreign keys from the table.
1848
1218
  */
1849
- MysqlQueryRunner.prototype.dropForeignKeys = function (tableOrName, foreignKeys) {
1850
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1851
- var promises;
1852
- var _this = this;
1853
- return tslib_1.__generator(this, function (_a) {
1854
- switch (_a.label) {
1855
- case 0:
1856
- promises = foreignKeys.map(function (foreignKey) {
1857
- return _this.dropForeignKey(tableOrName, foreignKey);
1858
- });
1859
- return [4 /*yield*/, Promise.all(promises)];
1860
- case 1:
1861
- _a.sent();
1862
- return [2 /*return*/];
1863
- }
1864
- });
1865
- });
1866
- };
1219
+ async dropForeignKeys(tableOrName, foreignKeys) {
1220
+ const promises = foreignKeys.map((foreignKey) => this.dropForeignKey(tableOrName, foreignKey));
1221
+ await Promise.all(promises);
1222
+ }
1867
1223
  /**
1868
1224
  * Creates a new index.
1869
1225
  */
1870
- MysqlQueryRunner.prototype.createIndex = function (tableOrName, index) {
1871
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1872
- var table, _a, up, down;
1873
- return tslib_1.__generator(this, function (_b) {
1874
- switch (_b.label) {
1875
- case 0:
1876
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1877
- _a = tableOrName;
1878
- return [3 /*break*/, 3];
1879
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)
1880
- // new index may be passed without name. In this case we generate index name manually.
1881
- ];
1882
- case 2:
1883
- _a = _b.sent();
1884
- _b.label = 3;
1885
- case 3:
1886
- table = _a;
1887
- // new index may be passed without name. In this case we generate index name manually.
1888
- if (!index.name)
1889
- index.name = this.generateIndexName(table, index);
1890
- up = this.createIndexSql(table, index);
1891
- down = this.dropIndexSql(table, index);
1892
- return [4 /*yield*/, this.executeQueries(up, down)];
1893
- case 4:
1894
- _b.sent();
1895
- table.addIndex(index, true);
1896
- return [2 /*return*/];
1897
- }
1898
- });
1899
- });
1900
- };
1226
+ async createIndex(tableOrName, index) {
1227
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
1228
+ ? tableOrName
1229
+ : await this.getCachedTable(tableOrName);
1230
+ // new index may be passed without name. In this case we generate index name manually.
1231
+ if (!index.name)
1232
+ index.name = this.generateIndexName(table, index);
1233
+ const up = this.createIndexSql(table, index);
1234
+ const down = this.dropIndexSql(table, index);
1235
+ await this.executeQueries(up, down);
1236
+ table.addIndex(index, true);
1237
+ }
1901
1238
  /**
1902
1239
  * Creates a new indices
1903
1240
  */
1904
- MysqlQueryRunner.prototype.createIndices = function (tableOrName, indices) {
1905
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1906
- var promises;
1907
- var _this = this;
1908
- return tslib_1.__generator(this, function (_a) {
1909
- switch (_a.label) {
1910
- case 0:
1911
- promises = indices.map(function (index) {
1912
- return _this.createIndex(tableOrName, index);
1913
- });
1914
- return [4 /*yield*/, Promise.all(promises)];
1915
- case 1:
1916
- _a.sent();
1917
- return [2 /*return*/];
1918
- }
1919
- });
1920
- });
1921
- };
1241
+ async createIndices(tableOrName, indices) {
1242
+ const promises = indices.map((index) => this.createIndex(tableOrName, index));
1243
+ await Promise.all(promises);
1244
+ }
1922
1245
  /**
1923
1246
  * Drops an index.
1924
1247
  */
1925
- MysqlQueryRunner.prototype.dropIndex = function (tableOrName, indexOrName) {
1926
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1927
- var table, _a, index, up, down;
1928
- return tslib_1.__generator(this, function (_b) {
1929
- switch (_b.label) {
1930
- case 0:
1931
- if (!InstanceChecker_1.InstanceChecker.isTable(tableOrName)) return [3 /*break*/, 1];
1932
- _a = tableOrName;
1933
- return [3 /*break*/, 3];
1934
- case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)];
1935
- case 2:
1936
- _a = _b.sent();
1937
- _b.label = 3;
1938
- case 3:
1939
- table = _a;
1940
- index = InstanceChecker_1.InstanceChecker.isTableIndex(indexOrName)
1941
- ? indexOrName
1942
- : table.indices.find(function (i) { return i.name === indexOrName; });
1943
- if (!index)
1944
- throw new error_1.TypeORMError("Supplied index ".concat(indexOrName, " was not found in table ").concat(table.name));
1945
- // old index may be passed without name. In this case we generate index name manually.
1946
- if (!index.name)
1947
- index.name = this.generateIndexName(table, index);
1948
- up = this.dropIndexSql(table, index);
1949
- down = this.createIndexSql(table, index);
1950
- return [4 /*yield*/, this.executeQueries(up, down)];
1951
- case 4:
1952
- _b.sent();
1953
- table.removeIndex(index, true);
1954
- return [2 /*return*/];
1955
- }
1956
- });
1957
- });
1958
- };
1248
+ async dropIndex(tableOrName, indexOrName) {
1249
+ const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
1250
+ ? tableOrName
1251
+ : await this.getCachedTable(tableOrName);
1252
+ const index = InstanceChecker_1.InstanceChecker.isTableIndex(indexOrName)
1253
+ ? indexOrName
1254
+ : table.indices.find((i) => i.name === indexOrName);
1255
+ if (!index)
1256
+ throw new error_1.TypeORMError(`Supplied index ${indexOrName} was not found in table ${table.name}`);
1257
+ // old index may be passed without name. In this case we generate index name manually.
1258
+ if (!index.name)
1259
+ index.name = this.generateIndexName(table, index);
1260
+ const up = this.dropIndexSql(table, index);
1261
+ const down = this.createIndexSql(table, index);
1262
+ await this.executeQueries(up, down);
1263
+ table.removeIndex(index, true);
1264
+ }
1959
1265
  /**
1960
1266
  * Drops an indices from the table.
1961
1267
  */
1962
- MysqlQueryRunner.prototype.dropIndices = function (tableOrName, indices) {
1963
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1964
- var promises;
1965
- var _this = this;
1966
- return tslib_1.__generator(this, function (_a) {
1967
- switch (_a.label) {
1968
- case 0:
1969
- promises = indices.map(function (index) {
1970
- return _this.dropIndex(tableOrName, index);
1971
- });
1972
- return [4 /*yield*/, Promise.all(promises)];
1973
- case 1:
1974
- _a.sent();
1975
- return [2 /*return*/];
1976
- }
1977
- });
1978
- });
1979
- };
1268
+ async dropIndices(tableOrName, indices) {
1269
+ const promises = indices.map((index) => this.dropIndex(tableOrName, index));
1270
+ await Promise.all(promises);
1271
+ }
1980
1272
  /**
1981
1273
  * Clears all table contents.
1982
1274
  * Note: this operation uses SQL's TRUNCATE query which cannot be reverted in transactions.
1983
1275
  */
1984
- MysqlQueryRunner.prototype.clearTable = function (tableOrName) {
1985
- return tslib_1.__awaiter(this, void 0, void 0, function () {
1986
- return tslib_1.__generator(this, function (_a) {
1987
- switch (_a.label) {
1988
- case 0: return [4 /*yield*/, this.query("TRUNCATE TABLE ".concat(this.escapePath(tableOrName)))];
1989
- case 1:
1990
- _a.sent();
1991
- return [2 /*return*/];
1992
- }
1993
- });
1994
- });
1995
- };
1276
+ async clearTable(tableOrName) {
1277
+ await this.query(`TRUNCATE TABLE ${this.escapePath(tableOrName)}`);
1278
+ }
1996
1279
  /**
1997
1280
  * Removes all tables from the currently connected database.
1998
1281
  * Be careful using this method and avoid using it in production or migrations
1999
1282
  * (because it can clear all your database).
2000
1283
  */
2001
- MysqlQueryRunner.prototype.clearDatabase = function (database) {
2002
- return tslib_1.__awaiter(this, void 0, void 0, function () {
2003
- var dbName, isDatabaseExist, isAnotherTransactionActive, selectViewDropsQuery, dropViewQueries, disableForeignKeysCheckQuery, dropTablesQuery, enableForeignKeysCheckQuery, dropQueries, error_2, rollbackError_1;
2004
- var _this = this;
2005
- return tslib_1.__generator(this, function (_a) {
2006
- switch (_a.label) {
2007
- case 0:
2008
- dbName = database ? database : this.driver.database;
2009
- if (!dbName) return [3 /*break*/, 2];
2010
- return [4 /*yield*/, this.hasDatabase(dbName)];
2011
- case 1:
2012
- isDatabaseExist = _a.sent();
2013
- if (!isDatabaseExist)
2014
- return [2 /*return*/, Promise.resolve()];
2015
- return [3 /*break*/, 3];
2016
- case 2: throw new error_1.TypeORMError("Can not clear database. No database is specified");
2017
- case 3:
2018
- isAnotherTransactionActive = this.isTransactionActive;
2019
- if (!!isAnotherTransactionActive) return [3 /*break*/, 5];
2020
- return [4 /*yield*/, this.startTransaction()];
2021
- case 4:
2022
- _a.sent();
2023
- _a.label = 5;
2024
- case 5:
2025
- _a.trys.push([5, 14, , 20]);
2026
- selectViewDropsQuery = "SELECT concat('DROP VIEW IF EXISTS `', table_schema, '`.`', table_name, '`') AS `query` FROM `INFORMATION_SCHEMA`.`VIEWS` WHERE `TABLE_SCHEMA` = '".concat(dbName, "'");
2027
- return [4 /*yield*/, this.query(selectViewDropsQuery)];
2028
- case 6:
2029
- dropViewQueries = _a.sent();
2030
- return [4 /*yield*/, Promise.all(dropViewQueries.map(function (q) { return _this.query(q["query"]); }))];
2031
- case 7:
2032
- _a.sent();
2033
- disableForeignKeysCheckQuery = "SET FOREIGN_KEY_CHECKS = 0;";
2034
- dropTablesQuery = "SELECT concat('DROP TABLE IF EXISTS `', table_schema, '`.`', table_name, '`') AS `query` FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = '".concat(dbName, "'");
2035
- enableForeignKeysCheckQuery = "SET FOREIGN_KEY_CHECKS = 1;";
2036
- return [4 /*yield*/, this.query(disableForeignKeysCheckQuery)];
2037
- case 8:
2038
- _a.sent();
2039
- return [4 /*yield*/, this.query(dropTablesQuery)];
2040
- case 9:
2041
- dropQueries = _a.sent();
2042
- return [4 /*yield*/, Promise.all(dropQueries.map(function (query) { return _this.query(query["query"]); }))];
2043
- case 10:
2044
- _a.sent();
2045
- return [4 /*yield*/, this.query(enableForeignKeysCheckQuery)];
2046
- case 11:
2047
- _a.sent();
2048
- if (!!isAnotherTransactionActive) return [3 /*break*/, 13];
2049
- return [4 /*yield*/, this.commitTransaction()];
2050
- case 12:
2051
- _a.sent();
2052
- _a.label = 13;
2053
- case 13: return [3 /*break*/, 20];
2054
- case 14:
2055
- error_2 = _a.sent();
2056
- _a.label = 15;
2057
- case 15:
2058
- _a.trys.push([15, 18, , 19]);
2059
- if (!!isAnotherTransactionActive) return [3 /*break*/, 17];
2060
- return [4 /*yield*/, this.rollbackTransaction()];
2061
- case 16:
2062
- _a.sent();
2063
- _a.label = 17;
2064
- case 17: return [3 /*break*/, 19];
2065
- case 18:
2066
- rollbackError_1 = _a.sent();
2067
- return [3 /*break*/, 19];
2068
- case 19: throw error_2;
2069
- case 20: return [2 /*return*/];
2070
- }
2071
- });
2072
- });
2073
- };
1284
+ async clearDatabase(database) {
1285
+ const dbName = database ? database : this.driver.database;
1286
+ if (dbName) {
1287
+ const isDatabaseExist = await this.hasDatabase(dbName);
1288
+ if (!isDatabaseExist)
1289
+ return Promise.resolve();
1290
+ }
1291
+ else {
1292
+ throw new error_1.TypeORMError(`Can not clear database. No database is specified`);
1293
+ }
1294
+ const isAnotherTransactionActive = this.isTransactionActive;
1295
+ if (!isAnotherTransactionActive)
1296
+ await this.startTransaction();
1297
+ try {
1298
+ const selectViewDropsQuery = `SELECT concat('DROP VIEW IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`VIEWS\` WHERE \`TABLE_SCHEMA\` = '${dbName}'`;
1299
+ const dropViewQueries = await this.query(selectViewDropsQuery);
1300
+ await Promise.all(dropViewQueries.map((q) => this.query(q["query"])));
1301
+ const disableForeignKeysCheckQuery = `SET FOREIGN_KEY_CHECKS = 0;`;
1302
+ const dropTablesQuery = `SELECT concat('DROP TABLE IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE \`TABLE_SCHEMA\` = '${dbName}'`;
1303
+ const enableForeignKeysCheckQuery = `SET FOREIGN_KEY_CHECKS = 1;`;
1304
+ await this.query(disableForeignKeysCheckQuery);
1305
+ const dropQueries = await this.query(dropTablesQuery);
1306
+ await Promise.all(dropQueries.map((query) => this.query(query["query"])));
1307
+ await this.query(enableForeignKeysCheckQuery);
1308
+ if (!isAnotherTransactionActive)
1309
+ await this.commitTransaction();
1310
+ }
1311
+ catch (error) {
1312
+ try {
1313
+ // we throw original error even if rollback thrown an error
1314
+ if (!isAnotherTransactionActive)
1315
+ await this.rollbackTransaction();
1316
+ }
1317
+ catch (rollbackError) { }
1318
+ throw error;
1319
+ }
1320
+ }
2074
1321
  // -------------------------------------------------------------------------
2075
1322
  // Protected Methods
2076
1323
  // -------------------------------------------------------------------------
2077
- MysqlQueryRunner.prototype.loadViews = function (viewNames) {
2078
- return tslib_1.__awaiter(this, void 0, void 0, function () {
2079
- var hasTable, currentDatabase, viewsCondition, query, dbViews;
2080
- var _this = this;
2081
- return tslib_1.__generator(this, function (_a) {
2082
- switch (_a.label) {
2083
- case 0: return [4 /*yield*/, this.hasTable(this.getTypeormMetadataTableName())];
2084
- case 1:
2085
- hasTable = _a.sent();
2086
- if (!hasTable) {
2087
- return [2 /*return*/, []];
2088
- }
2089
- if (!viewNames) {
2090
- viewNames = [];
2091
- }
2092
- return [4 /*yield*/, this.getCurrentDatabase()];
2093
- case 2:
2094
- currentDatabase = _a.sent();
2095
- viewsCondition = viewNames
2096
- .map(function (tableName) {
2097
- var _a = _this.driver.parseTableName(tableName), database = _a.database, name = _a.tableName;
2098
- if (!database) {
2099
- database = currentDatabase;
2100
- }
2101
- return "(`t`.`schema` = '".concat(database, "' AND `t`.`name` = '").concat(name, "')");
2102
- })
2103
- .join(" OR ");
2104
- query = "SELECT `t`.*, `v`.`check_option` FROM ".concat(this.escapePath(this.getTypeormMetadataTableName()), " `t` ") +
2105
- "INNER JOIN `information_schema`.`views` `v` ON `v`.`table_schema` = `t`.`schema` AND `v`.`table_name` = `t`.`name` WHERE `t`.`type` = '".concat(MetadataTableType_1.MetadataTableType.VIEW, "' ").concat(viewsCondition ? "AND (".concat(viewsCondition, ")") : "");
2106
- return [4 /*yield*/, this.query(query)];
2107
- case 3:
2108
- dbViews = _a.sent();
2109
- return [2 /*return*/, dbViews.map(function (dbView) {
2110
- var view = new View_1.View();
2111
- var db = dbView["schema"] === currentDatabase
2112
- ? undefined
2113
- : dbView["schema"];
2114
- view.database = dbView["schema"];
2115
- view.name = _this.driver.buildTableName(dbView["name"], undefined, db);
2116
- view.expression = dbView["value"];
2117
- return view;
2118
- })];
2119
- }
2120
- });
1324
+ async loadViews(viewNames) {
1325
+ const hasTable = await this.hasTable(this.getTypeormMetadataTableName());
1326
+ if (!hasTable) {
1327
+ return [];
1328
+ }
1329
+ if (!viewNames) {
1330
+ viewNames = [];
1331
+ }
1332
+ const currentDatabase = await this.getCurrentDatabase();
1333
+ const viewsCondition = viewNames
1334
+ .map((tableName) => {
1335
+ let { database, tableName: name } = this.driver.parseTableName(tableName);
1336
+ if (!database) {
1337
+ database = currentDatabase;
1338
+ }
1339
+ return `(\`t\`.\`schema\` = '${database}' AND \`t\`.\`name\` = '${name}')`;
1340
+ })
1341
+ .join(" OR ");
1342
+ const query = `SELECT \`t\`.*, \`v\`.\`check_option\` FROM ${this.escapePath(this.getTypeormMetadataTableName())} \`t\` ` +
1343
+ `INNER JOIN \`information_schema\`.\`views\` \`v\` ON \`v\`.\`table_schema\` = \`t\`.\`schema\` AND \`v\`.\`table_name\` = \`t\`.\`name\` WHERE \`t\`.\`type\` = '${MetadataTableType_1.MetadataTableType.VIEW}' ${viewsCondition ? `AND (${viewsCondition})` : ""}`;
1344
+ const dbViews = await this.query(query);
1345
+ return dbViews.map((dbView) => {
1346
+ const view = new View_1.View();
1347
+ const db = dbView["schema"] === currentDatabase
1348
+ ? undefined
1349
+ : dbView["schema"];
1350
+ view.database = dbView["schema"];
1351
+ view.name = this.driver.buildTableName(dbView["name"], undefined, db);
1352
+ view.expression = dbView["value"];
1353
+ return view;
2121
1354
  });
2122
- };
1355
+ }
2123
1356
  /**
2124
1357
  * Loads all tables (with given names) from the database and creates a Table from them.
2125
1358
  */
2126
- MysqlQueryRunner.prototype.loadTables = function (tableNames) {
2127
- return tslib_1.__awaiter(this, void 0, void 0, function () {
2128
- var currentDatabase, dbTables, tablesSql, _a, _b, _c, _d, tablesSql, _e, _f, _g, _h, statsSubquerySql, kcuSubquerySql, rcSubquerySql, columnsSql, collationsSql, primaryKeySql, indicesSql, foreignKeysSql, _j, dbColumns, dbPrimaryKeys, dbCollations, dbIndices, dbForeignKeys, isMariaDb, dbVersion;
2129
- var _this = this;
2130
- return tslib_1.__generator(this, function (_k) {
2131
- switch (_k.label) {
2132
- case 0:
2133
- if (tableNames && tableNames.length === 0) {
2134
- return [2 /*return*/, []];
2135
- }
2136
- return [4 /*yield*/, this.getCurrentDatabase()
2137
- // The following SQL brought to you by:
2138
- // A terrible understanding of https://dev.mysql.com/doc/refman/8.0/en/information-schema-optimization.html
2139
- //
2140
- // Short Version:
2141
- // INFORMATION_SCHEMA is a weird metadata virtual table and follows VERY FEW of the normal
2142
- // query optimization rules. Depending on the columns you query against & the columns you're SELECTing
2143
- // there can be a drastically different query performance - this is because the tables map to
2144
- // data on the disk and some pieces of data require a scan of the data directory, the database files, etc
2145
- // With most of these, you'll want to do an `EXPLAIN` when making changes to make sure
2146
- // the changes you're making aren't changing the query performance profile negatively
2147
- // When you do the explain you'll want to look at the `Extra` field -
2148
- // It will look something like: "Using where; {FILE_OPENING}; Scanned {DB_NUM} databases"
2149
- // FILE_OPENING will commonly be OPEN_FRM_ONLY or OPEN_FULL_TABLE - you want to aim to NOT do
2150
- // an OPEN_FULL_TABLE unless necessary. DB_NUM may be a number or "all" - you really want to
2151
- // keep this to 0 or 1. Ideally 0. "All" means you've scanned all databases - not good.
2152
- //
2153
- // For more info, see the above link to the MySQL docs.
2154
- //
2155
- // Something not noted in the docs is that complex `WHERE` clauses - such as `OR` expressions -
2156
- // will cause the query to not hit the optimizations & do full scans. This is why
2157
- // a number of queries below do `UNION`s of single `WHERE` clauses.
2158
- ];
2159
- case 1:
2160
- currentDatabase = _k.sent();
2161
- dbTables = [];
2162
- if (!!tableNames) return [3 /*break*/, 3];
2163
- tablesSql = "SELECT `TABLE_SCHEMA`, `TABLE_NAME` FROM `INFORMATION_SCHEMA`.`TABLES`";
2164
- _b = (_a = dbTables.push).apply;
2165
- _c = [dbTables];
2166
- _d = [[]];
2167
- return [4 /*yield*/, this.query(tablesSql)];
2168
- case 2:
2169
- _b.apply(_a, _c.concat([tslib_1.__spreadArray.apply(void 0, _d.concat([tslib_1.__read.apply(void 0, [(_k.sent())]), false]))]));
2170
- return [3 /*break*/, 5];
2171
- case 3:
2172
- tablesSql = tableNames
2173
- .filter(function (tableName) { return tableName; })
2174
- .map(function (tableName) {
2175
- var _a = _this.driver.parseTableName(tableName), database = _a.database, name = _a.tableName;
2176
- if (!database) {
2177
- database = currentDatabase;
2178
- }
2179
- return "SELECT `TABLE_SCHEMA`, `TABLE_NAME` FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = '".concat(database, "' AND `TABLE_NAME` = '").concat(name, "'");
2180
- })
2181
- .join(" UNION ");
2182
- _f = (_e = dbTables.push).apply;
2183
- _g = [dbTables];
2184
- _h = [[]];
2185
- return [4 /*yield*/, this.query(tablesSql)];
2186
- case 4:
2187
- _f.apply(_e, _g.concat([tslib_1.__spreadArray.apply(void 0, _h.concat([tslib_1.__read.apply(void 0, [(_k.sent())]), false]))]));
2188
- _k.label = 5;
2189
- case 5:
2190
- // if tables were not found in the db, no need to proceed
2191
- if (!dbTables.length)
2192
- return [2 /*return*/, []
2193
- // Avoid data directory scan: TABLE_SCHEMA
2194
- // Avoid database directory scan: TABLE_NAME
2195
- // Full columns: CARDINALITY & INDEX_TYPE - everything else is FRM only
2196
- ];
2197
- statsSubquerySql = dbTables
2198
- .map(function (_a) {
2199
- var TABLE_SCHEMA = _a.TABLE_SCHEMA, TABLE_NAME = _a.TABLE_NAME;
2200
- return "\n SELECT\n *\n FROM `INFORMATION_SCHEMA`.`STATISTICS`\n WHERE\n `TABLE_SCHEMA` = '".concat(TABLE_SCHEMA, "'\n AND\n `TABLE_NAME` = '").concat(TABLE_NAME, "'\n ");
2201
- })
2202
- .join(" UNION ");
2203
- kcuSubquerySql = dbTables
2204
- .map(function (_a) {
2205
- var TABLE_SCHEMA = _a.TABLE_SCHEMA, TABLE_NAME = _a.TABLE_NAME;
2206
- return "\n SELECT\n *\n FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE` `kcu`\n WHERE\n `kcu`.`TABLE_SCHEMA` = '".concat(TABLE_SCHEMA, "'\n AND\n `kcu`.`TABLE_NAME` = '").concat(TABLE_NAME, "'\n ");
2207
- })
2208
- .join(" UNION ");
2209
- rcSubquerySql = dbTables
2210
- .map(function (_a) {
2211
- var TABLE_SCHEMA = _a.TABLE_SCHEMA, TABLE_NAME = _a.TABLE_NAME;
2212
- return "\n SELECT\n *\n FROM `INFORMATION_SCHEMA`.`REFERENTIAL_CONSTRAINTS`\n WHERE\n `CONSTRAINT_SCHEMA` = '".concat(TABLE_SCHEMA, "'\n AND\n `TABLE_NAME` = '").concat(TABLE_NAME, "'\n ");
2213
- })
2214
- .join(" UNION ");
2215
- columnsSql = dbTables
2216
- .map(function (_a) {
2217
- var TABLE_SCHEMA = _a.TABLE_SCHEMA, TABLE_NAME = _a.TABLE_NAME;
2218
- return "\n SELECT\n *\n FROM\n `INFORMATION_SCHEMA`.`COLUMNS`\n WHERE\n `TABLE_SCHEMA` = '".concat(TABLE_SCHEMA, "'\n AND\n `TABLE_NAME` = '").concat(TABLE_NAME, "'\n ");
2219
- })
2220
- .join(" UNION ");
2221
- collationsSql = "\n SELECT\n `SCHEMA_NAME`,\n `DEFAULT_CHARACTER_SET_NAME` as `CHARSET`,\n `DEFAULT_COLLATION_NAME` AS `COLLATION`\n FROM `INFORMATION_SCHEMA`.`SCHEMATA`\n ";
2222
- primaryKeySql = "SELECT * FROM (".concat(kcuSubquerySql, ") `kcu` WHERE `CONSTRAINT_NAME` = 'PRIMARY'");
2223
- indicesSql = "\n SELECT\n `s`.*\n FROM (".concat(statsSubquerySql, ") `s`\n LEFT JOIN (").concat(rcSubquerySql, ") `rc`\n ON\n `s`.`INDEX_NAME` = `rc`.`CONSTRAINT_NAME`\n AND\n `s`.`TABLE_SCHEMA` = `rc`.`CONSTRAINT_SCHEMA`\n WHERE\n `s`.`INDEX_NAME` != 'PRIMARY'\n AND\n `rc`.`CONSTRAINT_NAME` IS NULL\n ");
2224
- foreignKeysSql = "\n SELECT\n `kcu`.`TABLE_SCHEMA`,\n `kcu`.`TABLE_NAME`,\n `kcu`.`CONSTRAINT_NAME`,\n `kcu`.`COLUMN_NAME`,\n `kcu`.`REFERENCED_TABLE_SCHEMA`,\n `kcu`.`REFERENCED_TABLE_NAME`,\n `kcu`.`REFERENCED_COLUMN_NAME`,\n `rc`.`DELETE_RULE` `ON_DELETE`,\n `rc`.`UPDATE_RULE` `ON_UPDATE`\n FROM (".concat(kcuSubquerySql, ") `kcu`\n INNER JOIN (").concat(rcSubquerySql, ") `rc`\n ON\n `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`CONSTRAINT_SCHEMA`\n AND\n `rc`.`TABLE_NAME` = `kcu`.`TABLE_NAME`\n AND\n `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`\n ");
2225
- return [4 /*yield*/, Promise.all([
2226
- this.query(columnsSql),
2227
- this.query(primaryKeySql),
2228
- this.query(collationsSql),
2229
- this.query(indicesSql),
2230
- this.query(foreignKeysSql),
2231
- ])];
2232
- case 6:
2233
- _j = tslib_1.__read.apply(void 0, [_k.sent(), 5]), dbColumns = _j[0], dbPrimaryKeys = _j[1], dbCollations = _j[2], dbIndices = _j[3], dbForeignKeys = _j[4];
2234
- isMariaDb = this.driver.options.type === "mariadb";
2235
- return [4 /*yield*/, this.getVersion()
2236
- // create tables for loaded tables
2237
- ];
2238
- case 7:
2239
- dbVersion = _k.sent();
2240
- // create tables for loaded tables
2241
- return [2 /*return*/, Promise.all(dbTables.map(function (dbTable) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
2242
- var table, dbCollation, defaultCollation, defaultCharset, db, _a, tableForeignKeyConstraints, tableIndexConstraints;
2243
- var _this = this;
2244
- return tslib_1.__generator(this, function (_b) {
2245
- switch (_b.label) {
2246
- case 0:
2247
- table = new Table_1.Table();
2248
- dbCollation = dbCollations.find(function (coll) { return coll["SCHEMA_NAME"] === dbTable["TABLE_SCHEMA"]; });
2249
- defaultCollation = dbCollation["COLLATION"];
2250
- defaultCharset = dbCollation["CHARSET"];
2251
- db = dbTable["TABLE_SCHEMA"] === currentDatabase
2252
- ? undefined
2253
- : dbTable["TABLE_SCHEMA"];
2254
- table.database = dbTable["TABLE_SCHEMA"];
2255
- table.name = this.driver.buildTableName(dbTable["TABLE_NAME"], undefined, db);
2256
- // create columns from the loaded columns
2257
- _a = table;
2258
- return [4 /*yield*/, Promise.all(dbColumns
2259
- .filter(function (dbColumn) {
2260
- return dbColumn["TABLE_NAME"] ===
2261
- dbTable["TABLE_NAME"] &&
2262
- dbColumn["TABLE_SCHEMA"] ===
2263
- dbTable["TABLE_SCHEMA"];
2264
- })
2265
- .map(function (dbColumn) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
2266
- var columnUniqueIndices, tableMetadata, hasIgnoredIndex, isConstraintComposite, tableColumn, width, asExpressionQuery, results, length_1, colType, items;
2267
- var _this = this;
2268
- return tslib_1.__generator(this, function (_a) {
2269
- switch (_a.label) {
2270
- case 0:
2271
- columnUniqueIndices = dbIndices.filter(function (dbIndex) {
2272
- return (dbIndex["TABLE_NAME"] ===
2273
- dbTable["TABLE_NAME"] &&
2274
- dbIndex["TABLE_SCHEMA"] ===
2275
- dbTable["TABLE_SCHEMA"] &&
2276
- dbIndex["COLUMN_NAME"] ===
2277
- dbColumn["COLUMN_NAME"] &&
2278
- parseInt(dbIndex["NON_UNIQUE"], 10) ===
2279
- 0);
2280
- });
2281
- tableMetadata = this.connection.entityMetadatas.find(function (metadata) {
2282
- return _this.getTablePath(table) ===
2283
- _this.getTablePath(metadata);
2284
- });
2285
- hasIgnoredIndex = columnUniqueIndices.length > 0 &&
2286
- tableMetadata &&
2287
- tableMetadata.indices.some(function (index) {
2288
- return columnUniqueIndices.some(function (uniqueIndex) {
2289
- return (index.name ===
2290
- uniqueIndex["INDEX_NAME"] &&
2291
- index.synchronize === false);
2292
- });
2293
- });
2294
- isConstraintComposite = columnUniqueIndices.every(function (uniqueIndex) {
2295
- return dbIndices.some(function (dbIndex) {
2296
- return dbIndex["INDEX_NAME"] ===
2297
- uniqueIndex["INDEX_NAME"] &&
2298
- dbIndex["COLUMN_NAME"] !==
2299
- dbColumn["COLUMN_NAME"];
2300
- });
2301
- });
2302
- tableColumn = new TableColumn_1.TableColumn();
2303
- tableColumn.name = dbColumn["COLUMN_NAME"];
2304
- tableColumn.type =
2305
- dbColumn["DATA_TYPE"].toLowerCase();
2306
- // since mysql 8.0, "geometrycollection" returned as "geomcollection"
2307
- // typeorm still use "geometrycollection"
2308
- if (tableColumn.type === "geomcollection") {
2309
- tableColumn.type = "geometrycollection";
2310
- }
2311
- tableColumn.zerofill =
2312
- dbColumn["COLUMN_TYPE"].indexOf("zerofill") !==
2313
- -1;
2314
- tableColumn.unsigned = tableColumn.zerofill
2315
- ? true
2316
- : dbColumn["COLUMN_TYPE"].indexOf("unsigned") !== -1;
2317
- if (this.driver.withWidthColumnTypes.indexOf(tableColumn.type) !== -1) {
2318
- width = dbColumn["COLUMN_TYPE"].substring(dbColumn["COLUMN_TYPE"].indexOf("(") + 1, dbColumn["COLUMN_TYPE"].indexOf(")"));
2319
- tableColumn.width =
2320
- width &&
2321
- !this.isDefaultColumnWidth(table, tableColumn, parseInt(width))
2322
- ? parseInt(width)
2323
- : undefined;
2324
- }
2325
- if (dbColumn["COLUMN_DEFAULT"] === null ||
2326
- dbColumn["COLUMN_DEFAULT"] === undefined ||
2327
- (isMariaDb &&
2328
- dbColumn["COLUMN_DEFAULT"] === "NULL")) {
2329
- tableColumn.default = undefined;
2330
- }
2331
- else if (/^CURRENT_TIMESTAMP(\([0-9]*\))?$/i.test(dbColumn["COLUMN_DEFAULT"])) {
2332
- // New versions of MariaDB return expressions in lowercase. We need to set it in
2333
- // uppercase so the comparison in MysqlDriver#compareDefaultValues does not fail.
2334
- tableColumn.default =
2335
- dbColumn["COLUMN_DEFAULT"].toUpperCase();
2336
- }
2337
- else if (isMariaDb &&
2338
- VersionUtils_1.VersionUtils.isGreaterOrEqual(dbVersion, "10.2.7")) {
2339
- // MariaDB started adding quotes to literals in COLUMN_DEFAULT since version 10.2.7
2340
- // See https://mariadb.com/kb/en/library/information-schema-columns-table/
2341
- tableColumn.default = dbColumn["COLUMN_DEFAULT"];
2342
- }
2343
- else {
2344
- tableColumn.default = "'".concat(dbColumn["COLUMN_DEFAULT"], "'");
2345
- }
2346
- if (dbColumn["EXTRA"].indexOf("on update") !== -1) {
2347
- // New versions of MariaDB return expressions in lowercase. We need to set it in
2348
- // uppercase so the comparison in MysqlDriver#compareExtraValues does not fail.
2349
- tableColumn.onUpdate = dbColumn["EXTRA"]
2350
- .substring(dbColumn["EXTRA"].indexOf("on update") +
2351
- 10)
2352
- .toUpperCase();
2353
- }
2354
- if (!dbColumn["GENERATION_EXPRESSION"]) return [3 /*break*/, 3];
2355
- tableColumn.generatedType =
2356
- dbColumn["EXTRA"].indexOf("VIRTUAL") !== -1
2357
- ? "VIRTUAL"
2358
- : "STORED";
2359
- return [4 /*yield*/, this.selectTypeormMetadataSql({
2360
- schema: dbTable["TABLE_SCHEMA"],
2361
- table: dbTable["TABLE_NAME"],
2362
- type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
2363
- name: tableColumn.name,
2364
- })];
2365
- case 1:
2366
- asExpressionQuery = _a.sent();
2367
- return [4 /*yield*/, this.query(asExpressionQuery.query, asExpressionQuery.parameters)];
2368
- case 2:
2369
- results = _a.sent();
2370
- if (results[0] && results[0].value) {
2371
- tableColumn.asExpression = results[0].value;
2372
- }
2373
- else {
2374
- tableColumn.asExpression = "";
2375
- }
2376
- _a.label = 3;
2377
- case 3:
2378
- tableColumn.isUnique =
2379
- columnUniqueIndices.length > 0 &&
2380
- !hasIgnoredIndex &&
2381
- !isConstraintComposite;
2382
- if (isMariaDb && tableColumn.generatedType) {
2383
- // do nothing - MariaDB does not support NULL/NOT NULL expressions for generated columns
2384
- }
2385
- else {
2386
- tableColumn.isNullable =
2387
- dbColumn["IS_NULLABLE"] === "YES";
2388
- }
2389
- tableColumn.isPrimary = dbPrimaryKeys.some(function (dbPrimaryKey) {
2390
- return (dbPrimaryKey["TABLE_NAME"] ===
2391
- dbColumn["TABLE_NAME"] &&
2392
- dbPrimaryKey["TABLE_SCHEMA"] ===
2393
- dbColumn["TABLE_SCHEMA"] &&
2394
- dbPrimaryKey["COLUMN_NAME"] ===
2395
- dbColumn["COLUMN_NAME"]);
2396
- });
2397
- tableColumn.isGenerated =
2398
- dbColumn["EXTRA"].indexOf("auto_increment") !==
2399
- -1;
2400
- if (tableColumn.isGenerated)
2401
- tableColumn.generationStrategy = "increment";
2402
- tableColumn.comment =
2403
- typeof dbColumn["COLUMN_COMMENT"] ===
2404
- "string" &&
2405
- dbColumn["COLUMN_COMMENT"].length === 0
2406
- ? undefined
2407
- : dbColumn["COLUMN_COMMENT"];
2408
- if (dbColumn["CHARACTER_SET_NAME"])
2409
- tableColumn.charset =
2410
- dbColumn["CHARACTER_SET_NAME"] ===
2411
- defaultCharset
2412
- ? undefined
2413
- : dbColumn["CHARACTER_SET_NAME"];
2414
- if (dbColumn["COLLATION_NAME"])
2415
- tableColumn.collation =
2416
- dbColumn["COLLATION_NAME"] ===
2417
- defaultCollation
2418
- ? undefined
2419
- : dbColumn["COLLATION_NAME"];
2420
- // check only columns that have length property
2421
- if (this.driver.withLengthColumnTypes.indexOf(tableColumn.type) !== -1 &&
2422
- dbColumn["CHARACTER_MAXIMUM_LENGTH"]) {
2423
- length_1 = dbColumn["CHARACTER_MAXIMUM_LENGTH"].toString();
2424
- tableColumn.length =
2425
- !this.isDefaultColumnLength(table, tableColumn, length_1)
2426
- ? length_1
2427
- : "";
2428
- }
2429
- if (tableColumn.type === "decimal" ||
2430
- tableColumn.type === "double" ||
2431
- tableColumn.type === "float") {
2432
- if (dbColumn["NUMERIC_PRECISION"] !== null &&
2433
- !this.isDefaultColumnPrecision(table, tableColumn, dbColumn["NUMERIC_PRECISION"]))
2434
- tableColumn.precision = parseInt(dbColumn["NUMERIC_PRECISION"]);
2435
- if (dbColumn["NUMERIC_SCALE"] !== null &&
2436
- !this.isDefaultColumnScale(table, tableColumn, dbColumn["NUMERIC_SCALE"]))
2437
- tableColumn.scale = parseInt(dbColumn["NUMERIC_SCALE"]);
2438
- }
2439
- if (tableColumn.type === "enum" ||
2440
- tableColumn.type === "simple-enum" ||
2441
- tableColumn.type === "set") {
2442
- colType = dbColumn["COLUMN_TYPE"];
2443
- items = colType
2444
- .substring(colType.indexOf("(") + 1, colType.lastIndexOf(")"))
2445
- .split(",");
2446
- tableColumn.enum = items.map(function (item) {
2447
- return item.substring(1, item.length - 1);
2448
- });
2449
- tableColumn.length = "";
2450
- }
2451
- if ((tableColumn.type === "datetime" ||
2452
- tableColumn.type === "time" ||
2453
- tableColumn.type === "timestamp") &&
2454
- dbColumn["DATETIME_PRECISION"] !== null &&
2455
- dbColumn["DATETIME_PRECISION"] !== undefined &&
2456
- !this.isDefaultColumnPrecision(table, tableColumn, parseInt(dbColumn["DATETIME_PRECISION"]))) {
2457
- tableColumn.precision = parseInt(dbColumn["DATETIME_PRECISION"]);
2458
- }
2459
- return [2 /*return*/, tableColumn];
2460
- }
2461
- });
2462
- }); }))
2463
- // find foreign key constraints of table, group them by constraint name and build TableForeignKey.
2464
- ];
2465
- case 1:
2466
- // create columns from the loaded columns
2467
- _a.columns = _b.sent();
2468
- tableForeignKeyConstraints = OrmUtils_1.OrmUtils.uniq(dbForeignKeys.filter(function (dbForeignKey) {
2469
- return (dbForeignKey["TABLE_NAME"] ===
2470
- dbTable["TABLE_NAME"] &&
2471
- dbForeignKey["TABLE_SCHEMA"] ===
2472
- dbTable["TABLE_SCHEMA"]);
2473
- }), function (dbForeignKey) { return dbForeignKey["CONSTRAINT_NAME"]; });
2474
- table.foreignKeys = tableForeignKeyConstraints.map(function (dbForeignKey) {
2475
- var foreignKeys = dbForeignKeys.filter(function (dbFk) {
2476
- return dbFk["CONSTRAINT_NAME"] ===
2477
- dbForeignKey["CONSTRAINT_NAME"];
2478
- });
2479
- // if referenced table located in currently used db, we don't need to concat db name to table name.
2480
- var database = dbForeignKey["REFERENCED_TABLE_SCHEMA"] ===
2481
- currentDatabase
2482
- ? undefined
2483
- : dbForeignKey["REFERENCED_TABLE_SCHEMA"];
2484
- var referencedTableName = _this.driver.buildTableName(dbForeignKey["REFERENCED_TABLE_NAME"], undefined, database);
2485
- return new TableForeignKey_1.TableForeignKey({
2486
- name: dbForeignKey["CONSTRAINT_NAME"],
2487
- columnNames: foreignKeys.map(function (dbFk) { return dbFk["COLUMN_NAME"]; }),
2488
- referencedDatabase: dbForeignKey["REFERENCED_TABLE_SCHEMA"],
2489
- referencedTableName: referencedTableName,
2490
- referencedColumnNames: foreignKeys.map(function (dbFk) { return dbFk["REFERENCED_COLUMN_NAME"]; }),
2491
- onDelete: dbForeignKey["ON_DELETE"],
2492
- onUpdate: dbForeignKey["ON_UPDATE"],
2493
- });
2494
- });
2495
- tableIndexConstraints = OrmUtils_1.OrmUtils.uniq(dbIndices.filter(function (dbIndex) {
2496
- return dbIndex["TABLE_NAME"] === dbTable["TABLE_NAME"] &&
2497
- dbIndex["TABLE_SCHEMA"] === dbTable["TABLE_SCHEMA"];
2498
- }), function (dbIndex) { return dbIndex["INDEX_NAME"]; });
2499
- table.indices = tableIndexConstraints.map(function (constraint) {
2500
- var indices = dbIndices.filter(function (index) {
2501
- return (index["TABLE_SCHEMA"] ===
2502
- constraint["TABLE_SCHEMA"] &&
2503
- index["TABLE_NAME"] === constraint["TABLE_NAME"] &&
2504
- index["INDEX_NAME"] === constraint["INDEX_NAME"]);
2505
- });
2506
- var nonUnique = parseInt(constraint["NON_UNIQUE"], 10);
2507
- return new TableIndex_1.TableIndex({
2508
- table: table,
2509
- name: constraint["INDEX_NAME"],
2510
- columnNames: indices.map(function (i) { return i["COLUMN_NAME"]; }),
2511
- isUnique: nonUnique === 0,
2512
- isSpatial: constraint["INDEX_TYPE"] === "SPATIAL",
2513
- isFulltext: constraint["INDEX_TYPE"] === "FULLTEXT",
2514
- });
2515
- });
2516
- return [2 /*return*/, table];
2517
- }
2518
- });
2519
- }); }))];
1359
+ async loadTables(tableNames) {
1360
+ if (tableNames && tableNames.length === 0) {
1361
+ return [];
1362
+ }
1363
+ const currentDatabase = await this.getCurrentDatabase();
1364
+ // The following SQL brought to you by:
1365
+ // A terrible understanding of https://dev.mysql.com/doc/refman/8.0/en/information-schema-optimization.html
1366
+ //
1367
+ // Short Version:
1368
+ // INFORMATION_SCHEMA is a weird metadata virtual table and follows VERY FEW of the normal
1369
+ // query optimization rules. Depending on the columns you query against & the columns you're SELECTing
1370
+ // there can be a drastically different query performance - this is because the tables map to
1371
+ // data on the disk and some pieces of data require a scan of the data directory, the database files, etc
1372
+ // With most of these, you'll want to do an `EXPLAIN` when making changes to make sure
1373
+ // the changes you're making aren't changing the query performance profile negatively
1374
+ // When you do the explain you'll want to look at the `Extra` field -
1375
+ // It will look something like: "Using where; {FILE_OPENING}; Scanned {DB_NUM} databases"
1376
+ // FILE_OPENING will commonly be OPEN_FRM_ONLY or OPEN_FULL_TABLE - you want to aim to NOT do
1377
+ // an OPEN_FULL_TABLE unless necessary. DB_NUM may be a number or "all" - you really want to
1378
+ // keep this to 0 or 1. Ideally 0. "All" means you've scanned all databases - not good.
1379
+ //
1380
+ // For more info, see the above link to the MySQL docs.
1381
+ //
1382
+ // Something not noted in the docs is that complex `WHERE` clauses - such as `OR` expressions -
1383
+ // will cause the query to not hit the optimizations & do full scans. This is why
1384
+ // a number of queries below do `UNION`s of single `WHERE` clauses.
1385
+ const dbTables = [];
1386
+ if (!tableNames) {
1387
+ // Since we don't have any of this data we have to do a scan
1388
+ const tablesSql = `SELECT \`TABLE_SCHEMA\`, \`TABLE_NAME\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\``;
1389
+ dbTables.push(...(await this.query(tablesSql)));
1390
+ }
1391
+ else {
1392
+ // Avoid data directory scan: TABLE_SCHEMA
1393
+ // Avoid database directory scan: TABLE_NAME
1394
+ // We only use `TABLE_SCHEMA` and `TABLE_NAME` which is `SKIP_OPEN_TABLE`
1395
+ const tablesSql = tableNames
1396
+ .filter((tableName) => tableName)
1397
+ .map((tableName) => {
1398
+ let { database, tableName: name } = this.driver.parseTableName(tableName);
1399
+ if (!database) {
1400
+ database = currentDatabase;
2520
1401
  }
2521
- });
2522
- });
2523
- };
1402
+ return `SELECT \`TABLE_SCHEMA\`, \`TABLE_NAME\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE \`TABLE_SCHEMA\` = '${database}' AND \`TABLE_NAME\` = '${name}'`;
1403
+ })
1404
+ .join(" UNION ");
1405
+ dbTables.push(...(await this.query(tablesSql)));
1406
+ }
1407
+ // if tables were not found in the db, no need to proceed
1408
+ if (!dbTables.length)
1409
+ return [];
1410
+ // Avoid data directory scan: TABLE_SCHEMA
1411
+ // Avoid database directory scan: TABLE_NAME
1412
+ // Full columns: CARDINALITY & INDEX_TYPE - everything else is FRM only
1413
+ const statsSubquerySql = dbTables
1414
+ .map(({ TABLE_SCHEMA, TABLE_NAME }) => {
1415
+ return `
1416
+ SELECT
1417
+ *
1418
+ FROM \`INFORMATION_SCHEMA\`.\`STATISTICS\`
1419
+ WHERE
1420
+ \`TABLE_SCHEMA\` = '${TABLE_SCHEMA}'
1421
+ AND
1422
+ \`TABLE_NAME\` = '${TABLE_NAME}'
1423
+ `;
1424
+ })
1425
+ .join(" UNION ");
1426
+ // Avoid data directory scan: TABLE_SCHEMA
1427
+ // Avoid database directory scan: TABLE_NAME
1428
+ // All columns will hit the full table.
1429
+ const kcuSubquerySql = dbTables
1430
+ .map(({ TABLE_SCHEMA, TABLE_NAME }) => {
1431
+ return `
1432
+ SELECT
1433
+ *
1434
+ FROM \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` \`kcu\`
1435
+ WHERE
1436
+ \`kcu\`.\`TABLE_SCHEMA\` = '${TABLE_SCHEMA}'
1437
+ AND
1438
+ \`kcu\`.\`TABLE_NAME\` = '${TABLE_NAME}'
1439
+ `;
1440
+ })
1441
+ .join(" UNION ");
1442
+ // Avoid data directory scan: CONSTRAINT_SCHEMA
1443
+ // Avoid database directory scan: TABLE_NAME
1444
+ // All columns will hit the full table.
1445
+ const rcSubquerySql = dbTables
1446
+ .map(({ TABLE_SCHEMA, TABLE_NAME }) => {
1447
+ return `
1448
+ SELECT
1449
+ *
1450
+ FROM \`INFORMATION_SCHEMA\`.\`REFERENTIAL_CONSTRAINTS\`
1451
+ WHERE
1452
+ \`CONSTRAINT_SCHEMA\` = '${TABLE_SCHEMA}'
1453
+ AND
1454
+ \`TABLE_NAME\` = '${TABLE_NAME}'
1455
+ `;
1456
+ })
1457
+ .join(" UNION ");
1458
+ // Avoid data directory scan: TABLE_SCHEMA
1459
+ // Avoid database directory scan: TABLE_NAME
1460
+ // OPEN_FRM_ONLY applies to all columns
1461
+ const columnsSql = dbTables
1462
+ .map(({ TABLE_SCHEMA, TABLE_NAME }) => {
1463
+ return `
1464
+ SELECT
1465
+ *
1466
+ FROM
1467
+ \`INFORMATION_SCHEMA\`.\`COLUMNS\`
1468
+ WHERE
1469
+ \`TABLE_SCHEMA\` = '${TABLE_SCHEMA}'
1470
+ AND
1471
+ \`TABLE_NAME\` = '${TABLE_NAME}'
1472
+ `;
1473
+ })
1474
+ .join(" UNION ");
1475
+ // No Optimizations are available for COLLATIONS
1476
+ const collationsSql = `
1477
+ SELECT
1478
+ \`SCHEMA_NAME\`,
1479
+ \`DEFAULT_CHARACTER_SET_NAME\` as \`CHARSET\`,
1480
+ \`DEFAULT_COLLATION_NAME\` AS \`COLLATION\`
1481
+ FROM \`INFORMATION_SCHEMA\`.\`SCHEMATA\`
1482
+ `;
1483
+ // Key Column Usage but only for PKs
1484
+ const primaryKeySql = `SELECT * FROM (${kcuSubquerySql}) \`kcu\` WHERE \`CONSTRAINT_NAME\` = 'PRIMARY'`;
1485
+ // Combine stats & referential constraints
1486
+ const indicesSql = `
1487
+ SELECT
1488
+ \`s\`.*
1489
+ FROM (${statsSubquerySql}) \`s\`
1490
+ LEFT JOIN (${rcSubquerySql}) \`rc\`
1491
+ ON
1492
+ \`s\`.\`INDEX_NAME\` = \`rc\`.\`CONSTRAINT_NAME\`
1493
+ AND
1494
+ \`s\`.\`TABLE_SCHEMA\` = \`rc\`.\`CONSTRAINT_SCHEMA\`
1495
+ WHERE
1496
+ \`s\`.\`INDEX_NAME\` != 'PRIMARY'
1497
+ AND
1498
+ \`rc\`.\`CONSTRAINT_NAME\` IS NULL
1499
+ `;
1500
+ // Combine Key Column Usage & Referential Constraints
1501
+ const foreignKeysSql = `
1502
+ SELECT
1503
+ \`kcu\`.\`TABLE_SCHEMA\`,
1504
+ \`kcu\`.\`TABLE_NAME\`,
1505
+ \`kcu\`.\`CONSTRAINT_NAME\`,
1506
+ \`kcu\`.\`COLUMN_NAME\`,
1507
+ \`kcu\`.\`REFERENCED_TABLE_SCHEMA\`,
1508
+ \`kcu\`.\`REFERENCED_TABLE_NAME\`,
1509
+ \`kcu\`.\`REFERENCED_COLUMN_NAME\`,
1510
+ \`rc\`.\`DELETE_RULE\` \`ON_DELETE\`,
1511
+ \`rc\`.\`UPDATE_RULE\` \`ON_UPDATE\`
1512
+ FROM (${kcuSubquerySql}) \`kcu\`
1513
+ INNER JOIN (${rcSubquerySql}) \`rc\`
1514
+ ON
1515
+ \`rc\`.\`CONSTRAINT_SCHEMA\` = \`kcu\`.\`CONSTRAINT_SCHEMA\`
1516
+ AND
1517
+ \`rc\`.\`TABLE_NAME\` = \`kcu\`.\`TABLE_NAME\`
1518
+ AND
1519
+ \`rc\`.\`CONSTRAINT_NAME\` = \`kcu\`.\`CONSTRAINT_NAME\`
1520
+ `;
1521
+ const [dbColumns, dbPrimaryKeys, dbCollations, dbIndices, dbForeignKeys,] = await Promise.all([
1522
+ this.query(columnsSql),
1523
+ this.query(primaryKeySql),
1524
+ this.query(collationsSql),
1525
+ this.query(indicesSql),
1526
+ this.query(foreignKeysSql),
1527
+ ]);
1528
+ const isMariaDb = this.driver.options.type === "mariadb";
1529
+ const dbVersion = await this.getVersion();
1530
+ // create tables for loaded tables
1531
+ return Promise.all(dbTables.map(async (dbTable) => {
1532
+ const table = new Table_1.Table();
1533
+ const dbCollation = dbCollations.find((coll) => coll["SCHEMA_NAME"] === dbTable["TABLE_SCHEMA"]);
1534
+ const defaultCollation = dbCollation["COLLATION"];
1535
+ const defaultCharset = dbCollation["CHARSET"];
1536
+ // We do not need to join database name, when database is by default.
1537
+ const db = dbTable["TABLE_SCHEMA"] === currentDatabase
1538
+ ? undefined
1539
+ : dbTable["TABLE_SCHEMA"];
1540
+ table.database = dbTable["TABLE_SCHEMA"];
1541
+ table.name = this.driver.buildTableName(dbTable["TABLE_NAME"], undefined, db);
1542
+ // create columns from the loaded columns
1543
+ table.columns = await Promise.all(dbColumns
1544
+ .filter((dbColumn) => dbColumn["TABLE_NAME"] ===
1545
+ dbTable["TABLE_NAME"] &&
1546
+ dbColumn["TABLE_SCHEMA"] ===
1547
+ dbTable["TABLE_SCHEMA"])
1548
+ .map(async (dbColumn) => {
1549
+ const columnUniqueIndices = dbIndices.filter((dbIndex) => {
1550
+ return (dbIndex["TABLE_NAME"] ===
1551
+ dbTable["TABLE_NAME"] &&
1552
+ dbIndex["TABLE_SCHEMA"] ===
1553
+ dbTable["TABLE_SCHEMA"] &&
1554
+ dbIndex["COLUMN_NAME"] ===
1555
+ dbColumn["COLUMN_NAME"] &&
1556
+ parseInt(dbIndex["NON_UNIQUE"], 10) ===
1557
+ 0);
1558
+ });
1559
+ const tableMetadata = this.connection.entityMetadatas.find((metadata) => this.getTablePath(table) ===
1560
+ this.getTablePath(metadata));
1561
+ const hasIgnoredIndex = columnUniqueIndices.length > 0 &&
1562
+ tableMetadata &&
1563
+ tableMetadata.indices.some((index) => {
1564
+ return columnUniqueIndices.some((uniqueIndex) => {
1565
+ return (index.name ===
1566
+ uniqueIndex["INDEX_NAME"] &&
1567
+ index.synchronize === false);
1568
+ });
1569
+ });
1570
+ const isConstraintComposite = columnUniqueIndices.every((uniqueIndex) => {
1571
+ return dbIndices.some((dbIndex) => dbIndex["INDEX_NAME"] ===
1572
+ uniqueIndex["INDEX_NAME"] &&
1573
+ dbIndex["COLUMN_NAME"] !==
1574
+ dbColumn["COLUMN_NAME"]);
1575
+ });
1576
+ const tableColumn = new TableColumn_1.TableColumn();
1577
+ tableColumn.name = dbColumn["COLUMN_NAME"];
1578
+ tableColumn.type =
1579
+ dbColumn["DATA_TYPE"].toLowerCase();
1580
+ // since mysql 8.0, "geometrycollection" returned as "geomcollection"
1581
+ // typeorm still use "geometrycollection"
1582
+ if (tableColumn.type === "geomcollection") {
1583
+ tableColumn.type = "geometrycollection";
1584
+ }
1585
+ tableColumn.zerofill =
1586
+ dbColumn["COLUMN_TYPE"].indexOf("zerofill") !==
1587
+ -1;
1588
+ tableColumn.unsigned = tableColumn.zerofill
1589
+ ? true
1590
+ : dbColumn["COLUMN_TYPE"].indexOf("unsigned") !== -1;
1591
+ if (this.driver.withWidthColumnTypes.indexOf(tableColumn.type) !== -1) {
1592
+ const width = dbColumn["COLUMN_TYPE"].substring(dbColumn["COLUMN_TYPE"].indexOf("(") + 1, dbColumn["COLUMN_TYPE"].indexOf(")"));
1593
+ tableColumn.width =
1594
+ width &&
1595
+ !this.isDefaultColumnWidth(table, tableColumn, parseInt(width))
1596
+ ? parseInt(width)
1597
+ : undefined;
1598
+ }
1599
+ if (dbColumn["COLUMN_DEFAULT"] === null ||
1600
+ dbColumn["COLUMN_DEFAULT"] === undefined ||
1601
+ (isMariaDb &&
1602
+ dbColumn["COLUMN_DEFAULT"] === "NULL")) {
1603
+ tableColumn.default = undefined;
1604
+ }
1605
+ else if (/^CURRENT_TIMESTAMP(\([0-9]*\))?$/i.test(dbColumn["COLUMN_DEFAULT"])) {
1606
+ // New versions of MariaDB return expressions in lowercase. We need to set it in
1607
+ // uppercase so the comparison in MysqlDriver#compareDefaultValues does not fail.
1608
+ tableColumn.default =
1609
+ dbColumn["COLUMN_DEFAULT"].toUpperCase();
1610
+ }
1611
+ else if (isMariaDb &&
1612
+ VersionUtils_1.VersionUtils.isGreaterOrEqual(dbVersion, "10.2.7")) {
1613
+ // MariaDB started adding quotes to literals in COLUMN_DEFAULT since version 10.2.7
1614
+ // See https://mariadb.com/kb/en/library/information-schema-columns-table/
1615
+ tableColumn.default = dbColumn["COLUMN_DEFAULT"];
1616
+ }
1617
+ else {
1618
+ tableColumn.default = `'${dbColumn["COLUMN_DEFAULT"]}'`;
1619
+ }
1620
+ if (dbColumn["EXTRA"].indexOf("on update") !== -1) {
1621
+ // New versions of MariaDB return expressions in lowercase. We need to set it in
1622
+ // uppercase so the comparison in MysqlDriver#compareExtraValues does not fail.
1623
+ tableColumn.onUpdate = dbColumn["EXTRA"]
1624
+ .substring(dbColumn["EXTRA"].indexOf("on update") +
1625
+ 10)
1626
+ .toUpperCase();
1627
+ }
1628
+ if (dbColumn["GENERATION_EXPRESSION"]) {
1629
+ tableColumn.generatedType =
1630
+ dbColumn["EXTRA"].indexOf("VIRTUAL") !== -1
1631
+ ? "VIRTUAL"
1632
+ : "STORED";
1633
+ // We cannot relay on information_schema.columns.generation_expression, because it is formatted different.
1634
+ const asExpressionQuery = await this.selectTypeormMetadataSql({
1635
+ schema: dbTable["TABLE_SCHEMA"],
1636
+ table: dbTable["TABLE_NAME"],
1637
+ type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
1638
+ name: tableColumn.name,
1639
+ });
1640
+ const results = await this.query(asExpressionQuery.query, asExpressionQuery.parameters);
1641
+ if (results[0] && results[0].value) {
1642
+ tableColumn.asExpression = results[0].value;
1643
+ }
1644
+ else {
1645
+ tableColumn.asExpression = "";
1646
+ }
1647
+ }
1648
+ tableColumn.isUnique =
1649
+ columnUniqueIndices.length > 0 &&
1650
+ !hasIgnoredIndex &&
1651
+ !isConstraintComposite;
1652
+ if (isMariaDb && tableColumn.generatedType) {
1653
+ // do nothing - MariaDB does not support NULL/NOT NULL expressions for generated columns
1654
+ }
1655
+ else {
1656
+ tableColumn.isNullable =
1657
+ dbColumn["IS_NULLABLE"] === "YES";
1658
+ }
1659
+ tableColumn.isPrimary = dbPrimaryKeys.some((dbPrimaryKey) => {
1660
+ return (dbPrimaryKey["TABLE_NAME"] ===
1661
+ dbColumn["TABLE_NAME"] &&
1662
+ dbPrimaryKey["TABLE_SCHEMA"] ===
1663
+ dbColumn["TABLE_SCHEMA"] &&
1664
+ dbPrimaryKey["COLUMN_NAME"] ===
1665
+ dbColumn["COLUMN_NAME"]);
1666
+ });
1667
+ tableColumn.isGenerated =
1668
+ dbColumn["EXTRA"].indexOf("auto_increment") !==
1669
+ -1;
1670
+ if (tableColumn.isGenerated)
1671
+ tableColumn.generationStrategy = "increment";
1672
+ tableColumn.comment =
1673
+ typeof dbColumn["COLUMN_COMMENT"] ===
1674
+ "string" &&
1675
+ dbColumn["COLUMN_COMMENT"].length === 0
1676
+ ? undefined
1677
+ : dbColumn["COLUMN_COMMENT"];
1678
+ if (dbColumn["CHARACTER_SET_NAME"])
1679
+ tableColumn.charset =
1680
+ dbColumn["CHARACTER_SET_NAME"] ===
1681
+ defaultCharset
1682
+ ? undefined
1683
+ : dbColumn["CHARACTER_SET_NAME"];
1684
+ if (dbColumn["COLLATION_NAME"])
1685
+ tableColumn.collation =
1686
+ dbColumn["COLLATION_NAME"] ===
1687
+ defaultCollation
1688
+ ? undefined
1689
+ : dbColumn["COLLATION_NAME"];
1690
+ // check only columns that have length property
1691
+ if (this.driver.withLengthColumnTypes.indexOf(tableColumn.type) !== -1 &&
1692
+ dbColumn["CHARACTER_MAXIMUM_LENGTH"]) {
1693
+ const length = dbColumn["CHARACTER_MAXIMUM_LENGTH"].toString();
1694
+ tableColumn.length =
1695
+ !this.isDefaultColumnLength(table, tableColumn, length)
1696
+ ? length
1697
+ : "";
1698
+ }
1699
+ if (tableColumn.type === "decimal" ||
1700
+ tableColumn.type === "double" ||
1701
+ tableColumn.type === "float") {
1702
+ if (dbColumn["NUMERIC_PRECISION"] !== null &&
1703
+ !this.isDefaultColumnPrecision(table, tableColumn, dbColumn["NUMERIC_PRECISION"]))
1704
+ tableColumn.precision = parseInt(dbColumn["NUMERIC_PRECISION"]);
1705
+ if (dbColumn["NUMERIC_SCALE"] !== null &&
1706
+ !this.isDefaultColumnScale(table, tableColumn, dbColumn["NUMERIC_SCALE"]))
1707
+ tableColumn.scale = parseInt(dbColumn["NUMERIC_SCALE"]);
1708
+ }
1709
+ if (tableColumn.type === "enum" ||
1710
+ tableColumn.type === "simple-enum" ||
1711
+ tableColumn.type === "set") {
1712
+ const colType = dbColumn["COLUMN_TYPE"];
1713
+ const items = colType
1714
+ .substring(colType.indexOf("(") + 1, colType.lastIndexOf(")"))
1715
+ .split(",");
1716
+ tableColumn.enum = items.map((item) => {
1717
+ return item.substring(1, item.length - 1);
1718
+ });
1719
+ tableColumn.length = "";
1720
+ }
1721
+ if ((tableColumn.type === "datetime" ||
1722
+ tableColumn.type === "time" ||
1723
+ tableColumn.type === "timestamp") &&
1724
+ dbColumn["DATETIME_PRECISION"] !== null &&
1725
+ dbColumn["DATETIME_PRECISION"] !== undefined &&
1726
+ !this.isDefaultColumnPrecision(table, tableColumn, parseInt(dbColumn["DATETIME_PRECISION"]))) {
1727
+ tableColumn.precision = parseInt(dbColumn["DATETIME_PRECISION"]);
1728
+ }
1729
+ return tableColumn;
1730
+ }));
1731
+ // find foreign key constraints of table, group them by constraint name and build TableForeignKey.
1732
+ const tableForeignKeyConstraints = OrmUtils_1.OrmUtils.uniq(dbForeignKeys.filter((dbForeignKey) => {
1733
+ return (dbForeignKey["TABLE_NAME"] ===
1734
+ dbTable["TABLE_NAME"] &&
1735
+ dbForeignKey["TABLE_SCHEMA"] ===
1736
+ dbTable["TABLE_SCHEMA"]);
1737
+ }), (dbForeignKey) => dbForeignKey["CONSTRAINT_NAME"]);
1738
+ table.foreignKeys = tableForeignKeyConstraints.map((dbForeignKey) => {
1739
+ const foreignKeys = dbForeignKeys.filter((dbFk) => dbFk["CONSTRAINT_NAME"] ===
1740
+ dbForeignKey["CONSTRAINT_NAME"]);
1741
+ // if referenced table located in currently used db, we don't need to concat db name to table name.
1742
+ const database = dbForeignKey["REFERENCED_TABLE_SCHEMA"] ===
1743
+ currentDatabase
1744
+ ? undefined
1745
+ : dbForeignKey["REFERENCED_TABLE_SCHEMA"];
1746
+ const referencedTableName = this.driver.buildTableName(dbForeignKey["REFERENCED_TABLE_NAME"], undefined, database);
1747
+ return new TableForeignKey_1.TableForeignKey({
1748
+ name: dbForeignKey["CONSTRAINT_NAME"],
1749
+ columnNames: foreignKeys.map((dbFk) => dbFk["COLUMN_NAME"]),
1750
+ referencedDatabase: dbForeignKey["REFERENCED_TABLE_SCHEMA"],
1751
+ referencedTableName: referencedTableName,
1752
+ referencedColumnNames: foreignKeys.map((dbFk) => dbFk["REFERENCED_COLUMN_NAME"]),
1753
+ onDelete: dbForeignKey["ON_DELETE"],
1754
+ onUpdate: dbForeignKey["ON_UPDATE"],
1755
+ });
1756
+ });
1757
+ // find index constraints of table, group them by constraint name and build TableIndex.
1758
+ const tableIndexConstraints = OrmUtils_1.OrmUtils.uniq(dbIndices.filter((dbIndex) => dbIndex["TABLE_NAME"] === dbTable["TABLE_NAME"] &&
1759
+ dbIndex["TABLE_SCHEMA"] === dbTable["TABLE_SCHEMA"]), (dbIndex) => dbIndex["INDEX_NAME"]);
1760
+ table.indices = tableIndexConstraints.map((constraint) => {
1761
+ const indices = dbIndices.filter((index) => {
1762
+ return (index["TABLE_SCHEMA"] ===
1763
+ constraint["TABLE_SCHEMA"] &&
1764
+ index["TABLE_NAME"] === constraint["TABLE_NAME"] &&
1765
+ index["INDEX_NAME"] === constraint["INDEX_NAME"]);
1766
+ });
1767
+ const nonUnique = parseInt(constraint["NON_UNIQUE"], 10);
1768
+ return new TableIndex_1.TableIndex({
1769
+ table: table,
1770
+ name: constraint["INDEX_NAME"],
1771
+ columnNames: indices.map((i) => i["COLUMN_NAME"]),
1772
+ isUnique: nonUnique === 0,
1773
+ isSpatial: constraint["INDEX_TYPE"] === "SPATIAL",
1774
+ isFulltext: constraint["INDEX_TYPE"] === "FULLTEXT",
1775
+ });
1776
+ });
1777
+ return table;
1778
+ }));
1779
+ }
2524
1780
  /**
2525
1781
  * Builds create table sql
2526
1782
  */
2527
- MysqlQueryRunner.prototype.createTableSql = function (table, createForeignKeys) {
2528
- var _this = this;
2529
- var columnDefinitions = table.columns
2530
- .map(function (column) { return _this.buildCreateColumnSql(column, true); })
1783
+ createTableSql(table, createForeignKeys) {
1784
+ const columnDefinitions = table.columns
1785
+ .map((column) => this.buildCreateColumnSql(column, true))
2531
1786
  .join(", ");
2532
- var sql = "CREATE TABLE ".concat(this.escapePath(table), " (").concat(columnDefinitions);
1787
+ let sql = `CREATE TABLE ${this.escapePath(table)} (${columnDefinitions}`;
2533
1788
  // we create unique indexes instead of unique constraints, because MySql does not have unique constraints.
2534
1789
  // if we mark column as Unique, it means that we create UNIQUE INDEX.
2535
1790
  table.columns
2536
- .filter(function (column) { return column.isUnique; })
2537
- .forEach(function (column) {
2538
- var isUniqueIndexExist = table.indices.some(function (index) {
1791
+ .filter((column) => column.isUnique)
1792
+ .forEach((column) => {
1793
+ const isUniqueIndexExist = table.indices.some((index) => {
2539
1794
  return (index.columnNames.length === 1 &&
2540
1795
  !!index.isUnique &&
2541
1796
  index.columnNames.indexOf(column.name) !== -1);
2542
1797
  });
2543
- var isUniqueConstraintExist = table.uniques.some(function (unique) {
1798
+ const isUniqueConstraintExist = table.uniques.some((unique) => {
2544
1799
  return (unique.columnNames.length === 1 &&
2545
1800
  unique.columnNames.indexOf(column.name) !== -1);
2546
1801
  });
2547
1802
  if (!isUniqueIndexExist && !isUniqueConstraintExist)
2548
1803
  table.indices.push(new TableIndex_1.TableIndex({
2549
- name: _this.connection.namingStrategy.uniqueConstraintName(table, [column.name]),
1804
+ name: this.connection.namingStrategy.uniqueConstraintName(table, [column.name]),
2550
1805
  columnNames: [column.name],
2551
1806
  isUnique: true,
2552
1807
  }));
2553
1808
  });
2554
1809
  // as MySql does not have unique constraints, we must create table indices from table uniques and mark them as unique.
2555
1810
  if (table.uniques.length > 0) {
2556
- table.uniques.forEach(function (unique) {
2557
- var uniqueExist = table.indices.some(function (index) { return index.name === unique.name; });
1811
+ table.uniques.forEach((unique) => {
1812
+ const uniqueExist = table.indices.some((index) => index.name === unique.name);
2558
1813
  if (!uniqueExist) {
2559
1814
  table.indices.push(new TableIndex_1.TableIndex({
2560
1815
  name: unique.name,
@@ -2565,235 +1820,216 @@ var MysqlQueryRunner = /** @class */ (function (_super) {
2565
1820
  });
2566
1821
  }
2567
1822
  if (table.indices.length > 0) {
2568
- var indicesSql = table.indices
2569
- .map(function (index) {
2570
- var columnNames = index.columnNames
2571
- .map(function (columnName) { return "`".concat(columnName, "`"); })
1823
+ const indicesSql = table.indices
1824
+ .map((index) => {
1825
+ const columnNames = index.columnNames
1826
+ .map((columnName) => `\`${columnName}\``)
2572
1827
  .join(", ");
2573
1828
  if (!index.name)
2574
- index.name = _this.connection.namingStrategy.indexName(table, index.columnNames, index.where);
2575
- var indexType = "";
1829
+ index.name = this.connection.namingStrategy.indexName(table, index.columnNames, index.where);
1830
+ let indexType = "";
2576
1831
  if (index.isUnique)
2577
1832
  indexType += "UNIQUE ";
2578
1833
  if (index.isSpatial)
2579
1834
  indexType += "SPATIAL ";
2580
1835
  if (index.isFulltext)
2581
1836
  indexType += "FULLTEXT ";
2582
- var indexParser = index.isFulltext && index.parser
2583
- ? " WITH PARSER ".concat(index.parser)
1837
+ const indexParser = index.isFulltext && index.parser
1838
+ ? ` WITH PARSER ${index.parser}`
2584
1839
  : "";
2585
- return "".concat(indexType, "INDEX `").concat(index.name, "` (").concat(columnNames, ")").concat(indexParser);
1840
+ return `${indexType}INDEX \`${index.name}\` (${columnNames})${indexParser}`;
2586
1841
  })
2587
1842
  .join(", ");
2588
- sql += ", ".concat(indicesSql);
1843
+ sql += `, ${indicesSql}`;
2589
1844
  }
2590
1845
  if (table.foreignKeys.length > 0 && createForeignKeys) {
2591
- var foreignKeysSql = table.foreignKeys
2592
- .map(function (fk) {
2593
- var columnNames = fk.columnNames
2594
- .map(function (columnName) { return "`".concat(columnName, "`"); })
1846
+ const foreignKeysSql = table.foreignKeys
1847
+ .map((fk) => {
1848
+ const columnNames = fk.columnNames
1849
+ .map((columnName) => `\`${columnName}\``)
2595
1850
  .join(", ");
2596
1851
  if (!fk.name)
2597
- fk.name = _this.connection.namingStrategy.foreignKeyName(table, fk.columnNames, _this.getTablePath(fk), fk.referencedColumnNames);
2598
- var referencedColumnNames = fk.referencedColumnNames
2599
- .map(function (columnName) { return "`".concat(columnName, "`"); })
1852
+ fk.name = this.connection.namingStrategy.foreignKeyName(table, fk.columnNames, this.getTablePath(fk), fk.referencedColumnNames);
1853
+ const referencedColumnNames = fk.referencedColumnNames
1854
+ .map((columnName) => `\`${columnName}\``)
2600
1855
  .join(", ");
2601
- var constraint = "CONSTRAINT `".concat(fk.name, "` FOREIGN KEY (").concat(columnNames, ") REFERENCES ").concat(_this.escapePath(_this.getTablePath(fk)), " (").concat(referencedColumnNames, ")");
1856
+ let constraint = `CONSTRAINT \`${fk.name}\` FOREIGN KEY (${columnNames}) REFERENCES ${this.escapePath(this.getTablePath(fk))} (${referencedColumnNames})`;
2602
1857
  if (fk.onDelete)
2603
- constraint += " ON DELETE ".concat(fk.onDelete);
1858
+ constraint += ` ON DELETE ${fk.onDelete}`;
2604
1859
  if (fk.onUpdate)
2605
- constraint += " ON UPDATE ".concat(fk.onUpdate);
1860
+ constraint += ` ON UPDATE ${fk.onUpdate}`;
2606
1861
  return constraint;
2607
1862
  })
2608
1863
  .join(", ");
2609
- sql += ", ".concat(foreignKeysSql);
1864
+ sql += `, ${foreignKeysSql}`;
2610
1865
  }
2611
1866
  if (table.primaryColumns.length > 0) {
2612
- var columnNames = table.primaryColumns
2613
- .map(function (column) { return "`".concat(column.name, "`"); })
1867
+ const columnNames = table.primaryColumns
1868
+ .map((column) => `\`${column.name}\``)
2614
1869
  .join(", ");
2615
- sql += ", PRIMARY KEY (".concat(columnNames, ")");
1870
+ sql += `, PRIMARY KEY (${columnNames})`;
2616
1871
  }
2617
- sql += ") ENGINE=".concat(table.engine || "InnoDB");
1872
+ sql += `) ENGINE=${table.engine || "InnoDB"}`;
2618
1873
  return new Query_1.Query(sql);
2619
- };
1874
+ }
2620
1875
  /**
2621
1876
  * Builds drop table sql
2622
1877
  */
2623
- MysqlQueryRunner.prototype.dropTableSql = function (tableOrName) {
2624
- return new Query_1.Query("DROP TABLE ".concat(this.escapePath(tableOrName)));
2625
- };
2626
- MysqlQueryRunner.prototype.createViewSql = function (view) {
1878
+ dropTableSql(tableOrName) {
1879
+ return new Query_1.Query(`DROP TABLE ${this.escapePath(tableOrName)}`);
1880
+ }
1881
+ createViewSql(view) {
2627
1882
  if (typeof view.expression === "string") {
2628
- return new Query_1.Query("CREATE VIEW ".concat(this.escapePath(view), " AS ").concat(view.expression));
1883
+ return new Query_1.Query(`CREATE VIEW ${this.escapePath(view)} AS ${view.expression}`);
2629
1884
  }
2630
1885
  else {
2631
- return new Query_1.Query("CREATE VIEW ".concat(this.escapePath(view), " AS ").concat(view
1886
+ return new Query_1.Query(`CREATE VIEW ${this.escapePath(view)} AS ${view
2632
1887
  .expression(this.connection)
2633
- .getQuery()));
1888
+ .getQuery()}`);
2634
1889
  }
2635
- };
2636
- MysqlQueryRunner.prototype.insertViewDefinitionSql = function (view) {
2637
- return tslib_1.__awaiter(this, void 0, void 0, function () {
2638
- var currentDatabase, expression;
2639
- return tslib_1.__generator(this, function (_a) {
2640
- switch (_a.label) {
2641
- case 0: return [4 /*yield*/, this.getCurrentDatabase()];
2642
- case 1:
2643
- currentDatabase = _a.sent();
2644
- expression = typeof view.expression === "string"
2645
- ? view.expression.trim()
2646
- : view.expression(this.connection).getQuery();
2647
- return [2 /*return*/, this.insertTypeormMetadataSql({
2648
- type: MetadataTableType_1.MetadataTableType.VIEW,
2649
- schema: currentDatabase,
2650
- name: view.name,
2651
- value: expression,
2652
- })];
2653
- }
2654
- });
1890
+ }
1891
+ async insertViewDefinitionSql(view) {
1892
+ const currentDatabase = await this.getCurrentDatabase();
1893
+ const expression = typeof view.expression === "string"
1894
+ ? view.expression.trim()
1895
+ : view.expression(this.connection).getQuery();
1896
+ return this.insertTypeormMetadataSql({
1897
+ type: MetadataTableType_1.MetadataTableType.VIEW,
1898
+ schema: currentDatabase,
1899
+ name: view.name,
1900
+ value: expression,
2655
1901
  });
2656
- };
1902
+ }
2657
1903
  /**
2658
1904
  * Builds drop view sql.
2659
1905
  */
2660
- MysqlQueryRunner.prototype.dropViewSql = function (viewOrPath) {
2661
- return new Query_1.Query("DROP VIEW ".concat(this.escapePath(viewOrPath)));
2662
- };
1906
+ dropViewSql(viewOrPath) {
1907
+ return new Query_1.Query(`DROP VIEW ${this.escapePath(viewOrPath)}`);
1908
+ }
2663
1909
  /**
2664
1910
  * Builds remove view sql.
2665
1911
  */
2666
- MysqlQueryRunner.prototype.deleteViewDefinitionSql = function (viewOrPath) {
2667
- return tslib_1.__awaiter(this, void 0, void 0, function () {
2668
- var currentDatabase, viewName;
2669
- return tslib_1.__generator(this, function (_a) {
2670
- switch (_a.label) {
2671
- case 0: return [4 /*yield*/, this.getCurrentDatabase()];
2672
- case 1:
2673
- currentDatabase = _a.sent();
2674
- viewName = InstanceChecker_1.InstanceChecker.isView(viewOrPath)
2675
- ? viewOrPath.name
2676
- : viewOrPath;
2677
- return [2 /*return*/, this.deleteTypeormMetadataSql({
2678
- type: MetadataTableType_1.MetadataTableType.VIEW,
2679
- schema: currentDatabase,
2680
- name: viewName,
2681
- })];
2682
- }
2683
- });
1912
+ async deleteViewDefinitionSql(viewOrPath) {
1913
+ const currentDatabase = await this.getCurrentDatabase();
1914
+ const viewName = InstanceChecker_1.InstanceChecker.isView(viewOrPath)
1915
+ ? viewOrPath.name
1916
+ : viewOrPath;
1917
+ return this.deleteTypeormMetadataSql({
1918
+ type: MetadataTableType_1.MetadataTableType.VIEW,
1919
+ schema: currentDatabase,
1920
+ name: viewName,
2684
1921
  });
2685
- };
1922
+ }
2686
1923
  /**
2687
1924
  * Builds create index sql.
2688
1925
  */
2689
- MysqlQueryRunner.prototype.createIndexSql = function (table, index) {
2690
- var columns = index.columnNames
2691
- .map(function (columnName) { return "`".concat(columnName, "`"); })
1926
+ createIndexSql(table, index) {
1927
+ const columns = index.columnNames
1928
+ .map((columnName) => `\`${columnName}\``)
2692
1929
  .join(", ");
2693
- var indexType = "";
1930
+ let indexType = "";
2694
1931
  if (index.isUnique)
2695
1932
  indexType += "UNIQUE ";
2696
1933
  if (index.isSpatial)
2697
1934
  indexType += "SPATIAL ";
2698
1935
  if (index.isFulltext)
2699
1936
  indexType += "FULLTEXT ";
2700
- var indexParser = index.isFulltext && index.parser
2701
- ? " WITH PARSER ".concat(index.parser)
1937
+ const indexParser = index.isFulltext && index.parser
1938
+ ? ` WITH PARSER ${index.parser}`
2702
1939
  : "";
2703
- return new Query_1.Query("CREATE ".concat(indexType, "INDEX `").concat(index.name, "` ON ").concat(this.escapePath(table), " (").concat(columns, ")").concat(indexParser));
2704
- };
1940
+ return new Query_1.Query(`CREATE ${indexType}INDEX \`${index.name}\` ON ${this.escapePath(table)} (${columns})${indexParser}`);
1941
+ }
2705
1942
  /**
2706
1943
  * Builds drop index sql.
2707
1944
  */
2708
- MysqlQueryRunner.prototype.dropIndexSql = function (table, indexOrName) {
2709
- var indexName = InstanceChecker_1.InstanceChecker.isTableIndex(indexOrName)
1945
+ dropIndexSql(table, indexOrName) {
1946
+ let indexName = InstanceChecker_1.InstanceChecker.isTableIndex(indexOrName)
2710
1947
  ? indexOrName.name
2711
1948
  : indexOrName;
2712
- return new Query_1.Query("DROP INDEX `".concat(indexName, "` ON ").concat(this.escapePath(table)));
2713
- };
1949
+ return new Query_1.Query(`DROP INDEX \`${indexName}\` ON ${this.escapePath(table)}`);
1950
+ }
2714
1951
  /**
2715
1952
  * Builds create primary key sql.
2716
1953
  */
2717
- MysqlQueryRunner.prototype.createPrimaryKeySql = function (table, columnNames) {
2718
- var columnNamesString = columnNames
2719
- .map(function (columnName) { return "`".concat(columnName, "`"); })
1954
+ createPrimaryKeySql(table, columnNames) {
1955
+ const columnNamesString = columnNames
1956
+ .map((columnName) => `\`${columnName}\``)
2720
1957
  .join(", ");
2721
- return new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " ADD PRIMARY KEY (").concat(columnNamesString, ")"));
2722
- };
1958
+ return new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD PRIMARY KEY (${columnNamesString})`);
1959
+ }
2723
1960
  /**
2724
1961
  * Builds drop primary key sql.
2725
1962
  */
2726
- MysqlQueryRunner.prototype.dropPrimaryKeySql = function (table) {
2727
- return new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP PRIMARY KEY"));
2728
- };
1963
+ dropPrimaryKeySql(table) {
1964
+ return new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`);
1965
+ }
2729
1966
  /**
2730
1967
  * Builds create foreign key sql.
2731
1968
  */
2732
- MysqlQueryRunner.prototype.createForeignKeySql = function (table, foreignKey) {
2733
- var columnNames = foreignKey.columnNames
2734
- .map(function (column) { return "`".concat(column, "`"); })
1969
+ createForeignKeySql(table, foreignKey) {
1970
+ const columnNames = foreignKey.columnNames
1971
+ .map((column) => `\`${column}\``)
2735
1972
  .join(", ");
2736
- var referencedColumnNames = foreignKey.referencedColumnNames
2737
- .map(function (column) { return "`".concat(column, "`"); })
1973
+ const referencedColumnNames = foreignKey.referencedColumnNames
1974
+ .map((column) => `\`${column}\``)
2738
1975
  .join(",");
2739
- var sql = "ALTER TABLE ".concat(this.escapePath(table), " ADD CONSTRAINT `").concat(foreignKey.name, "` FOREIGN KEY (").concat(columnNames, ") ") +
2740
- "REFERENCES ".concat(this.escapePath(this.getTablePath(foreignKey)), "(").concat(referencedColumnNames, ")");
1976
+ let sql = `ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT \`${foreignKey.name}\` FOREIGN KEY (${columnNames}) ` +
1977
+ `REFERENCES ${this.escapePath(this.getTablePath(foreignKey))}(${referencedColumnNames})`;
2741
1978
  if (foreignKey.onDelete)
2742
- sql += " ON DELETE ".concat(foreignKey.onDelete);
1979
+ sql += ` ON DELETE ${foreignKey.onDelete}`;
2743
1980
  if (foreignKey.onUpdate)
2744
- sql += " ON UPDATE ".concat(foreignKey.onUpdate);
1981
+ sql += ` ON UPDATE ${foreignKey.onUpdate}`;
2745
1982
  return new Query_1.Query(sql);
2746
- };
1983
+ }
2747
1984
  /**
2748
1985
  * Builds drop foreign key sql.
2749
1986
  */
2750
- MysqlQueryRunner.prototype.dropForeignKeySql = function (table, foreignKeyOrName) {
2751
- var foreignKeyName = InstanceChecker_1.InstanceChecker.isTableForeignKey(foreignKeyOrName)
1987
+ dropForeignKeySql(table, foreignKeyOrName) {
1988
+ const foreignKeyName = InstanceChecker_1.InstanceChecker.isTableForeignKey(foreignKeyOrName)
2752
1989
  ? foreignKeyOrName.name
2753
1990
  : foreignKeyOrName;
2754
- return new Query_1.Query("ALTER TABLE ".concat(this.escapePath(table), " DROP FOREIGN KEY `").concat(foreignKeyName, "`"));
2755
- };
1991
+ return new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP FOREIGN KEY \`${foreignKeyName}\``);
1992
+ }
2756
1993
  /**
2757
1994
  * Escapes a given comment so it's safe to include in a query.
2758
1995
  */
2759
- MysqlQueryRunner.prototype.escapeComment = function (comment) {
1996
+ escapeComment(comment) {
2760
1997
  if (!comment || comment.length === 0) {
2761
- return "''";
1998
+ return `''`;
2762
1999
  }
2763
2000
  comment = comment
2764
2001
  .replace(/\\/g, "\\\\") // MySQL allows escaping characters via backslashes
2765
2002
  .replace(/'/g, "''")
2766
2003
  .replace(/\u0000/g, ""); // Null bytes aren't allowed in comments
2767
- return "'".concat(comment, "'");
2768
- };
2004
+ return `'${comment}'`;
2005
+ }
2769
2006
  /**
2770
2007
  * Escapes given table or view path.
2771
2008
  */
2772
- MysqlQueryRunner.prototype.escapePath = function (target) {
2773
- var _a = this.driver.parseTableName(target), database = _a.database, tableName = _a.tableName;
2009
+ escapePath(target) {
2010
+ const { database, tableName } = this.driver.parseTableName(target);
2774
2011
  if (database && database !== this.driver.database) {
2775
- return "`".concat(database, "`.`").concat(tableName, "`");
2012
+ return `\`${database}\`.\`${tableName}\``;
2776
2013
  }
2777
- return "`".concat(tableName, "`");
2778
- };
2014
+ return `\`${tableName}\``;
2015
+ }
2779
2016
  /**
2780
2017
  * Builds a part of query to create/change a column.
2781
2018
  */
2782
- MysqlQueryRunner.prototype.buildCreateColumnSql = function (column, skipPrimary, skipName) {
2783
- if (skipName === void 0) { skipName = false; }
2784
- var c = "";
2019
+ buildCreateColumnSql(column, skipPrimary, skipName = false) {
2020
+ let c = "";
2785
2021
  if (skipName) {
2786
2022
  c = this.connection.driver.createFullType(column);
2787
2023
  }
2788
2024
  else {
2789
- c = "`".concat(column.name, "` ").concat(this.connection.driver.createFullType(column));
2025
+ c = `\`${column.name}\` ${this.connection.driver.createFullType(column)}`;
2790
2026
  }
2791
2027
  if (column.charset)
2792
- c += " CHARACTER SET \"".concat(column.charset, "\"");
2028
+ c += ` CHARACTER SET "${column.charset}"`;
2793
2029
  if (column.collation)
2794
- c += " COLLATE \"".concat(column.collation, "\"");
2030
+ c += ` COLLATE "${column.collation}"`;
2795
2031
  if (column.asExpression)
2796
- c += " AS (".concat(column.asExpression, ") ").concat(column.generatedType ? column.generatedType : "VIRTUAL");
2032
+ c += ` AS (${column.asExpression}) ${column.generatedType ? column.generatedType : "VIRTUAL"}`;
2797
2033
  // if you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to that column.
2798
2034
  if (column.zerofill) {
2799
2035
  c += " ZEROFILL";
@@ -2802,10 +2038,10 @@ var MysqlQueryRunner = /** @class */ (function (_super) {
2802
2038
  c += " UNSIGNED";
2803
2039
  }
2804
2040
  if (column.enum)
2805
- c += " (".concat(column.enum
2806
- .map(function (value) { return "'" + value.replace(/'/g, "''") + "'"; })
2807
- .join(", "), ")");
2808
- var isMariaDb = this.driver.options.type === "mariadb";
2041
+ c += ` (${column.enum
2042
+ .map((value) => "'" + value.replace(/'/g, "''") + "'")
2043
+ .join(", ")})`;
2044
+ const isMariaDb = this.driver.options.type === "mariadb";
2809
2045
  if (isMariaDb &&
2810
2046
  column.asExpression &&
2811
2047
  ["VIRTUAL", "STORED"].includes(column.generatedType || "VIRTUAL")) {
@@ -2823,50 +2059,41 @@ var MysqlQueryRunner = /** @class */ (function (_super) {
2823
2059
  // don't use skipPrimary here since updates can update already exist primary without auto inc.
2824
2060
  c += " AUTO_INCREMENT";
2825
2061
  if (column.comment && column.comment.length > 0)
2826
- c += " COMMENT ".concat(this.escapeComment(column.comment));
2062
+ c += ` COMMENT ${this.escapeComment(column.comment)}`;
2827
2063
  if (column.default !== undefined && column.default !== null)
2828
- c += " DEFAULT ".concat(column.default);
2064
+ c += ` DEFAULT ${column.default}`;
2829
2065
  if (column.onUpdate)
2830
- c += " ON UPDATE ".concat(column.onUpdate);
2066
+ c += ` ON UPDATE ${column.onUpdate}`;
2831
2067
  return c;
2832
- };
2833
- MysqlQueryRunner.prototype.getVersion = function () {
2834
- return tslib_1.__awaiter(this, void 0, void 0, function () {
2835
- var result;
2836
- return tslib_1.__generator(this, function (_a) {
2837
- switch (_a.label) {
2838
- case 0: return [4 /*yield*/, this.query("SELECT VERSION() AS `version`")];
2839
- case 1:
2840
- result = _a.sent();
2841
- return [2 /*return*/, result[0]["version"]];
2842
- }
2843
- });
2844
- });
2845
- };
2068
+ }
2069
+ async getVersion() {
2070
+ const result = await this.query(`SELECT VERSION() AS \`version\``);
2071
+ return result[0]["version"];
2072
+ }
2846
2073
  /**
2847
2074
  * Checks if column display width is by default.
2848
2075
  */
2849
- MysqlQueryRunner.prototype.isDefaultColumnWidth = function (table, column, width) {
2076
+ isDefaultColumnWidth(table, column, width) {
2850
2077
  // if table have metadata, we check if length is specified in column metadata
2851
2078
  if (this.connection.hasMetadata(table.name)) {
2852
- var metadata = this.connection.getMetadata(table.name);
2853
- var columnMetadata = metadata.findColumnWithDatabaseName(column.name);
2079
+ const metadata = this.connection.getMetadata(table.name);
2080
+ const columnMetadata = metadata.findColumnWithDatabaseName(column.name);
2854
2081
  if (columnMetadata && columnMetadata.width)
2855
2082
  return false;
2856
2083
  }
2857
- var defaultWidthForType = this.connection.driver.dataTypeDefaults &&
2084
+ const defaultWidthForType = this.connection.driver.dataTypeDefaults &&
2858
2085
  this.connection.driver.dataTypeDefaults[column.type] &&
2859
2086
  this.connection.driver.dataTypeDefaults[column.type].width;
2860
2087
  if (defaultWidthForType) {
2861
2088
  // In MariaDB & MySQL 5.7, the default widths of certain numeric types are 1 less than
2862
2089
  // the usual defaults when the column is unsigned.
2863
- var typesWithReducedUnsignedDefault = [
2090
+ const typesWithReducedUnsignedDefault = [
2864
2091
  "int",
2865
2092
  "tinyint",
2866
2093
  "smallint",
2867
2094
  "mediumint",
2868
2095
  ];
2869
- var needsAdjustment = typesWithReducedUnsignedDefault.indexOf(column.type) !== -1;
2096
+ const needsAdjustment = typesWithReducedUnsignedDefault.indexOf(column.type) !== -1;
2870
2097
  if (column.unsigned && needsAdjustment) {
2871
2098
  return defaultWidthForType - 1 === width;
2872
2099
  }
@@ -2875,9 +2102,8 @@ var MysqlQueryRunner = /** @class */ (function (_super) {
2875
2102
  }
2876
2103
  }
2877
2104
  return false;
2878
- };
2879
- return MysqlQueryRunner;
2880
- }(BaseQueryRunner_1.BaseQueryRunner));
2105
+ }
2106
+ }
2881
2107
  exports.MysqlQueryRunner = MysqlQueryRunner;
2882
2108
  //#endregion
2883
2109
  //# sourceMappingURL=MysqlQueryRunner.js.map