Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/dbml alias & primary key & note content bug #504

Merged
merged 5 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export default class TableValidator implements ElementValidator {
}

if (!isValidAlias(aliasNode)) {
return [new CompileError(CompileErrorCode.INVALID_ALIAS, 'A Table alias must be of the form <alias>', aliasNode)]
return [new CompileError(CompileErrorCode.INVALID_ALIAS, 'Table aliases can only contains alphanumeric and underscore unless surrounded by double quotes', aliasNode)]
}

return [];
Expand Down Expand Up @@ -134,7 +134,7 @@ export default class TableValidator implements ElementValidator {

const maybeNameFragments = destructureComplexVariable(name);
if (maybeNameFragments.isOk()) {
const nameFragments = maybeNameFragments.unwrap();
Huy-DNA marked this conversation as resolved.
Show resolved Hide resolved
const nameFragments = [...maybeNameFragments.unwrap()];
const tableName = nameFragments.pop()!;
const symbolTable = registerSchemaStack(nameFragments, this.publicSymbolTable, this.symbolFactory);
const tableId = createTableSymbolIndex(tableName);
Expand All @@ -144,10 +144,14 @@ export default class TableValidator implements ElementValidator {
symbolTable.set(tableId, this.declarationNode.symbol!);
}

if (alias && isSimpleName(alias)) {
const aliasId = createTableSymbolIndex(extractVarNameFromPrimaryVariable(alias as any).unwrap());
if (
alias && isSimpleName(alias) &&
!isAliasSameAsName(alias.expression.variable!.value, maybeNameFragments.unwrap_or([]))
) {
const aliasName = extractVarNameFromPrimaryVariable(alias as any).unwrap();
const aliasId = createTableSymbolIndex(aliasName);
if (this.publicSymbolTable.has(aliasId)) {
errors.push(new CompileError(CompileErrorCode.DUPLICATE_NAME, `Table name '${alias}' already exists`, name!))
errors.push(new CompileError(CompileErrorCode.DUPLICATE_NAME, `Table name '${aliasName}' already exists`, name!))
}
this.publicSymbolTable.set(aliasId, this.declarationNode.symbol!)
}
Expand Down Expand Up @@ -422,3 +426,7 @@ function isValidColumnType(type: SyntaxNode): boolean {

return variables !== undefined && variables.length > 0;
}

function isAliasSameAsName(alias: string, nameFragments: string[]): boolean {
return nameFragments.length === 1 && alias === nameFragments[0];
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { aggregateSettingList } from "../../analyzer/validator/utils";
import { CompileError, CompileErrorCode } from "../../errors";
import { BlockExpressionNode, ElementDeclarationNode, FunctionApplicationNode, ListExpressionNode, SyntaxNode } from "../../parser/nodes";
import { ElementInterpreter, Enum, EnumField, InterpreterDatabase, Table } from "../types";
import { extractElementName, getTokenPosition, normalizeNoteContent } from "../utils";
import { extractElementName, getTokenPosition } from "../utils";

export class EnumInterpreter implements ElementInterpreter {
private declarationNode: ElementDeclarationNode;
Expand Down Expand Up @@ -50,7 +50,7 @@ export class EnumInterpreter implements ElementInterpreter {
const settingMap = aggregateSettingList(field.args[0] as ListExpressionNode).getValue();
const noteNode = settingMap['note']?.at(0);
enumField.note = noteNode && {
value: normalizeNoteContent(extractQuotedStringToken(noteNode.value).unwrap()),
value: extractQuotedStringToken(noteNode.value).unwrap(),
token: getTokenPosition(noteNode),
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { extractQuotedStringToken } from "../../analyzer/utils";
import { CompileError } from "../../errors";
import { BlockExpressionNode, ElementDeclarationNode, FunctionApplicationNode, SyntaxNode } from "../../parser/nodes";
import { ElementInterpreter, InterpreterDatabase, Project } from "../types";
import { extractElementName, getTokenPosition, normalizeNoteContent } from "../utils";
import { extractElementName, getTokenPosition } from "../utils";
import { EnumInterpreter } from "./enum";
import { RefInterpreter } from "./ref";
import { TableInterpreter } from "./table";
Expand Down Expand Up @@ -63,7 +63,7 @@ export class ProjectInterpreter implements ElementInterpreter {
}
case 'note': {
this.project.note = {
value: normalizeNoteContent(extractQuotedStringToken(sub.body instanceof BlockExpressionNode ? (sub.body.body[0] as FunctionApplicationNode).callee : sub.body!.callee).unwrap()),
value: extractQuotedStringToken(sub.body instanceof BlockExpressionNode ? (sub.body.body[0] as FunctionApplicationNode).callee : sub.body!.callee).unwrap(),
token: getTokenPosition(sub),
}
return [];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Column, ColumnType, ElementInterpreter, Index, InlineRef, InterpreterDatabase, Table } from '../types';
import { ArrayNode, AttributeNode, BlockExpressionNode, CallExpressionNode, ElementDeclarationNode, FunctionApplicationNode, FunctionExpressionNode, ListExpressionNode, PrefixExpressionNode, SyntaxNode } from '../../parser/nodes';
import { extractColor, extractElementName, getColumnSymbolsOfRefOperand, getMultiplicities, getRefId, getTokenPosition, isSameEndpoint, normalizeNoteContent } from '../utils';
import { extractColor, extractElementName, getColumnSymbolsOfRefOperand, getMultiplicities, getRefId, getTokenPosition, isSameEndpoint } from '../utils';
import { destructureComplexVariable, destructureIndexNode, extractQuotedStringToken, extractVarNameFromPrimaryVariable, extractVariableFromExpression } from '../../analyzer/utils';
import { CompileError, CompileErrorCode } from '../../errors';
import { aggregateSettingList, isExpressionANumber } from '../../analyzer/validator/utils';
Expand Down Expand Up @@ -97,7 +97,7 @@ export class TableInterpreter implements ElementInterpreter {
const [noteNode] = settingMap['note'] || [];
const noteValue = extractQuotedStringToken(noteNode?.value).unwrap_or(undefined);
this.table.note = noteNode && {
value: normalizeNoteContent(noteValue!),
value: noteValue!,
token: getTokenPosition(noteNode),
};

Expand All @@ -114,7 +114,7 @@ export class TableInterpreter implements ElementInterpreter {
switch (sub.type?.value.toLowerCase()) {
case 'note':
this.table.note = {
value: normalizeNoteContent(extractQuotedStringToken(sub.body instanceof BlockExpressionNode ? (sub.body.body[0] as FunctionApplicationNode).callee : sub.body!.callee).unwrap()),
value: extractQuotedStringToken(sub.body instanceof BlockExpressionNode ? (sub.body.body[0] as FunctionApplicationNode).callee : sub.body!.callee).unwrap(),
token: getTokenPosition(sub),
}
return [];
Expand Down Expand Up @@ -149,14 +149,14 @@ export class TableInterpreter implements ElementInterpreter {
const settings = field.args.slice(1);
if (_.last(settings) instanceof ListExpressionNode) {
const settingMap = aggregateSettingList(settings.pop() as ListExpressionNode).getValue();
column.pk = !!settingMap['pk']?.length;
column.pk = !!settingMap['pk']?.length || !!settingMap['primary key']?.length;
column.increment = !!settingMap['increment']?.length;
column.unique = !!settingMap['unique']?.length;
column.not_null = !!settingMap['not null']?.length && true;
column.dbdefault = processDefaultValue(settingMap['default']?.at(0)?.value);
const noteNode = settingMap['note']?.at(0);
column.note = noteNode && {
value: normalizeNoteContent(extractQuotedStringToken(noteNode.value).unwrap()),
value: extractQuotedStringToken(noteNode.value).unwrap(),
token: getTokenPosition(noteNode),
}
const refs = settingMap['ref'] || [];
Expand Down Expand Up @@ -244,7 +244,7 @@ export class TableInterpreter implements ElementInterpreter {
index.name = extractQuotedStringToken(settingMap['name']?.at(0)?.value).unwrap_or(undefined);
const noteNode = settingMap['note']?.at(0);
index.note = noteNode && {
value: normalizeNoteContent(extractQuotedStringToken(noteNode.value).unwrap()),
value: extractQuotedStringToken(noteNode.value).unwrap(),
token: getTokenPosition(noteNode),
};
index.type = extractVariableFromExpression(settingMap['type']?.at(0)?.value).unwrap_or(undefined);
Expand Down
7 changes: 0 additions & 7 deletions packages/dbml-parse/src/lib/interpreter/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,6 @@ export function getColumnSymbolsOfRefOperand(ref: SyntaxNode): ColumnSymbol[] {
return [colNode!.referee as ColumnSymbol];
}

export function normalizeNoteContent(content: string): string {
return content
.split('\n')
.map((s) => s.trim())
.join('\n');
}

export function extractElementName(nameNode: SyntaxNode): { schemaName: string[]; name: string } {
const fragments = destructureComplexVariable(nameNode).unwrap();
const name = fragments.pop()!;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Table A {
id int [primary key]
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
}
},
"inline_refs": [],
"pk": false,
"pk": true,
"increment": false,
"unique": false,
"not_null": false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"unique": false,
"not_null": false,
"note": {
"value": "\n\n# Objective\n* Support writing long string that can \\undefined'span' over multiple lines\n* Support writing markdown for DBML Note\n\n# Syntax\n\n",
"value": "\n\n # Objective\n * Support writing long string that can \\undefined'span' over multiple lines\n * Support writing markdown for DBML Note\n \n # Syntax\n\n ",
"token": {
"start": {
"offset": 24,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@
}
},
"inline_refs": [],
"pk": false,
"pk": true,
"increment": false,
"unique": false,
"not_null": false
Expand Down
55 changes: 55 additions & 0 deletions packages/dbml-parse/tests/interpreter/output/primary_key.out.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"schemas": [],
"tables": [
{
"name": "A",
"schemaName": null,
"alias": null,
"fields": [
{
"name": "id",
"type": {
"schemaName": null,
"type_name": "int",
"args": null
},
"token": {
"start": {
"offset": 14,
"line": 2,
"column": 5
},
"end": {
"offset": 34,
"line": 2,
"column": 25
}
},
"inline_refs": [],
"pk": true,
"increment": false,
"unique": false,
"not_null": false
}
],
"token": {
"start": {
"offset": 0,
"line": 1,
"column": 1
},
"end": {
"offset": 36,
"line": 3,
"column": 2
}
},
"indexes": []
}
],
"refs": [],
"enums": [],
"tableGroups": [],
"aliases": [],
"project": {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1386,7 +1386,7 @@
"tables": [],
"name": "ecommerce",
"note": {
"value": "\n# Introduction\nThis is an ecommerce project\n\n# Description\n...\n",
"value": "\n # Introduction\n This is an ecommerce project\n\n # Description\n ...\n ",
"token": {
"start": {
"offset": 22,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
}
},
"inline_refs": [],
"pk": false,
"pk": true,
"increment": false,
"unique": false,
"not_null": false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"unique": false,
"not_null": false,
"note": {
"value": "\n\n# Objective\n* Support writing long string that can \\undefined'span' over multiple lines\n* Support writing markdown for DBML Note\n\n# Syntax\n\n",
"value": "\n\n # Objective\n * Support writing long string that can \\undefined'span' over multiple lines\n * Support writing markdown for DBML Note\n \n # Syntax\n\n ",
"token": {
"start": {
"offset": 24,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1386,7 +1386,7 @@
"tables": [],
"name": "ecommerce",
"note": {
"value": "\n# Introduction\nThis is an ecommerce project\n\n# Description\n...\n",
"value": "\n # Introduction\n This is an ecommerce project\n\n # Description\n ...\n ",
"token": {
"start": {
"offset": 22,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Table A as A {
id int [primary key]
}

Table "B" as B {
id int [primary key]
}

Table C as "C" {
id int [primary key]
}

Table "D" as "D" {
id int [primary key]
}
Original file line number Diff line number Diff line change
Expand Up @@ -2256,7 +2256,7 @@
},
{
"code": 3003,
"diagnostic": "Table name '[object Object]' already exists",
"diagnostic": "Table name 'U1' already exists",
"nodeOrToken": {
"id": 13,
"kind": "<primary-expression>",
Expand Down
Loading
Loading