@dbml/core 2.6.1 → 3.1.0

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 (33) hide show
  1. package/lib/export/MysqlExporter.js +3 -3
  2. package/lib/export/PostgresExporter.js +2 -2
  3. package/lib/export/SqlServerExporter.js +2 -2
  4. package/lib/export/index.js +1 -1
  5. package/lib/import/index.js +1 -1
  6. package/lib/model_structure/database.js +5 -3
  7. package/lib/model_structure/enum.js +6 -3
  8. package/lib/model_structure/enumValue.js +6 -3
  9. package/lib/model_structure/field.js +6 -3
  10. package/lib/model_structure/schema.js +6 -3
  11. package/lib/model_structure/table.js +6 -3
  12. package/lib/parse/ANTLR/ASTGeneration/AST.js +54 -8
  13. package/lib/parse/ANTLR/ASTGeneration/ParserErrorListener.js +11 -6
  14. package/lib/parse/ANTLR/ASTGeneration/constants.js +39 -0
  15. package/lib/parse/ANTLR/ASTGeneration/index.js +33 -11
  16. package/lib/parse/ANTLR/ASTGeneration/mysql/MySQLASTGen.js +1148 -0
  17. package/lib/parse/ANTLR/ASTGeneration/mysql/MySQLBaseCommon.js +31 -0
  18. package/lib/parse/ANTLR/ASTGeneration/mysql/MySQLBaseLexer.js +40 -0
  19. package/lib/parse/ANTLR/ASTGeneration/mysql/MySQLBaseRecognizer.js +32 -0
  20. package/lib/parse/ANTLR/ASTGeneration/postgres/PostgresASTGen.js +64 -62
  21. package/lib/parse/ANTLR/parsers/mysql/MySQLLexer.g4 +1357 -0
  22. package/lib/parse/ANTLR/parsers/mysql/MySQLLexer.interp +3515 -0
  23. package/lib/parse/ANTLR/parsers/mysql/MySQLLexer.js +1211 -0
  24. package/lib/parse/ANTLR/parsers/mysql/MySQLLexer.tokens +2300 -0
  25. package/lib/parse/ANTLR/parsers/mysql/MySQLParser.g4 +3494 -0
  26. package/lib/parse/ANTLR/parsers/mysql/MySQLParser.interp +2694 -0
  27. package/lib/parse/ANTLR/parsers/mysql/MySQLParser.js +3 -0
  28. package/lib/parse/ANTLR/parsers/mysql/MySQLParser.tokens +2300 -0
  29. package/lib/parse/ANTLR/parsers/mysql/MySQLParserVisitor.js +4360 -0
  30. package/lib/parse/ANTLR/parsers/mysql/predefined.tokens +744 -0
  31. package/lib/parse/Parser.js +73 -38
  32. package/package.json +3 -2
  33. package/types/parse/Parser.d.ts +3 -1
@@ -0,0 +1,1148 @@
1
+ "use strict";
2
+
3
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports["default"] = void 0;
8
+ var _lodash = require("lodash");
9
+ var _MySqlParserVisitor = _interopRequireDefault(require("../../parsers/mysql/MySqlParserVisitor"));
10
+ var _AST = require("../AST");
11
+ var _constants = require("../constants");
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
13
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
14
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
15
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
16
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
17
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
18
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
19
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
20
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
21
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
22
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
23
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
24
+ function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
25
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
26
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
27
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
28
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
29
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
30
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
31
+ function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
32
+ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
33
+ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
34
+ function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
35
+ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
36
+ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
37
+ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /* eslint-disable class-methods-use-this */
38
+ var TABLE_OPTIONS_KIND = {
39
+ NOTE: 'note'
40
+ };
41
+ var ALTER_KIND = {
42
+ ADD_PK: 'add_pk',
43
+ ADD_FK: 'add_fk'
44
+ };
45
+ var INDEX_OPTION_KIND = {
46
+ TYPE: 'type'
47
+ };
48
+ var getTableNames = function getTableNames(names) {
49
+ var tableName = (0, _lodash.last)(names);
50
+ var schemaName = names.length > 1 ? names[names.length - 2] : undefined;
51
+ return {
52
+ tableName: tableName,
53
+ schemaName: schemaName
54
+ };
55
+ };
56
+ var getFieldNames = function getFieldNames(names) {
57
+ var fieldName = (0, _lodash.last)(names);
58
+ var tableName = names.length > 1 ? names[names.length - 2] : undefined;
59
+ var schemaName = names.length > 2 ? names[names.length - 3] : undefined;
60
+ return {
61
+ fieldName: fieldName,
62
+ tableName: tableName,
63
+ schemaName: schemaName
64
+ };
65
+ };
66
+ var MySQLASTGen = /*#__PURE__*/function (_MySQLParserVisitor) {
67
+ _inherits(MySQLASTGen, _MySQLParserVisitor);
68
+ var _super = _createSuper(MySQLASTGen);
69
+ function MySQLASTGen() {
70
+ var _this;
71
+ _classCallCheck(this, MySQLASTGen);
72
+ _this = _super.call(this);
73
+ _this.data = {
74
+ schemas: [],
75
+ tables: [],
76
+ refs: [],
77
+ enums: [],
78
+ tableGroups: [],
79
+ aliases: [],
80
+ project: {}
81
+ };
82
+ return _this;
83
+ }
84
+
85
+ // TODO: support configurable default schema name other than 'public'
86
+ _createClass(MySQLASTGen, [{
87
+ key: "findTable",
88
+ value: function findTable(schemaName, tableName) {
89
+ var realSchemaName = schemaName || 'public';
90
+ var table = this.data.tables.find(function (t) {
91
+ var targetSchemaName = t.schemaName || 'public';
92
+ return targetSchemaName === realSchemaName && t.name === tableName;
93
+ });
94
+ return table;
95
+ }
96
+
97
+ // sqlStatements? (MINUS MINUS)? EOF
98
+ }, {
99
+ key: "visitRoot",
100
+ value: function visitRoot(ctx) {
101
+ var _ctx$sqlStatements;
102
+ (_ctx$sqlStatements = ctx.sqlStatements()) === null || _ctx$sqlStatements === void 0 ? void 0 : _ctx$sqlStatements.accept(this);
103
+ return this.data;
104
+ }
105
+
106
+ // (sqlStatement (MINUS MINUS)? SEMI? | emptyStatement_)* (sqlStatement ((MINUS MINUS)? SEMI)? | emptyStatement_)
107
+ }, {
108
+ key: "visitSqlStatements",
109
+ value: function visitSqlStatements(ctx) {
110
+ var _this2 = this;
111
+ ctx.sqlStatement().forEach(function (statement) {
112
+ statement.accept(_this2);
113
+ });
114
+ }
115
+
116
+ // ddlStatement | dmlStatement | transactionStatement | replicationStatement | preparedStatement | administrationStatement | utilityStatement
117
+ }, {
118
+ key: "visitSqlStatement",
119
+ value: function visitSqlStatement(ctx) {
120
+ if (ctx.ddlStatement()) {
121
+ ctx.ddlStatement().accept(this);
122
+ }
123
+ }
124
+
125
+ // createDatabase | createEvent | createIndex | createLogfileGroup | createProcedure | createFunction | createServer | createTable | createTablespaceInnodb | createTablespaceNdb | createTrigger | createView | createRole
126
+ // | alterDatabase | alterEvent | alterFunction | alterInstance | alterLogfileGroup | alterProcedure | alterServer | alterTable | alterTablespace | alterView
127
+ // | dropDatabase | dropEvent | dropIndex | dropLogfileGroup | dropProcedure | dropFunction | dropServer | dropTable | dropTablespace | dropTrigger | dropView | dropRole
128
+ // | setRole| renameTable | truncateTable
129
+ }, {
130
+ key: "visitDdlStatement",
131
+ value: function visitDdlStatement(ctx) {
132
+ var _this3 = this;
133
+ if (ctx.createTable()) {
134
+ var _this$data$refs, _this$data$refs2;
135
+ var createTableResult = ctx.createTable().accept(this);
136
+ if (!createTableResult) return;
137
+ var tableName = createTableResult.tableName,
138
+ schemaName = createTableResult.schemaName,
139
+ definitions = createTableResult.definitions,
140
+ options = createTableResult.options;
141
+ var _definitions$reduce = definitions.reduce(function (acc, ele) {
142
+ if (ele.kind === _constants.TABLE_CONSTRAINT_KIND.FIELD) acc[0].push(ele.value);else if (ele.kind === _constants.TABLE_CONSTRAINT_KIND.INDEX) acc[1].push(ele.value);else if (ele.kind === _constants.TABLE_CONSTRAINT_KIND.UNIQUE) acc[1].push(ele.value);else if (ele.kind === _constants.TABLE_CONSTRAINT_KIND.FK) acc[2].push(ele.value);else if (ele.kind === _constants.TABLE_CONSTRAINT_KIND.PK) {
143
+ /** @type {Index} */
144
+ var index = ele.value;
145
+ if (index.columns.length > 1) acc[1].push(ele.value);else acc[3] = index;
146
+ }
147
+ return acc;
148
+ }, [[], [], [], null]),
149
+ _definitions$reduce2 = _slicedToArray(_definitions$reduce, 4),
150
+ fieldsData = _definitions$reduce2[0],
151
+ indexes = _definitions$reduce2[1],
152
+ tableRefs = _definitions$reduce2[2],
153
+ singlePkIndex = _definitions$reduce2[3];
154
+ var inlineRefsOfFields = fieldsData.map(function (fieldData) {
155
+ var _field$type$type_name;
156
+ var field = fieldData.field,
157
+ inlineRefs = fieldData.inlineRefs;
158
+ if (((_field$type$type_name = field.type.type_name) === null || _field$type$type_name === void 0 ? void 0 : _field$type$type_name.toLowerCase()) === 'enum') {
159
+ var values = field.type.args.map(function (arg) {
160
+ var newValue = arg.replace(/'|"|`/g, '').trim();
161
+ return {
162
+ name: newValue
163
+ };
164
+ });
165
+ var _enum = new _AST.Enum({
166
+ name: "".concat(tableName, "_").concat(field.name, "_enum"),
167
+ schemaName: schemaName,
168
+ values: values
169
+ });
170
+ field.type.type_name = _enum.name;
171
+ field.type.schemaName = _enum.schemaName;
172
+ _this3.data.enums.push(_enum);
173
+ }
174
+ inlineRefs.forEach(function (inlineRef) {
175
+ inlineRef.endpoints[0].tableName = tableName;
176
+ inlineRef.endpoints[0].schemaName = schemaName;
177
+ inlineRef.endpoints[0].fieldNames = [field.name];
178
+ });
179
+ return inlineRefs;
180
+ });
181
+ (_this$data$refs = this.data.refs).push.apply(_this$data$refs, _toConsumableArray((0, _lodash.flatten)(inlineRefsOfFields)));
182
+ (_this$data$refs2 = this.data.refs).push.apply(_this$data$refs2, _toConsumableArray(tableRefs.map(function (tableRef) {
183
+ tableRef.endpoints[0].tableName = tableName;
184
+ tableRef.endpoints[0].schemaName = schemaName;
185
+ return tableRef;
186
+ })));
187
+ var tableOptions = options.reduce(function (acc, option) {
188
+ acc[option.kind] = option.value;
189
+ return acc;
190
+ }, {});
191
+ var table = new _AST.Table(_objectSpread({
192
+ name: tableName,
193
+ schemaName: schemaName,
194
+ fields: fieldsData.map(function (fd) {
195
+ return fd.field;
196
+ }),
197
+ indexes: indexes
198
+ }, tableOptions));
199
+ if (singlePkIndex) {
200
+ var field = table.fields.find(function (f) {
201
+ return f.name === singlePkIndex.columns[0].value;
202
+ });
203
+ if (field) field.pk = true;
204
+ }
205
+ this.data.tables.push(table.toJSON());
206
+ } else if (ctx.alterTable()) {
207
+ ctx.alterTable().accept(this);
208
+ } else if (ctx.createIndex()) {
209
+ ctx.createIndex().accept(this);
210
+ }
211
+ }
212
+
213
+ // createTable:
214
+ // CREATE TEMPORARY? TABLE ifNotExists? tableName (LIKE tableName | '(' LIKE parenthesisTable = tableName ')') # copyCreateTable
215
+ // | CREATE TEMPORARY? TABLE ifNotExists? tableName createDefinitions? (tableOption (','? tableOption)*)? partitionDefinitions? keyViolate = (IGNORE | REPLACE)? AS? selectStatement # queryCreateTable
216
+ // | CREATE TEMPORARY? TABLE ifNotExists? tableName createDefinitions (tableOption (','? tableOption)*)? partitionDefinitions? # columnCreateTable
217
+ }, {
218
+ key: "visitCopyCreateTable",
219
+ value: function visitCopyCreateTable(ctx) {
220
+ // not supported
221
+ }
222
+ }, {
223
+ key: "visitQueryCreateTable",
224
+ value: function visitQueryCreateTable(ctx) {
225
+ var _ctx$tableOption,
226
+ _this4 = this;
227
+ var names = ctx.tableName().accept(this);
228
+ var _getTableNames = getTableNames(names),
229
+ tableName = _getTableNames.tableName,
230
+ schemaName = _getTableNames.schemaName;
231
+ if (!ctx.createDefinitions()) return null;
232
+ var definitions = ctx.createDefinitions().accept(this).filter(function (d) {
233
+ return d === null || d === void 0 ? void 0 : d.kind;
234
+ });
235
+ var options = ((_ctx$tableOption = ctx.tableOption()) === null || _ctx$tableOption === void 0 ? void 0 : _ctx$tableOption.map(function (to) {
236
+ return to.accept(_this4);
237
+ }).filter(function (o) {
238
+ return o === null || o === void 0 ? void 0 : o.kind;
239
+ })) || [];
240
+ return {
241
+ tableName: tableName,
242
+ schemaName: schemaName,
243
+ definitions: definitions,
244
+ options: options
245
+ };
246
+ }
247
+ }, {
248
+ key: "visitColumnCreateTable",
249
+ value: function visitColumnCreateTable(ctx) {
250
+ var _this5 = this;
251
+ var names = ctx.tableName().accept(this);
252
+ var _getTableNames2 = getTableNames(names),
253
+ tableName = _getTableNames2.tableName,
254
+ schemaName = _getTableNames2.schemaName;
255
+ var definitions = ctx.createDefinitions().accept(this).filter(function (d) {
256
+ return d === null || d === void 0 ? void 0 : d.kind;
257
+ });
258
+ var options = ctx.tableOption().map(function (to) {
259
+ return to.accept(_this5);
260
+ }).filter(function (o) {
261
+ return o === null || o === void 0 ? void 0 : o.kind;
262
+ });
263
+ return {
264
+ tableName: tableName,
265
+ schemaName: schemaName,
266
+ definitions: definitions,
267
+ options: options
268
+ };
269
+ }
270
+
271
+ // tableOption visits: check MySqlParser.g4 line 491.
272
+ // Out of all these rules, We only care about tableOptionComment
273
+
274
+ // COMMENT '='? STRING_LITERAL
275
+ }, {
276
+ key: "visitTableOptionComment",
277
+ value: function visitTableOptionComment(ctx) {
278
+ var quotedString = ctx.STRING_LITERAL().getText();
279
+ return {
280
+ kind: TABLE_OPTIONS_KIND.NOTE,
281
+ value: {
282
+ value: quotedString.slice(1, quotedString.length - 1)
283
+ }
284
+ };
285
+ }
286
+
287
+ // fullId
288
+ }, {
289
+ key: "visitTableName",
290
+ value: function visitTableName(ctx) {
291
+ return ctx.fullId().accept(this);
292
+ }
293
+
294
+ // uid (DOT_ID | '.' uid)?
295
+ }, {
296
+ key: "visitFullId",
297
+ value: function visitFullId(ctx) {
298
+ var _this6 = this;
299
+ var names = ctx.uid().map(function (u) {
300
+ return u.accept(_this6);
301
+ });
302
+ if (ctx.DOT_ID()) {
303
+ // DOT_ID: '.' ID_LITERAL
304
+ var text = ctx.DOT_ID().getText();
305
+ names.push(text.slice(1));
306
+ }
307
+ return names;
308
+ }
309
+
310
+ // simpleId | CHARSET_REVERSE_QOUTE_STRING | STRING_LITERAL
311
+ }, {
312
+ key: "visitUid",
313
+ value: function visitUid(ctx) {
314
+ if (ctx.simpleId()) return ctx.simpleId().accept(this);
315
+
316
+ // both CHARSET_REVERSE_QOUTE_STRING and STRING_LITERAL contain outside quotes like '...', "..." or `...`
317
+ var quotedString = ctx.getChild(0).getText();
318
+ return quotedString.slice(1, quotedString.length - 1);
319
+ }
320
+
321
+ // ID | charsetNameBase | transactionLevelBase | engineNameBase | privilegesBase
322
+ // | intervalTypeBase | dataTypeBase | keywordsCanBeId | scalarFunctionName
323
+ }, {
324
+ key: "visitSimpleId",
325
+ value: function visitSimpleId(ctx) {
326
+ return ctx.getChild(0).getText();
327
+ }
328
+
329
+ // '(' createDefinition (',' createDefinition)* ')'
330
+ }, {
331
+ key: "visitCreateDefinitions",
332
+ value: function visitCreateDefinitions(ctx) {
333
+ var _this7 = this;
334
+ return ctx.createDefinition().map(function (cd) {
335
+ return cd.accept(_this7);
336
+ });
337
+ }
338
+
339
+ // createDefinition:
340
+ // fullColumnName columnDefinition # columnDeclaration
341
+ // | tableConstraint NOT? ENFORCED? # constraintDeclaration
342
+ // | indexColumnDefinition # indexDeclaration
343
+ }, {
344
+ key: "visitColumnDeclaration",
345
+ value: function visitColumnDeclaration(ctx) {
346
+ var names = ctx.fullColumnName().accept(this);
347
+ var _getFieldNames = getFieldNames(names),
348
+ fieldName = _getFieldNames.fieldName;
349
+ var _ctx$columnDefinition = ctx.columnDefinition().accept(this),
350
+ type = _ctx$columnDefinition.type,
351
+ constraints = _ctx$columnDefinition.constraints;
352
+ var field = new _AST.Field(_objectSpread({
353
+ name: fieldName,
354
+ type: type
355
+ }, constraints));
356
+ return {
357
+ kind: _constants.TABLE_CONSTRAINT_KIND.FIELD,
358
+ value: {
359
+ field: field,
360
+ inlineRefs: constraints.inlineRefs
361
+ }
362
+ };
363
+ }
364
+ }, {
365
+ key: "visitConstraintDeclaration",
366
+ value: function visitConstraintDeclaration(ctx) {
367
+ return ctx.tableConstraint().accept(this);
368
+ }
369
+ }, {
370
+ key: "visitIndexDeclaration",
371
+ value: function visitIndexDeclaration(ctx) {
372
+ return ctx.indexColumnDefinition().accept(this);
373
+ }
374
+
375
+ // uid (dottedId dottedId?)? | .? dottedId dottedId?
376
+ }, {
377
+ key: "visitFullColumnName",
378
+ value: function visitFullColumnName(ctx) {
379
+ var _this8 = this;
380
+ var names = [];
381
+ if (ctx.uid()) names.push(ctx.uid().accept(this));
382
+ names.push.apply(names, _toConsumableArray(ctx.dottedId().map(function (dId) {
383
+ return dId.accept(_this8);
384
+ })));
385
+ return names;
386
+ }
387
+
388
+ // DOT_ID | '.' uid
389
+ }, {
390
+ key: "visitDottedId",
391
+ value: function visitDottedId(ctx) {
392
+ if (ctx.DOT_ID()) {
393
+ // DOT_ID: '.' ID_LITERAL
394
+ var text = ctx.DOT_ID().getText();
395
+ return text.slice(1);
396
+ }
397
+ return ctx.uid().accept(this);
398
+ }
399
+
400
+ // dataType columnConstraint* NOT? ENFORCED?
401
+ }, {
402
+ key: "visitColumnDefinition",
403
+ value: function visitColumnDefinition(ctx) {
404
+ var _this9 = this;
405
+ var type = ctx.dataType().accept(this);
406
+ var constraints = {
407
+ inlineRefs: []
408
+ };
409
+ ctx.columnConstraint().forEach(function (c) {
410
+ var constraint = c.accept(_this9);
411
+ if (!constraint) return;
412
+ if (constraint.kind === _constants.COLUMN_CONSTRAINT_KIND.INLINE_REF) {
413
+ constraints.inlineRefs.push(constraint.value);
414
+ return;
415
+ }
416
+ constraints[constraint.kind] = constraint.value;
417
+ });
418
+ return {
419
+ type: type,
420
+ constraints: constraints
421
+ };
422
+ }
423
+
424
+ // dataType visits:
425
+ // stringDataType | nationalVaryingStringDataType | nationalStringDataType | dimensionDataType | simpleDataType
426
+ // | collectionDataType | spatialDataType | longVarcharDataType | longVarbinaryDataType
427
+
428
+ // typeName = ( CHAR | CHARACTER | VARCHAR | TINYTEXT | TEXT | MEDIUMTEXT | LONGTEXT | NCHAR | NVARCHAR | LONG )
429
+ // VARYING? lengthOneDimension? BINARY? (charSet charsetName)? (COLLATE collationName | BINARY)? # stringDataType
430
+ }, {
431
+ key: "visitStringDataType",
432
+ value: function visitStringDataType(ctx) {
433
+ var typeName = ctx.typeName.text;
434
+ if (ctx.lengthOneDimension()) typeName += ctx.lengthOneDimension().getText();
435
+ return {
436
+ type_name: typeName,
437
+ schemaName: null
438
+ };
439
+ }
440
+
441
+ // NATIONAL typeName = (CHAR | CHARACTER) VARYING lengthOneDimension? BINARY?
442
+ }, {
443
+ key: "visitNationalVaryingStringDataType",
444
+ value: function visitNationalVaryingStringDataType(ctx) {
445
+ var typeName = ctx.typeName.text;
446
+ if (ctx.lengthOneDimension()) typeName += ctx.lengthOneDimension().getText();
447
+ return {
448
+ type_name: typeName,
449
+ schemaName: null
450
+ };
451
+ }
452
+
453
+ // NATIONAL typeName = (VARCHAR | CHARACTER | CHAR) lengthOneDimension? BINARY?
454
+ // | NCHAR typeName = VARCHAR lengthOneDimension? BINARY?
455
+ }, {
456
+ key: "visitNationalStringDataType",
457
+ value: function visitNationalStringDataType(ctx) {
458
+ var typeName = ctx.typeName.text;
459
+ if (ctx.lengthOneDimension()) typeName += ctx.lengthOneDimension().getText();
460
+ return {
461
+ type_name: typeName,
462
+ schemaName: null
463
+ };
464
+ }
465
+
466
+ // typeName = (TINYINT | SMALLINT | MEDIUMINT | INT | INTEGER | BIGINT | MIDDLEINT | INT1 | INT2 | INT3 | INT4 | INT8) lengthOneDimension? (SIGNED | UNSIGNED | ZEROFILL)*
467
+ // | typeName = REAL lengthTwoDimension? (SIGNED | UNSIGNED | ZEROFILL)*
468
+ // | typeName = DOUBLE PRECISION? lengthTwoDimension? (SIGNED | UNSIGNED | ZEROFILL)*
469
+ // | typeName = (DECIMAL | DEC | FIXED | NUMERIC | FLOAT | FLOAT4 | FLOAT8) lengthTwoOptionalDimension? (SIGNED | UNSIGNED | ZEROFILL)*
470
+ // | typeName = (BIT | TIME | TIMESTAMP | DATETIME | BINARY | VARBINARY | BLOB | YEAR) lengthOneDimension?
471
+ }, {
472
+ key: "visitDimensionDataType",
473
+ value: function visitDimensionDataType(ctx) {
474
+ var typeName = ctx.typeName.text;
475
+ if (ctx.lengthOneDimension()) typeName += ctx.lengthOneDimension().getText();
476
+ if (ctx.lengthTwoDimension()) typeName += ctx.lengthTwoDimension().getText();
477
+ if (ctx.lengthTwoOptionalDimension()) typeName += ctx.lengthTwoOptionalDimension().getText();
478
+ return {
479
+ type_name: typeName,
480
+ schemaName: null
481
+ };
482
+ }
483
+
484
+ // typeName = (DATE | TINYBLOB | MEDIUMBLOB | LONGBLOB | BOOL | BOOLEAN | SERIAL)
485
+ }, {
486
+ key: "visitSimpleDataType",
487
+ value: function visitSimpleDataType(ctx) {
488
+ var typeName = ctx.typeName.text;
489
+ return {
490
+ type_name: typeName,
491
+ schemaName: null
492
+ };
493
+ }
494
+
495
+ // typeName = (ENUM | SET) collectionOptions BINARY? (charSet charsetName)?
496
+ }, {
497
+ key: "visitCollectionDataType",
498
+ value: function visitCollectionDataType(ctx) {
499
+ if (ctx.SET()) {
500
+ var _typeName = ctx.typeName.text + ctx.collectionOptions().getText();
501
+ return {
502
+ type_name: _typeName,
503
+ schemaName: null
504
+ };
505
+ }
506
+ var typeName = ctx.typeName.text;
507
+ var args = ctx.collectionOptions().accept(this);
508
+ return {
509
+ type_name: typeName,
510
+ args: args,
511
+ schemaName: null
512
+ };
513
+ }
514
+
515
+ // '(' STRING_LITERAL (',' STRING_LITERAL)* ')'
516
+ }, {
517
+ key: "visitCollectionOptions",
518
+ value: function visitCollectionOptions(ctx) {
519
+ return ctx.STRING_LITERAL().map(function (s) {
520
+ return s.getText();
521
+ });
522
+ }
523
+
524
+ // typeName = (GEOMETRYCOLLECTION | GEOMCOLLECTION | LINESTRING | MULTILINESTRING | MULTIPOINT | MULTIPOLYGON | POINT | POLYGON | JSON | GEOMETRY) (SRID decimalLiteral)?
525
+ }, {
526
+ key: "visitSpatialDataType",
527
+ value: function visitSpatialDataType(ctx) {
528
+ var typeName = ctx.typeName.text;
529
+ return {
530
+ type_name: typeName,
531
+ schemaName: null
532
+ };
533
+ }
534
+
535
+ // typeName = LONG VARCHAR? BINARY? (charSet charsetName)? (COLLATE collationName)?
536
+ }, {
537
+ key: "visitLongVarcharDataType",
538
+ value: function visitLongVarcharDataType(ctx) {
539
+ var typeName = ctx.typeName.text;
540
+ return {
541
+ type_name: typeName,
542
+ schemaName: null
543
+ };
544
+ }
545
+
546
+ // LONG VARBINARY
547
+ }, {
548
+ key: "visitLongVarbinaryDataType",
549
+ value: function visitLongVarbinaryDataType(ctx) {
550
+ var typeName = "".concat(ctx.LONG().getText(), " ").concat(ctx.VARBINARY().getText());
551
+ return {
552
+ type_name: typeName,
553
+ schemaName: null
554
+ };
555
+ }
556
+
557
+ // columnConstraint visits:
558
+ // : nullNotnull # nullColumnConstraint
559
+ // | DEFAULT defaultValue # defaultColumnConstraint
560
+ // | VISIBLE # visibilityColumnConstraint
561
+ // | INVISIBLE # invisibilityColumnConstraint
562
+ // | (AUTO_INCREMENT | ON UPDATE currentTimestamp) # autoIncrementColumnConstraint
563
+ // | PRIMARY? KEY # primaryKeyColumnConstraint
564
+ // | UNIQUE KEY? # uniqueKeyColumnConstraint
565
+ // | COMMENT STRING_LITERAL # commentColumnConstraint
566
+ // | COLUMN_FORMAT colformat = (FIXED | DYNAMIC | DEFAULT) # formatColumnConstraint
567
+ // | STORAGE storageval = (DISK | MEMORY | DEFAULT) # storageColumnConstraint
568
+ // | referenceDefinition # referenceColumnConstraint
569
+ // | COLLATE collationName # collateColumnConstraint
570
+ // | (GENERATED ALWAYS)? AS '(' expression ')' (VIRTUAL | STORED)? # generatedColumnConstraint
571
+ // | SERIAL DEFAULT VALUE # serialDefaultColumnConstraint
572
+ // | (CONSTRAINT name = uid?)? CHECK '(' expression ')' # checkColumnConstraint
573
+
574
+ // nullColumnConstraint: nullNotnull
575
+ }, {
576
+ key: "visitNullColumnConstraint",
577
+ value: function visitNullColumnConstraint(ctx) {
578
+ return ctx.nullNotnull().accept(this);
579
+ }
580
+
581
+ // NOT? (NULL_LITERAL | NULL_SPEC_LITERAL)
582
+ }, {
583
+ key: "visitNullNotnull",
584
+ value: function visitNullNotnull(ctx) {
585
+ var notNull = false;
586
+ if (ctx.NOT()) notNull = true;
587
+ return {
588
+ kind: _constants.COLUMN_CONSTRAINT_KIND.NOT_NULL,
589
+ value: notNull
590
+ };
591
+ }
592
+
593
+ // defaultColumnConstraint: DEFAULT defaultValue
594
+ }, {
595
+ key: "visitDefaultColumnConstraint",
596
+ value: function visitDefaultColumnConstraint(ctx) {
597
+ return {
598
+ kind: _constants.COLUMN_CONSTRAINT_KIND.DEFAULT,
599
+ value: ctx.defaultValue().accept(this)
600
+ };
601
+ }
602
+
603
+ // autoIncrementColumnConstraint: (AUTO_INCREMENT | ON UPDATE currentTimestamp)
604
+ }, {
605
+ key: "visitAutoIncrementColumnConstraint",
606
+ value: function visitAutoIncrementColumnConstraint(ctx) {
607
+ if (ctx.AUTO_INCREMENT()) {
608
+ return {
609
+ kind: _constants.COLUMN_CONSTRAINT_KIND.INCREMENT,
610
+ value: true
611
+ };
612
+ }
613
+ return null;
614
+ }
615
+
616
+ // primaryKeyColumnConstraint: PRIMARY? KEY
617
+ }, {
618
+ key: "visitPrimaryKeyColumnConstraint",
619
+ value: function visitPrimaryKeyColumnConstraint(ctx) {
620
+ if (ctx.PRIMARY()) {
621
+ return {
622
+ kind: _constants.COLUMN_CONSTRAINT_KIND.PK,
623
+ value: true
624
+ };
625
+ }
626
+ return null;
627
+ }
628
+
629
+ // uniqueKeyColumnConstraint: UNIQUE KEY?
630
+ }, {
631
+ key: "visitUniqueKeyColumnConstraint",
632
+ value: function visitUniqueKeyColumnConstraint(ctx) {
633
+ return {
634
+ kind: _constants.COLUMN_CONSTRAINT_KIND.UNIQUE,
635
+ value: true
636
+ };
637
+ }
638
+
639
+ // commentColumnConstraint: COMMENT STRING_LITERAL
640
+ }, {
641
+ key: "visitCommentColumnConstraint",
642
+ value: function visitCommentColumnConstraint(ctx) {
643
+ var quotedString = ctx.STRING_LITERAL().getText();
644
+ return {
645
+ kind: _constants.COLUMN_CONSTRAINT_KIND.NOTE,
646
+ value: {
647
+ value: quotedString.slice(1, quotedString.length - 1)
648
+ }
649
+ };
650
+ }
651
+
652
+ // referenceColumnConstraint: referenceDefinition
653
+ }, {
654
+ key: "visitReferenceColumnConstraint",
655
+ value: function visitReferenceColumnConstraint(ctx) {
656
+ var value = ctx.referenceDefinition().accept(this);
657
+ return {
658
+ kind: _constants.COLUMN_CONSTRAINT_KIND.INLINE_REF,
659
+ value: value
660
+ };
661
+ }
662
+
663
+ // NULL_LITERAL | CAST '(' expression AS convertedDataType ')' | unaryOperator? constant
664
+ // | currentTimestamp (ON UPDATE currentTimestamp)? | '(' expression ')' | '(' fullId ')'
665
+ }, {
666
+ key: "visitDefaultValue",
667
+ value: function visitDefaultValue(ctx) {
668
+ var _ctx$currentTimestamp;
669
+ if (ctx.NULL_LITERAL()) {
670
+ return {
671
+ value: ctx.NULL_LITERAL().getText(),
672
+ type: _constants.DATA_TYPE.BOOLEAN // same behavior as the legacy parser
673
+ };
674
+ }
675
+
676
+ if (ctx.expression()) {
677
+ return {
678
+ value: ctx.expression().getText(),
679
+ type: _constants.DATA_TYPE.EXPRESSION
680
+ };
681
+ }
682
+ if (ctx.constant()) {
683
+ if (ctx.unaryOperator()) {
684
+ return {
685
+ value: ctx.getText(),
686
+ type: _constants.DATA_TYPE.EXPRESSION
687
+ };
688
+ }
689
+ var _ctx$constant$accept = ctx.constant().accept(this),
690
+ value = _ctx$constant$accept.value,
691
+ type = _ctx$constant$accept.type;
692
+ return {
693
+ value: value,
694
+ type: type
695
+ };
696
+ }
697
+ if ((_ctx$currentTimestamp = ctx.currentTimestamp()) !== null && _ctx$currentTimestamp !== void 0 && _ctx$currentTimestamp.length) {
698
+ return {
699
+ value: ctx.currentTimestamp()[0].getText(),
700
+ type: _constants.DATA_TYPE.EXPRESSION
701
+ };
702
+ }
703
+ return {
704
+ value: ctx.getText(),
705
+ type: _constants.DATA_TYPE.EXPRESSION
706
+ };
707
+ }
708
+
709
+ // stringLiteral | decimalLiteral | '-' decimalLiteral | hexadecimalLiteral | booleanLiteral
710
+ // | REAL_LITERAL | BIT_STRING | NOT? nullLiteral = (NULL_LITERAL | NULL_SPEC_LITERAL)
711
+ }, {
712
+ key: "visitConstant",
713
+ value: function visitConstant(ctx) {
714
+ if (ctx.stringLiteral()) {
715
+ var quotedString = ctx.stringLiteral().getText();
716
+ return {
717
+ value: quotedString.slice(1, quotedString.length - 1),
718
+ type: _constants.DATA_TYPE.STRING
719
+ };
720
+ }
721
+ if (ctx.decimalLiteral()) {
722
+ if (ctx.getChildCount() > 1) {
723
+ return {
724
+ value: ctx.getText(),
725
+ type: _constants.DATA_TYPE.EXPRESSION
726
+ };
727
+ }
728
+ return {
729
+ value: ctx.decimalLiteral().getText(),
730
+ type: _constants.DATA_TYPE.NUMBER
731
+ };
732
+ }
733
+ if (ctx.hexadecimalLiteral()) {
734
+ return {
735
+ value: ctx.hexadecimalLiteral().getText(),
736
+ type: _constants.DATA_TYPE.NUMBER
737
+ };
738
+ }
739
+ if (ctx.booleanLiteral()) {
740
+ return {
741
+ value: ctx.booleanLiteral().getText(),
742
+ type: _constants.DATA_TYPE.BOOLEAN
743
+ };
744
+ }
745
+ if (ctx.REAL_LITERAL()) {
746
+ return {
747
+ value: ctx.REAL_LITERAL().getText(),
748
+ type: _constants.DATA_TYPE.NUMBER
749
+ };
750
+ }
751
+ if (ctx.BIT_STRING()) {
752
+ return {
753
+ value: ctx.BIT_STRING().getText(),
754
+ type: _constants.DATA_TYPE.STRING
755
+ };
756
+ }
757
+ return {
758
+ value: ctx.getText(),
759
+ type: _constants.DATA_TYPE.STRING
760
+ };
761
+ }
762
+
763
+ // REFERENCES tableName indexColumnNames? (MATCH matchType = (FULL | PARTIAL | SIMPLE))? referenceAction?
764
+ }, {
765
+ key: "visitReferenceDefinition",
766
+ value: function visitReferenceDefinition(ctx) {
767
+ var _ctx$referenceAction;
768
+ var names = ctx.tableName().accept(this);
769
+ var _getTableNames3 = getTableNames(names),
770
+ tableName = _getTableNames3.tableName,
771
+ schemaName = _getTableNames3.schemaName;
772
+ if (!ctx.indexColumnNames()) return null;
773
+ var actions = ((_ctx$referenceAction = ctx.referenceAction()) === null || _ctx$referenceAction === void 0 ? void 0 : _ctx$referenceAction.accept(this)) || {};
774
+ var fieldNames = ctx.indexColumnNames().accept(this).map(function (icn) {
775
+ return icn.value;
776
+ });
777
+ var endpoint0 = new _AST.Endpoint({
778
+ tableName: null,
779
+ schemaName: null,
780
+ fieldNames: null,
781
+ relation: '*'
782
+ });
783
+ var endpoint1 = new _AST.Endpoint({
784
+ tableName: tableName,
785
+ schemaName: schemaName,
786
+ fieldNames: fieldNames,
787
+ relation: '1'
788
+ });
789
+ return new _AST.Ref({
790
+ endpoints: [endpoint0, endpoint1],
791
+ onUpdate: actions.onUpdate,
792
+ onDelete: actions.onDelete
793
+ });
794
+ }
795
+
796
+ // '(' indexColumnName (',' indexColumnName)* ')'
797
+ }, {
798
+ key: "visitIndexColumnNames",
799
+ value: function visitIndexColumnNames(ctx) {
800
+ var _this10 = this;
801
+ return ctx.indexColumnName().map(function (indexColumnName) {
802
+ return indexColumnName.accept(_this10);
803
+ });
804
+ }
805
+
806
+ // ((uid | STRING_LITERAL) ('(' decimalLiteral ')')? | expression) sortType = (ASC | DESC)?
807
+ }, {
808
+ key: "visitIndexColumnName",
809
+ value: function visitIndexColumnName(ctx) {
810
+ if (ctx.uid()) {
811
+ return {
812
+ type: _constants.CONSTRAINT_TYPE.COLUMN,
813
+ value: ctx.uid().accept(this)
814
+ };
815
+ }
816
+ if (ctx.STRING_LITERAL()) {
817
+ var quotedString = ctx.STRING_LITERAL().getText();
818
+ return {
819
+ type: _constants.CONSTRAINT_TYPE.STRING,
820
+ value: quotedString.slice(1, quotedString.length - 1)
821
+ };
822
+ }
823
+ return {
824
+ type: _constants.CONSTRAINT_TYPE.EXPRESSION,
825
+ value: ctx.expression().getText()
826
+ };
827
+ }
828
+
829
+ // ON DELETE onDelete = referenceControlType (ON UPDATE onUpdate = referenceControlType)?
830
+ // | ON UPDATE onUpdate = referenceControlType (ON DELETE onDelete = referenceControlType)?
831
+ }, {
832
+ key: "visitReferenceAction",
833
+ value: function visitReferenceAction(ctx) {
834
+ var _ctx$onDelete, _ctx$onUpdate;
835
+ var r = {};
836
+ r.onDelete = (_ctx$onDelete = ctx.onDelete) === null || _ctx$onDelete === void 0 ? void 0 : _ctx$onDelete.accept(this);
837
+ r.onUpdate = (_ctx$onUpdate = ctx.onUpdate) === null || _ctx$onUpdate === void 0 ? void 0 : _ctx$onUpdate.accept(this);
838
+ return r;
839
+ }
840
+
841
+ // RESTRICT | CASCADE | SET NULL_LITERAL | NO ACTION | SET DEFAULT
842
+ }, {
843
+ key: "visitReferenceControlType",
844
+ value: function visitReferenceControlType(ctx) {
845
+ var childIndices = _toConsumableArray(Array(ctx.getChildCount()).keys());
846
+ var text = childIndices.reduce(function (acc, i) {
847
+ return "".concat(acc).concat(ctx.getChild(i).getText(), " ");
848
+ }, '');
849
+ return text.slice(0, text.length - 1); // remove the last whitespace
850
+ }
851
+
852
+ // tableConstraint:
853
+ // (CONSTRAINT name = uid?)? PRIMARY KEY index = uid? indexType? indexColumnNames indexOption* # primaryKeyTableConstraint
854
+ // | (CONSTRAINT name = uid?)? UNIQUE indexFormat = (INDEX | KEY)? index = uid? indexType? indexColumnNames indexOption* # uniqueKeyTableConstraint
855
+ // | (CONSTRAINT name = uid?)? FOREIGN KEY index = uid? indexColumnNames referenceDefinition # foreignKeyTableConstraint
856
+ // | (CONSTRAINT name = uid?)? CHECK '(' expression ')' # checkTableConstraint
857
+
858
+ // Note: In MySQL 8.0.16 and higher, 'index' is ignored. For maximum compability, we use both 'name' and 'index' for naming index
859
+ // https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html
860
+ }, {
861
+ key: "visitPrimaryKeyTableConstraint",
862
+ value: function visitPrimaryKeyTableConstraint(ctx) {
863
+ var _ctx$name,
864
+ _ctx$index,
865
+ _ctx$indexType,
866
+ _ctx$indexOption,
867
+ _this11 = this;
868
+ var name = ((_ctx$name = ctx.name) === null || _ctx$name === void 0 ? void 0 : _ctx$name.accept(this)) || ((_ctx$index = ctx.index) === null || _ctx$index === void 0 ? void 0 : _ctx$index.accept(this));
869
+ var type = (_ctx$indexType = ctx.indexType()) === null || _ctx$indexType === void 0 ? void 0 : _ctx$indexType.accept(this);
870
+ if ((_ctx$indexOption = ctx.indexOption()) !== null && _ctx$indexOption !== void 0 && _ctx$indexOption.length) {
871
+ var indexOptions = ctx.indexOption().map(function (io) {
872
+ return io.accept(_this11);
873
+ });
874
+ var typeOption = indexOptions.find(function (io) {
875
+ return (io === null || io === void 0 ? void 0 : io.kind) === INDEX_OPTION_KIND.TYPE;
876
+ });
877
+ if (typeOption) type = typeOption.value;
878
+ }
879
+ var columns = ctx.indexColumnNames().accept(this);
880
+ return {
881
+ kind: _constants.TABLE_CONSTRAINT_KIND.PK,
882
+ value: new _AST.Index({
883
+ name: name,
884
+ pk: true,
885
+ columns: columns,
886
+ type: type
887
+ })
888
+ };
889
+ }
890
+ }, {
891
+ key: "visitUniqueKeyTableConstraint",
892
+ value: function visitUniqueKeyTableConstraint(ctx) {
893
+ var _ctx$name2,
894
+ _ctx$index2,
895
+ _ctx$indexType2,
896
+ _ctx$indexOption2,
897
+ _this12 = this;
898
+ var name = ((_ctx$name2 = ctx.name) === null || _ctx$name2 === void 0 ? void 0 : _ctx$name2.accept(this)) || ((_ctx$index2 = ctx.index) === null || _ctx$index2 === void 0 ? void 0 : _ctx$index2.accept(this));
899
+ var type = (_ctx$indexType2 = ctx.indexType()) === null || _ctx$indexType2 === void 0 ? void 0 : _ctx$indexType2.accept(this);
900
+ if ((_ctx$indexOption2 = ctx.indexOption()) !== null && _ctx$indexOption2 !== void 0 && _ctx$indexOption2.length) {
901
+ var indexOptions = ctx.indexOption().map(function (io) {
902
+ return io.accept(_this12);
903
+ });
904
+ var typeOption = indexOptions.find(function (io) {
905
+ return (io === null || io === void 0 ? void 0 : io.kind) === INDEX_OPTION_KIND.TYPE;
906
+ });
907
+ if (typeOption) type = typeOption.value;
908
+ }
909
+ var columns = ctx.indexColumnNames().accept(this);
910
+ return {
911
+ kind: _constants.TABLE_CONSTRAINT_KIND.UNIQUE,
912
+ value: new _AST.Index({
913
+ name: name,
914
+ unique: true,
915
+ columns: columns,
916
+ type: type
917
+ })
918
+ };
919
+ }
920
+ }, {
921
+ key: "visitForeignKeyTableConstraint",
922
+ value: function visitForeignKeyTableConstraint(ctx) {
923
+ var _ctx$name3, _ctx$index3;
924
+ var ref = ctx.referenceDefinition().accept(this);
925
+ ref.name = ((_ctx$name3 = ctx.name) === null || _ctx$name3 === void 0 ? void 0 : _ctx$name3.accept(this)) || ((_ctx$index3 = ctx.index) === null || _ctx$index3 === void 0 ? void 0 : _ctx$index3.accept(this));
926
+ ref.endpoints[0].fieldNames = ctx.indexColumnNames().accept(this).map(function (icn) {
927
+ return icn.value;
928
+ });
929
+ return {
930
+ kind: _constants.TABLE_CONSTRAINT_KIND.FK,
931
+ value: ref
932
+ };
933
+ }
934
+ }, {
935
+ key: "visitCheckTableConstraint",
936
+ value: function visitCheckTableConstraint(ctx) {
937
+ // ignored
938
+ }
939
+
940
+ // USING (BTREE | HASH)
941
+ }, {
942
+ key: "visitIndexType",
943
+ value: function visitIndexType(ctx) {
944
+ return ctx.getChild(1).getText();
945
+ }
946
+
947
+ // KEY_BLOCK_SIZE EQUAL_SYMBOL? fileSizeLiteral | indexType | WITH PARSER uid | COMMENT STRING_LITERAL | (VISIBLE | INVISIBLE)
948
+ // | ENGINE_ATTRIBUTE EQUAL_SYMBOL? STRING_LITERAL | SECONDARY_ENGINE_ATTRIBUTE EQUAL_SYMBOL? STRING_LITERAL
949
+ }, {
950
+ key: "visitIndexOption",
951
+ value: function visitIndexOption(ctx) {
952
+ if (ctx.indexType()) {
953
+ return {
954
+ kind: INDEX_OPTION_KIND.TYPE,
955
+ value: ctx.indexType().accept(this)
956
+ };
957
+ }
958
+ return null;
959
+ }
960
+
961
+ // indexColumnDefinition:
962
+ // indexFormat = (INDEX | KEY) uid? indexType? indexColumnNames indexOption* # simpleIndexDeclaration
963
+ // | (FULLTEXT | SPATIAL) indexFormat = (INDEX | KEY)? uid? indexColumnNames indexOption* # specialIndexDeclaration
964
+ }, {
965
+ key: "visitSimpleIndexDeclaration",
966
+ value: function visitSimpleIndexDeclaration(ctx) {
967
+ var _ctx$uid,
968
+ _ctx$indexType3,
969
+ _ctx$indexOption3,
970
+ _this13 = this;
971
+ var name = (_ctx$uid = ctx.uid()) === null || _ctx$uid === void 0 ? void 0 : _ctx$uid.accept(this);
972
+ var type = (_ctx$indexType3 = ctx.indexType()) === null || _ctx$indexType3 === void 0 ? void 0 : _ctx$indexType3.accept(this);
973
+ if ((_ctx$indexOption3 = ctx.indexOption()) !== null && _ctx$indexOption3 !== void 0 && _ctx$indexOption3.length) {
974
+ var indexOptions = ctx.indexOption().map(function (io) {
975
+ return io.accept(_this13);
976
+ });
977
+ var typeOption = indexOptions.find(function (io) {
978
+ return (io === null || io === void 0 ? void 0 : io.kind) === INDEX_OPTION_KIND.TYPE;
979
+ });
980
+ if (typeOption) type = typeOption.value;
981
+ }
982
+ var columns = ctx.indexColumnNames().accept(this);
983
+ return {
984
+ kind: _constants.TABLE_CONSTRAINT_KIND.INDEX,
985
+ value: new _AST.Index({
986
+ name: name,
987
+ columns: columns,
988
+ type: type
989
+ })
990
+ };
991
+ }
992
+ }, {
993
+ key: "visitSpecialIndexDeclaration",
994
+ value: function visitSpecialIndexDeclaration(ctx) {
995
+ var _ctx$uid2,
996
+ _ctx$indexOption4,
997
+ _this14 = this;
998
+ var name = (_ctx$uid2 = ctx.uid()) === null || _ctx$uid2 === void 0 ? void 0 : _ctx$uid2.accept(this);
999
+ var type = null;
1000
+ if ((_ctx$indexOption4 = ctx.indexOption()) !== null && _ctx$indexOption4 !== void 0 && _ctx$indexOption4.length) {
1001
+ var indexOptions = ctx.indexOption().map(function (io) {
1002
+ return io.accept(_this14);
1003
+ });
1004
+ var typeOption = indexOptions.find(function (io) {
1005
+ return (io === null || io === void 0 ? void 0 : io.kind) === INDEX_OPTION_KIND.TYPE;
1006
+ });
1007
+ if (typeOption) type = typeOption.value;
1008
+ }
1009
+ var columns = ctx.indexColumnNames().accept(this);
1010
+ return {
1011
+ kind: _constants.TABLE_CONSTRAINT_KIND.INDEX,
1012
+ value: new _AST.Index({
1013
+ name: name,
1014
+ columns: columns,
1015
+ type: type
1016
+ })
1017
+ };
1018
+ }
1019
+
1020
+ // ALTER intimeAction = (ONLINE | OFFLINE)? IGNORE? TABLE tableName waitNowaitClause? (alterSpecification (',' alterSpecification)*)? partitionDefinitions?
1021
+ }, {
1022
+ key: "visitAlterTable",
1023
+ value: function visitAlterTable(ctx) {
1024
+ var _ctx$alterSpecificati,
1025
+ _this15 = this;
1026
+ var names = ctx.tableName().accept(this);
1027
+ var _getTableNames4 = getTableNames(names),
1028
+ tableName = _getTableNames4.tableName,
1029
+ schemaName = _getTableNames4.schemaName;
1030
+
1031
+ /** @type {Table} */
1032
+ var table = this.findTable(schemaName, tableName);
1033
+ if (!table) return;
1034
+ var alterSpecs = ((_ctx$alterSpecificati = ctx.alterSpecification()) === null || _ctx$alterSpecificati === void 0 ? void 0 : _ctx$alterSpecificati.map(function (spec) {
1035
+ return spec.accept(_this15);
1036
+ }).filter(function (spec) {
1037
+ return spec === null || spec === void 0 ? void 0 : spec.kind;
1038
+ })) || [];
1039
+ alterSpecs.forEach(function (alter) {
1040
+ if (alter.kind === ALTER_KIND.ADD_PK) {
1041
+ /** @type {Index} */
1042
+ var index = alter.value;
1043
+ if (index.columns.length > 1) return table.indexes.push(index);
1044
+ var field = table.fields.find(function (f) {
1045
+ return f.name === index.columns[0].value;
1046
+ });
1047
+ field.pk = true;
1048
+ } else if (alter.kind === ALTER_KIND.ADD_FK) {
1049
+ /** @type {Ref} */
1050
+ var ref = alter.value;
1051
+ ref.endpoints[0].schemaName = schemaName;
1052
+ ref.endpoints[0].tableName = tableName;
1053
+ _this15.data.refs.push(ref);
1054
+ }
1055
+ return null;
1056
+ });
1057
+ }
1058
+
1059
+ // alterSpecification: for full rules breakdown check MySqlParser.g4 line 660.
1060
+ // The list below only containt alterSpecification rules that we will supported (should have same behaviors as the legacy parser):
1061
+ // alterByAddPrimaryKey | alterByAddForeignKey
1062
+
1063
+ // ADD (CONSTRAINT name = uid?)? PRIMARY KEY index = uid? indexType? indexColumnNames indexOption*
1064
+ }, {
1065
+ key: "visitAlterByAddPrimaryKey",
1066
+ value: function visitAlterByAddPrimaryKey(ctx) {
1067
+ var _ctx$name4,
1068
+ _ctx$index4,
1069
+ _ctx$indexType4,
1070
+ _ctx$indexOption5,
1071
+ _this16 = this;
1072
+ var name = ((_ctx$name4 = ctx.name) === null || _ctx$name4 === void 0 ? void 0 : _ctx$name4.accept(this)) || ((_ctx$index4 = ctx.index) === null || _ctx$index4 === void 0 ? void 0 : _ctx$index4.accept(this));
1073
+ var type = (_ctx$indexType4 = ctx.indexType()) === null || _ctx$indexType4 === void 0 ? void 0 : _ctx$indexType4.accept(this);
1074
+ if ((_ctx$indexOption5 = ctx.indexOption()) !== null && _ctx$indexOption5 !== void 0 && _ctx$indexOption5.length) {
1075
+ var indexOptions = ctx.indexOption().map(function (io) {
1076
+ return io.accept(_this16);
1077
+ });
1078
+ var typeOption = indexOptions.find(function (io) {
1079
+ return (io === null || io === void 0 ? void 0 : io.kind) === INDEX_OPTION_KIND.TYPE;
1080
+ });
1081
+ if (typeOption) type = typeOption.value;
1082
+ }
1083
+ var columns = ctx.indexColumnNames().accept(this);
1084
+ return {
1085
+ kind: ALTER_KIND.ADD_PK,
1086
+ value: new _AST.Index({
1087
+ name: name,
1088
+ pk: true,
1089
+ columns: columns,
1090
+ type: type
1091
+ })
1092
+ };
1093
+ }
1094
+
1095
+ // ADD (CONSTRAINT name = uid?)? FOREIGN KEY indexName = uid? indexColumnNames referenceDefinition
1096
+ }, {
1097
+ key: "visitAlterByAddForeignKey",
1098
+ value: function visitAlterByAddForeignKey(ctx) {
1099
+ var _ctx$name5, _ctx$index5;
1100
+ var ref = ctx.referenceDefinition().accept(this);
1101
+ ref.name = ((_ctx$name5 = ctx.name) === null || _ctx$name5 === void 0 ? void 0 : _ctx$name5.accept(this)) || ((_ctx$index5 = ctx.index) === null || _ctx$index5 === void 0 ? void 0 : _ctx$index5.accept(this));
1102
+ ref.endpoints[0].fieldNames = ctx.indexColumnNames().accept(this).map(function (icn) {
1103
+ return icn.value;
1104
+ });
1105
+ return {
1106
+ kind: ALTER_KIND.ADD_FK,
1107
+ value: ref
1108
+ };
1109
+ }
1110
+
1111
+ // CREATE intimeAction = (ONLINE | OFFLINE)? indexCategory = (UNIQUE | FULLTEXT | SPATIAL)? INDEX uid indexType? ON tableName indexColumnNames
1112
+ // indexOption* (ALGORITHM EQUAL_SYMBOL? algType = (DEFAULT | INPLACE | COPY) | LOCK EQUAL_SYMBOL? lockType = (DEFAULT | NONE | SHARED | EXCLUSIVE))*
1113
+ }, {
1114
+ key: "visitCreateIndex",
1115
+ value: function visitCreateIndex(ctx) {
1116
+ var _ctx$indexType5,
1117
+ _ctx$indexOption6,
1118
+ _this17 = this;
1119
+ var tableNames = ctx.tableName().accept(this);
1120
+ var _getTableNames5 = getTableNames(tableNames),
1121
+ tableName = _getTableNames5.tableName,
1122
+ schemaName = _getTableNames5.schemaName;
1123
+ var table = this.findTable(schemaName, tableName);
1124
+ if (!table) return;
1125
+ var name = ctx.uid().accept(this);
1126
+ var type = (_ctx$indexType5 = ctx.indexType()) === null || _ctx$indexType5 === void 0 ? void 0 : _ctx$indexType5.accept(this);
1127
+ if ((_ctx$indexOption6 = ctx.indexOption()) !== null && _ctx$indexOption6 !== void 0 && _ctx$indexOption6.length) {
1128
+ var indexOptions = ctx.indexOption().map(function (io) {
1129
+ return io.accept(_this17);
1130
+ });
1131
+ var typeOption = indexOptions.find(function (io) {
1132
+ return (io === null || io === void 0 ? void 0 : io.kind) === INDEX_OPTION_KIND.TYPE;
1133
+ });
1134
+ if (typeOption) type = typeOption.value;
1135
+ }
1136
+ var columns = ctx.indexColumnNames().accept(this);
1137
+ var index = new _AST.Index({
1138
+ name: name,
1139
+ columns: columns,
1140
+ unique: !!ctx.UNIQUE(),
1141
+ type: type
1142
+ });
1143
+ table.indexes.push(index);
1144
+ }
1145
+ }]);
1146
+ return MySQLASTGen;
1147
+ }(_MySqlParserVisitor["default"]);
1148
+ exports["default"] = MySQLASTGen;