| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
- <title>数据库表查询</title>
- <script src="https://kylx365-1253256735.file.myqcloud.com/js/jquery-1.10.2.min.js"></script>
- <script src="https://kylx365-1253256735.file.myqcloud.com/js/vue.min.js"></script>
- <style>
- /* 表格项样式 */
- .table-item {
- padding: 10px;
- margin: 5px 0;
- background: white;
- border-radius: 4px;
- cursor: pointer;
- transition: background-color 0.2s;
- }
- .table-comment {
- font-size: 12px;
- color: #999;
- margin-top: 2px;
- }
- .main00 {
- width: 100%;
- height: 100vh;
- min-height: 600px;
- background: white;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- }
- .ListTop {
- width: 100%;
- height: 60px;
- background: white;
- border-bottom: 1px solid #EEEEEE;
- justify-content: flex-start;
- flex-shrink: 0;
- }
- .ListTop3 {
- margin-left: 40px;
- height: 50px;
- align-items: center;
- }
- .title {
- font-size: 24px;
- color: #333333;
- font-weight: bold;
- }
- .main0 {
- width: 100%;
- background: white;
- flex: 1;
- min-height: 0;
- overflow: hidden;
- display: flex;
- position: relative;
- align-items: flex-start;
- }
- .tables-panel {
- width: 300px;
- border-right: 1px solid #EEEEEE;
- background: #F9F9F9;
- display: flex;
- flex-direction: column;
- height: 100%;
- position: relative;
- flex-shrink: 0;
- }
- .search-box {
- padding: 15px 0;
- border-bottom: 1px solid #EEEEEE;
- background: white;
- width: 100%;
- justify-content: center;
- width: 100%;
- }
- .search-input {
- width: 200px;
- height: 32px;
- padding: 0 32px 0 12px;
- border: 1px solid #DDDDDD;
- border-radius: 4px;
- font-size: 14px;
- color: #333333;
- }
- .search-input:focus {
- border-color: #4A90E2;
- outline: none;
- }
- .btn33 {
- width: 32px;
- height: 32px;
- margin-left: 8px;
- border-radius: 4px;
- background: #F5F5F5;
- cursor: pointer;
- justify-content: center;
- align-items: center;
- }
- .btn33:hover {
- background: #EEEEEE;
- }
- .content-panel {
- width: calc(100% - 300px);
- height: 100%;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- }
- .sql-editor {
- padding: 20px;
- border-bottom: 1px solid #EEEEEE;
- background: white;
- height: 200px;
- display: flex;
- flex-direction: row;
- }
- .sql-editor-left {
- flex: 1;
- display: flex;
- flex-direction: column;
- margin-right: 20px;
- }
- .sql-editor-right {
- width: 400px;
- display: flex;
- flex-direction: column;
- border-left: 1px solid #EEEEEE;
- padding-left: 20px;
- position: relative;
- }
- .columns-list {
- flex: 1;
- overflow-y: auto;
- border: 1px solid #DDDDDD;
- border-radius: 4px;
- background: #FFFFFF;
- }
- .column-item {
- padding: 8px 10px;
- border-bottom: 1px solid #EEEEEE;
- cursor: pointer;
- display: flex;
- flex-direction: row;
- justify-content: space-between;
- }
- .column-item:hover {
- background-color: #F0F7FF;
- }
- .column-left {
- display: flex;
- flex-direction: column;
- flex: 1;
- }
- .column-right {
- display: flex;
- align-items: center;
- min-width: 100px;
- padding-left: 10px;
- }
- .column-name {
- font-weight: bold;
- }
- .column-type {
- font-size: 13px;
- color: #666;
- background-color: #f5f5f5;
- padding: 2px 6px;
- border-radius: 3px;
- white-space: nowrap;
- }
- .column-comment {
- font-size: 12px;
- color: #999;
- margin-top: 2px;
- }
- .sql-textarea {
- width: 100%;
- height: 120px;
- padding: 10px;
- border: 1px solid #DDDDDD;
- border-radius: 4px;
- font-family: monospace;
- font-size: 14px;
- resize: none;
- margin-bottom: 10px;
- }
- .sql-textarea:focus {
- border-color: #4A90E2;
- outline: none;
- }
- .results-panel {
- flex: 1;
- overflow: auto;
- padding: 20px;
- background: white;
- position: relative;
- }
- .table-container {
- width: 100%;
- overflow-x: auto;
- max-height: calc(100vh - 380px); /* 减去其他元素的高度 */
- overflow-y: auto;
- position: relative; /* 为内部元素提供定位上下文 */
- }
- .data-table {
- width: 100%;
- border-collapse: separate; /* 改为separate以支持边框样式 */
- border-spacing: 0; /* 消除单元格间距 */
- font-size: 14px;
- }
- .data-table th {
- background: #F5F5F5;
- padding: 10px;
- text-align: left;
- border: 1px solid #DDDDDD;
- position: sticky;
- top: 0;
- z-index: 10;
- box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
- }
- /* 确保表头单元格背景色完整覆盖 */
- .data-table thead th {
- background: #F5F5F5;
- }
-
- /* 优化表头在滚动时的视觉效果 */
- .table-container:not(:hover) .data-table th {
- transition: box-shadow 0.3s ease;
- }
-
- .table-container:hover .data-table th {
- box-shadow: 0 3px 5px -2px rgba(0, 0, 0, 0.2);
- }
- .data-table td {
- padding: 8px 10px;
- border: 1px solid #DDDDDD;
- max-width: 300px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .data-table tr:nth-child(even) {
- background-color: #F9F9F9;
- }
- .data-table tr:hover {
- background-color: #F0F7FF;
- }
- .btn {
- min-width: 30px;
- height: 36px;
- padding: 0 16px;
- margin-left: 12px;
- border: none;
- border-radius: 4px;
- cursor: pointer;
- font-size: 14px;
- transition: all 0.3s;
- }
- .btn-primary {
- background: #4A90E2;
- color: white;
- }
- .btn-primary:hover {
- background: #357ABD;
- }
- .btn-default {
- background: white;
- border: 1px solid #DDDDDD;
- color: #666666;
- }
- .btn-default:hover {
- background: #F5F5F5;
- border-color: #CCCCCC;
- }
-
- .btn:disabled {
- opacity: 0.5;
- cursor: not-allowed;
- pointer-events: none;
- }
- .toast {
- position: fixed;
- top: 20px;
- left: 50%;
- transform: translateX(-50%);
- padding: 12px 24px;
- background: rgba(0, 0, 0, 0.7);
- color: white;
- border-radius: 4px;
- z-index: 9999;
- opacity: 0;
- transition: opacity 0.3s;
- }
- .toast.show {
- opacity: 1;
- }
- .toast.success {
- background: #4CAF50;
- }
- .toast.error {
- background: #F44336;
- }
- .toast.info {
- background: #2196F3;
- }
- /* Loading样式 */
- .loading-overlay {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(255, 255, 255, 0.7);
- display: flex;
- justify-content: center;
- align-items: center;
- z-index: 100;
- }
- .loading-spinner {
- width: 50px;
- height: 50px;
- border: 5px solid #f3f3f3;
- border-top: 5px solid #4A90E2;
- border-radius: 50%;
- animation: spin 1s linear infinite;
- }
- @keyframes spin {
- 0% {
- transform: rotate(0deg);
- }
- 100% {
- transform: rotate(360deg);
- }
- }
- .clear-btn {
- position: absolute;
- right: 12px;
- top: 50%;
- transform: translateY(-50%);
- width: 16px;
- height: 16px;
- background-color: #999;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- transition: background-color 0.2s;
- }
- .clear-btn:hover {
- background-color: #666;
- }
- .clear-x {
- position: relative;
- width: 8px;
- height: 8px;
- }
- .clear-x:before,
- .clear-x:after {
- content: '';
- position: absolute;
- width: 8px;
- height: 2px;
- background-color: white;
- top: 3px;
- left: 0;
- }
- .clear-x:before {
- transform: rotate(45deg);
- }
- .clear-x:after {
- transform: rotate(-45deg);
- }
- .FlexRow {
- display: flex;
- flex-direction: row;
- }
- .FlexColumn {
- display: flex;
- flex-direction: column;
- }
- .table-list {
- flex: 1;
- overflow-y: auto;
- padding: 10px;
- }
- .table-item {
- padding: 10px;
- margin: 5px 0;
- background: white;
- border-radius: 4px;
- cursor: pointer;
- overflow-x: hidden;
- transition: background-color 0.2s;
- }
- .table-item:hover {
- background-color: #f0f0f0;
- }
- .table-item.active {
- background-color: #e6f3ff;
- border-left: 3px solid #4A90E2;
- }
- .btn-group {
- display: flex;
- justify-content: flex-end;
- margin-top: 10px;
- }
- .no-data {
- text-align: center;
- padding: 40px;
- color: #999;
- font-size: 16px;
- }
- .pagination {
- display: flex;
- justify-content: center;
- margin-top: 20px;
- padding: 10px;
- }
- .pagination-btn {
- padding: 5px 10px;
- margin: 0 5px;
- border: 1px solid #DDDDDD;
- border-radius: 4px;
- background: white;
- cursor: pointer;
- }
- .pagination-btn:hover {
- background: #F5F5F5;
- }
- .pagination-btn.active {
- background: #4A90E2;
- color: white;
- border-color: #4A90E2;
- }
- .pagination-btn.disabled {
- color: #CCCCCC;
- cursor: not-allowed;
- }
- /* 完整内容弹出层样式 - 改进版 */
- .complete-content-overlay {
- position: fixed;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- display: flex;
- justify-content: center;
- align-items: center;
- z-index: 1000;
- background-color: rgba(0, 0, 0, 0.5);
- pointer-events: auto;
- }
-
- .complete-content-container {
- width: 80%;
- max-width: 800px;
- max-height: 80vh;
- background-color: white;
- border-radius: 8px;
- padding: 20px;
- padding-top: 50px; /* 为固定的关闭按钮留出空间 */
- position: relative;
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
- overflow: auto;
- animation: fadeIn 0.3s ease-out;
- }
- @keyframes fadeIn {
- from {
- opacity: 0;
- transform: translateY(20px);
- }
- to {
- opacity: 1;
- transform: translateY(0);
- }
- }
-
- .close-btn {
- position: absolute;
- right: 15px; /* 根据弹窗宽度计算位置 */
- top: 15px; /* 根据弹窗位置计算 */
- z-index: 1010; /* 确保按钮在最上层 */
- width: 40px;
- height: 40px;
- display: flex;
- align-items: center;
- justify-content: center;
- background: rgba(255, 255, 255, 0.9);
- border: none;
- border-radius: 50%;
- font-size: 24px;
- cursor: pointer;
- color: #999;
- box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
- }
-
- .close-btn:hover {
- color: #333;
- background: #fff;
- }
-
- .complete-content {
- white-space: pre-wrap;
- word-break: break-word;
- font-family: monospace;
- line-height: 1.5;
- }
- </style>
- </head>
- <body class="container FlexRow">
- <div id="app" class="main00 FlexColumn">
- <div class="ListTop FlexRow">
- <div class="ListTop3 FlexRow" style="width: 100%; justify-content: space-between;">
- <div class="title">数据库表查询</div>
- </div>
- </div>
- <div class="main0 FlexRow">
- <!-- 左侧表格列表 -->
- <div class="tables-panel" style="position: relative;">
- <div v-if="isTablesLoading" class="loading-overlay">
- <div class="loading-spinner"></div>
- </div>
- <div class="search-box FlexRow">
- <div style="position: relative;">
- <input type="text" class="search-input" v-model="searchText" @input="searchTables" @keyup.enter="searchTables"
- placeholder="搜索表格...">
- <div class="clear-btn" v-show="searchText" @click="clearSearch">
- <span class="clear-x"></span>
- </div>
- </div>
- <div class="btn33 FlexRow" @click="searchTables">
- <img title="搜索" alt="搜索"
- src="https://kylx365-1253256735.file.myqcloud.com/web/universalpic_search_gray_30x30.png"
- style="width: 20px; height: 20px;" />
- </div>
- </div>
- <!-- 表格列表 -->
- <div class="table-list">
- <div v-if="tables && tables.length > 0">
- <div v-for="(table, index) in filteredTables" :key="index" @click="selectTable(table)"
- :class="['table-item', { active: selectedTable === table }]">
- <div class="table-name">{{ table }}</div>
- <div class="table-comment" v-if="tableComments[table]">{{ tableComments[table] }}</div>
- </div>
- <div v-if="filteredTables.length === 0" class="no-data">
- 没有匹配的表格
- </div>
- </div>
- <div v-else-if="tables && tables.length === 0" class="no-data">
- 未找到表格
- </div>
- <div v-else class="no-data">
- 加载中...
- </div>
- </div>
- </div>
- <!-- 右侧内容区域 -->
- <div class="content-panel">
- <!-- SQL编辑器 -->
- <div class="sql-editor">
- <!-- 左侧SQL编辑区域 -->
-
- <div class="sql-editor-right">
- <div v-if="isColumnsLoading" class="loading-overlay">
- <div class="loading-spinner"></div>
- </div>
- <div class="columns-list">
- <div v-if="tableColumnsList && tableColumnsList.length > 0">
- <div v-for="(column, index) in tableColumnsList" :key="index" class="column-item"
- @click="copyColumnName(column.name)" @dblclick="insertColumnName(column.name)">
- <div class="column-left">
- <div class="column-name">{{ column.name }}</div>
- <div class="column-comment" v-if="column.comment">{{ column.comment }}</div>
- </div>
- <div class="column-right">
- <div class="column-type">{{ column.type }}</div>
- </div>
- </div>
- </div>
- <div v-else class="no-data">
- 请选择表格查看字段列表
- </div>
- </div>
- </div>
- <!-- 右侧字段列表 -->
- <div class="sql-editor-left">
- <textarea class="sql-textarea" v-model="sqlQuery" placeholder="输入SQL查询语句..."></textarea>
- <div class="btn-group" style="justify-content: flex-start;">
- <button type="button" class="btn btn-default" @click="insertSqlClause('WHERE')">WHERE</button>
- <button type="button" class="btn btn-default" @click="insertSqlClause('INNER JOIN ON')" :disabled="!hasWhere">INNER JOIN ON</button>
- <button type="button" class="btn btn-default" @click="insertSqlClause('GROUP BY')">GROUP BY</button>
- <button type="button" class="btn btn-default" @click="insertSqlClause('HAVING')" :disabled="!hasGroupBy">HAVING</button>
- <button type="button" class="btn btn-default" @click="insertSqlClause('ORDER BY')">ORDER BY</button>
- <select class="btn btn-default" v-model="selectedLimit" @change="updateQueryLimit"
- style="margin-left: 8px;">
- <option v-for="limit in limitOptions" :key="limit" :value="limit">
- LIMIT {{ limit }}
- </option>
- </select>
- <div style="margin-left: auto;">
- <button type="button" class="btn btn-default" @click="clearQuery">清空</button>
- <button type="button" class="btn btn-primary" @click="executeQuery">执行</button>
- </div>
- </div>
- </div>
- </div>
- <!-- 查询结果 -->
- <div class="results-panel" style="position: relative;">
- <div v-if="isQueryLoading" class="loading-overlay">
- <div class="loading-spinner"></div>
- </div>
- <div v-if="queryExecuted" class="table-container">
- <div v-if="allResults && allResults.length > 0">
- <div style="margin-bottom: 10px; color: #666;">
- 显示 {{ queryResults.length }} 条记录,共 {{ allResults.length }} 条
- </div>
- <div v-if="isQueryLoading" class="loading-indicator">
- <div class="spinner"></div>
- <div>数据加载中...</div>
- </div>
- <div v-else-if="!tableColumns || tableColumns.length === 0" class="no-data">
- 未检测到有效的表格列
- </div>
- <template v-else>
- <table class="data-table">
- <thead>
- <tr>
- <th v-for="(column, index) in tableColumns"
- :key="'th-'+index"
- v-show="!column.startsWith('__')">
- {{ column }}
- </th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="(row, rowIndex) in queryResults"
- :key="'tr-'+rowIndex">
- <td v-for="(column, colIndex) in tableColumns"
- :key="'td-'+rowIndex+'-'+colIndex"
- v-show="!column.startsWith('__')"
- @dblclick="formatTableCell(row[column]).endsWith('...') ? showCompleteField(row, column) : copyColumnName(formatTableCell(row[column]))"
- >
- {{ formatTableCell(row[column]) }}
- </td>
- </tr>
- </tbody>
- </table>
- <div v-if="queryResults.length === 0" class="no-data">
- 没有可显示的数据
- <div v-if="allResults.length > 0" style="margin-top: 10px; font-size: 12px; color: #999;">
- 共 {{allResults.length}} 条数据
- </div>
- </div>
- </template>
-
- </div>
- <div v-else class="no-data">
- 查询未返回数据
- </div>
- </div>
- <div v-else-if="queryExecuted" class="no-data">
- 查询未返回数据
- </div>
- <div v-else class="no-data">
- 请选择表格并执行查询
- </div>
- </div>
- </div>
- </div>
- <!-- Toast提示 -->
- <div class="toast" :class="{ show: showToast, [toastType]: showToast }">{{ toastMessage }}</div>
-
- <!-- 完整内容弹出层 -->
- <div v-if="showCompleteContent" class="complete-content-overlay" @click.self="closeCompleteContent">
- <div class="complete-content-container">
- <button class="close-btn" @click="closeCompleteContent">×</button>
- <div class="complete-content" @dblclick="copyToClipboard(completeContent)">
- {{ completeContent }}
- </div>
- </div>
- </div>
- </div>
- <script>
- new Vue({
- el: '#app',
- data: {
- searchText: '',
- tables: [], // 存储表格名称列表
- tableComments: {}, // 存储表格注释,格式为 {表名: 注释}
- filteredTables: [],
- selectedTable: null,
- sqlQuery: '',
- queryResults: [],
- tableColumns: [],
- showToast: false,
- toastMessage: '',
- toastType: 'info',
- isTablesLoading: false,
- isQueryLoading: false,
- isColumnsLoading: false,
- queryExecuted: false,
- allResults: [],
- tableColumnsList: [], // 存储表格字段列表
- limitOptions: [10, 100, 500, 1000, 2000, 3000], // LIMIT选项
- selectedLimit: 100, // 默认选中的LIMIT值
- showCompleteContent: false,
- completeContent: '',
- currentRow: null,
- currentColumn: null
- },
- computed: {
- // 检查SQL查询中是否包含WHERE子句
- hasWhere() {
- return this.sqlQuery && this.sqlQuery.toUpperCase().includes('WHERE');
- },
- // 检查SQL查询中是否包含GROUP BY子句
- hasGroupBy() {
- return this.sqlQuery && this.sqlQuery.toUpperCase().includes('GROUP BY');
- }
- },
- mounted() {
- this.loadTables();
- },
- methods: {
- // 加载数据库表格列表
- loadTables() {
- this.isTablesLoading = true;
- this.tableComments = {};
- // 调用后端API获取表格列表
- fetch('/api/GetKylx365Tables')
- .then(response => {
- // console.log('API响应状态:', response.status);
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- return response.json();
- })
- .then(data => {
- //console.log('API返回数据:', data);
- // 检查数据格式,处理可能的不同响应结构
- //console.log('检查数据格式:', data);
- // 尝试确定数据的实际结构
- let resultData = null;
- if (data && data.result && Array.isArray(data.result)) {
- //console.log('标准格式: data.result 是数组');
- resultData = data.result;
- } else if (data && Array.isArray(data)) {
- //console.log('替代格式: data 本身是数组');
- resultData = data;
- } else if (data && typeof data === 'object') {
- //console.log('检查对象中的数组属性');
- // 尝试在对象中找到数组属性
- for (const key in data) {
- if (Array.isArray(data[key])) {
- //console.log(`找到数组属性: ${key}`);
- resultData = data[key];
- break;
- }
- }
- }
- if (resultData && Array.isArray(resultData)) {
- //console.log('数据验证通过,开始处理数据');
- //console.log('数据结果长度:', resultData.length);
- if (resultData.length > 0 && typeof resultData[0] === 'object' && !Array.isArray(resultData[0])) {
- //console.log('检测到对象数组格式,第一个对象:', resultData[0]);
- //console.log('第一个对象的属性:', Object.keys(resultData[0]));
- // 检查并适应不同的属性名称
- const firstItem = resultData[0];
- const tableNameKey = 'table_name' in firstItem ? 'table_name' :
- 'tableName' in firstItem ? 'tableName' :
- 'name' in firstItem ? 'name' : null;
- const tableCommentKey = 'table_comment' in firstItem ? 'table_comment' :
- 'tableComment' in firstItem ? 'tableComment' :
- 'comment' in firstItem ? 'comment' : null;
- //console.log('使用的属性名:', { tableNameKey, tableCommentKey });
- if (tableNameKey) {
- // 如果返回的是对象数组(包含name和comment)
- this.tables = resultData.map(item => {
- const tableName = item[tableNameKey] || '';
- //console.log('处理表名:', tableName);
- return tableName;
- }).filter(name => name); // 过滤掉空表名
- //console.log('处理后的表格列表:', this.tables);
- // 存储表格注释
- if (tableCommentKey) {
- resultData.forEach(item => {
- const tableName = item[tableNameKey] || '';
- const tableComment = item[tableCommentKey] || '';
- if (tableName && tableComment) {
- this.tableComments[tableName] = tableComment;
- }
- });
- //console.log('处理后的表格注释:', this.tableComments);
- }
- } else {
- //console.error('无法找到表名属性');
- this.showToastMessage('数据格式错误:无法找到表名属性', 'error');
- }
- } else {
- //console.log('检测到简单数组格式');
- // 如果返回的只是表名数组
- this.tables = resultData.filter(name => {
- //console.log('处理表名:', name);
- return name && typeof name === 'string';
- });
- //console.log('处理后的表格列表:', this.tables);
- }
- this.filteredTables = [...this.tables];
- // console.log('更新后的过滤表格列表:', this.filteredTables);
- } else {
- this.tables = [];
- this.filteredTables = [];
- this.showToastMessage('获取表格列表失败', 'error');
- }
- this.isTablesLoading = false;
- })
- .catch(error => {
- //console.error('获取表格列表失败详细错误:', error);
- this.showToastMessage(`获取表格列表失败: ${error.message}`, 'error');
- this.isTablesLoading = false;
- });
- },
- // 搜索表格
- searchTables() {
- //console.log('开始搜索表格,搜索文本:', this.searchText);
- if (!this.searchText.trim()) {
- //console.log('搜索文本为空,显示所有表格');
- this.filteredTables = [...this.tables];
- return;
- }
- const searchTerm = this.searchText.toLowerCase();
- //console.log('过滤表格列表,搜索条件:', searchTerm);
- this.filteredTables = this.tables.filter(table => {
- const tableName = table.toLowerCase();
- const tableComment = (this.tableComments[table] || '').toLowerCase();
- const matches = tableName.includes(searchTerm) || tableComment.includes(searchTerm);
- // if (matches) {
- // console.log(`表格匹配: ${table} (${this.tableComments[table] || '无注释'})`);
- // }
- return matches;
- });
- //console.log('过滤后的表格数量:', this.filteredTables.length);
- },
- // 清空搜索
- clearSearch() {
- this.searchText = '';
- this.filteredTables = [...this.tables];
- },
- // 选择表格
- selectTable(table) {
- this.selectedTable = table;
-
- // 重置LIMIT值为默认的100
- this.selectedLimit = 100;
-
- // 获取表格字段列表
- this.loadTableColumns(table);
-
- // 监听字段列表变化,当加载完成后构建查询语句
- this.$watch('tableColumnsList', (newVal) => {
- if (newVal && newVal.length > 0) {
- const columns = newVal.map(col => `\`${col.name}\``).join(',');
- this.sqlQuery = `SELECT ${columns}\nFROM \`${table}\`\nLIMIT ${this.selectedLimit};`;
- } else {
- this.sqlQuery = `SELECT *\nFROM \`${table}\`\nLIMIT ${this.selectedLimit};`;
- }
- }, {immediate: true});
- },
- // 加载表格字段列表
- loadTableColumns(tableName) {
- this.isColumnsLoading = true;
- this.tableColumnsList = [];
- // 调用API获取表格字段列表
- fetch(`/api/GetKylx365TableColumnByTable?table=${encodeURIComponent(tableName)}`)
- .then(response => response.json())
- .then(data => {
- //console.log('收到的原始数据:', data);
- // 验证数据格式
- if (!data) {
- //console.error('接收到空数据');
- throw new Error('接收到空数据');
- }
- // 尝试确定数据的实际结构
- let columnsData = null;
- if (data && data.result && Array.isArray(data.result)) {
- //console.log('标准格式: data.result 是数组');
- columnsData = data.result;
- } else if (data && Array.isArray(data)) {
- //console.log('替代格式: data 本身是数组');
- columnsData = data;
- } else if (data && typeof data === 'object') {
- //console.log('检查对象中的数组属性');
- // 尝试在对象中找到数组属性
- for (const key in data) {
- if (Array.isArray(data[key])) {
- //console.log(`找到数组属性: ${key}`);
- columnsData = data[key];
- break;
- }
- }
- }
- if (columnsData && Array.isArray(columnsData)) {
- //console.log('数据验证通过,开始处理数据');
- //console.log('字段数据长度:', columnsData.length);
- if (columnsData.length > 0) {
- // 检查第一个元素的格式
- const firstItem = columnsData[0];
- //console.log('第一个字段项:', firstItem);
- if (typeof firstItem === 'object' && !Array.isArray(firstItem)) {
- // 检查并适应不同的属性名称
- const nameKey = 'Field' in firstItem ? 'Field' :
- 'name' in firstItem ? 'name' :
- 'column_name' in firstItem ? 'column_name' :
- 'columnName' in firstItem ? 'columnName' :
- 'field' in firstItem ? 'field' : null;
- const typeKey = 'Type' in firstItem ? 'Type' :
- 'type' in firstItem ? 'type' :
- 'column_type' in firstItem ? 'column_type' :
- 'columnType' in firstItem ? 'columnType' :
- 'data_type' in firstItem ? 'data_type' : null;
- const commentKey = 'Comment' in firstItem ? 'Comment' :
- 'comment' in firstItem ? 'comment' :
- 'column_comment' in firstItem ? 'column_comment' :
- 'columnComment' in firstItem ? 'columnComment' : null;
- // 组合Default和Extra作为注释
- const getComment = (item) => {
- let comment = [];
- if (item['Default']) {
- comment.push(`默认值: ${item['Default']}`);
- }
- if (item['Extra'] && item['Extra'] !== '') {
- comment.push(item['Extra']);
- }
- if (item['Null'] === 'NO') {
- comment.push('不可为空');
- }
- return comment.join(', ');
- };
- //console.log('使用的属性名:', { nameKey, typeKey, commentKey });
- if (nameKey) {
- // 转换为标准格式
- this.tableColumnsList = columnsData.map(item => {
- return {
- name: item[nameKey] || '',
- type: typeKey ? (item[typeKey] || '') : '',
- comment: [
- commentKey ? (item[commentKey] || '') : '',
- getComment(item)
- ].filter(Boolean).join(' | ')
- };
- }).filter(col => col.name); // 过滤掉没有名称的列
- //console.log('处理后的字段列表:', this.tableColumnsList);
- } else {
- console.error('无法找到字段名属性');
- this.showToastMessage('数据格式错误:无法找到字段名属性', 'error');
- this.tableColumnsList = [];
- }
- } else if (typeof firstItem === 'string') {
- // 如果只是字段名数组
- this.tableColumnsList = columnsData.map(name => {
- return {
- name: name,
- type: '',
- comment: ''
- };
- });
- //console.log('处理后的字段列表(仅名称):', this.tableColumnsList);
- } else {
- console.error('未知的字段数据格式');
- this.showToastMessage('未知的字段数据格式', 'error');
- this.tableColumnsList = [];
- }
- } else {
- //console.log('字段列表为空');
- this.tableColumnsList = [];
- }
- } else {
- //console.error('无法找到有效的字段数据');
- this.tableColumnsList = [];
- this.showToastMessage('获取字段列表失败', 'error');
- }
- this.isColumnsLoading = false;
- })
- .catch(error => {
- this.showToastMessage('获取字段列表失败,请稍后重试', 'error');
- this.isColumnsLoading = false;
- });
- },
- // 清空查询
- clearQuery() {
- this.sqlQuery = '';
- },
- // 复制字段名称到剪贴板
- copyColumnName(columnName) {
- // 创建一个临时文本区域元素
- const textarea = document.createElement('textarea');
- textarea.value = columnName;
- textarea.setAttribute('readonly', '');
- textarea.style.position = 'absolute';
- textarea.style.left = '-9999px';
- document.body.appendChild(textarea);
- // 选择文本并复制
- textarea.select();
- let success = false;
- try {
- success = document.execCommand('copy');
- this.showToastMessage(`已复制字段 "${columnName}" 到剪贴板`, 'success');
- } catch (err) {
- success = false;
- this.showToastMessage('复制失败,请手动复制', 'error');
- console.error('复制到剪贴板失败:', err);
- }
- // 移除临时元素
- document.body.removeChild(textarea);
- // 如果浏览器支持现代剪贴板API,也尝试使用它
- if (navigator.clipboard && window.isSecureContext) {
- navigator.clipboard.writeText(columnName).catch(err => {
- console.log('剪贴板API失败,但已使用备用方法', err);
- });
- }
- return success;
- },
- // 插入字段名称到SQL查询(双击时触发)
- insertColumnName(columnName) {
- // 获取文本框元素
- const textarea = document.querySelector('.sql-textarea');
- // 添加反引号的字段名
- const quotedColumnName = `\`${columnName}\``;
- // 如果文本框存在
- if (textarea) {
- // 获取当前光标位置
- const startPos = textarea.selectionStart;
- const endPos = textarea.selectionEnd;
- // 在光标位置插入字段名称
- const textBefore = this.sqlQuery.substring(0, startPos);
- const textAfter = this.sqlQuery.substring(endPos);
- // 更新SQL查询
- this.sqlQuery = textBefore + quotedColumnName + textAfter;
- // 设置新的光标位置
- this.$nextTick(() => {
- textarea.focus();
- textarea.selectionStart = startPos + quotedColumnName.length;
- textarea.selectionEnd = startPos + quotedColumnName.length;
- });
- this.showToastMessage(`已插入字段 "${columnName}" 到查询`, 'info');
- } else {
- // 如果无法获取文本框元素,则直接在末尾添加
- this.sqlQuery += ' ' + quotedColumnName;
- }
- },
- // 更新SQL查询中的LIMIT值
- updateQueryLimit() {
- // 检查SQL查询是否为空
- if (!this.sqlQuery.trim()) {
- return;
- }
- // 正则表达式匹配LIMIT子句
- const limitRegex = /\bLIMIT\s+\d+\s*;?\s*$/i;
- if (limitRegex.test(this.sqlQuery)) {
- // 如果已经有LIMIT子句,替换数字
- this.sqlQuery = this.sqlQuery.replace(limitRegex, `LIMIT ${this.selectedLimit}${this.sqlQuery.endsWith(';') ? ';' : ''}`);
- } else {
- // 如果没有LIMIT子句,添加到末尾
- // 确保前面有换行符
- const hasNewlineBefore = this.sqlQuery.trimEnd().endsWith('\n');
- const prefix = hasNewlineBefore ? '' : '\n';
-
- // 检查SQL是否以分号结尾
- if (this.sqlQuery.trim().endsWith(';')) {
- // 在分号前添加LIMIT
- this.sqlQuery = this.sqlQuery.replace(/;\s*$/, `${prefix}LIMIT ${this.selectedLimit};`);
- } else {
- // 直接在末尾添加LIMIT
- this.sqlQuery = this.sqlQuery.trim() + `${prefix}LIMIT ${this.selectedLimit};`;
- }
- }
- this.showToastMessage(`已设置查询限制为 ${this.selectedLimit} 条记录`, 'info');
- },
- // 执行查询
- executeQuery() {
- if (!this.sqlQuery.trim()) {
- this.showToastMessage('请输入SQL查询语句', 'info');
- return;
- }
- this.isQueryLoading = true;
- this.queryExecuted = true;
- // 重置查询结果
- this.queryResults = [];
- this.tableColumns = [];
- this.allResults = [];
- // 调用后端API执行SQL查询,使用RunKylx365DBSql接口
- const apiUrl = '/api/RunKylx365DBSql';
- fetch(apiUrl, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Accept': 'application/json'
- },
- body: JSON.stringify({
- sql: this.sqlQuery.trim()
- })
- })
- .then(response => {
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- return response.json();
- })
- .then(data => {
- // 检查数据格式
- let resultData = null;
- let errorMessage = null;
- // 检查标准格式 {"errcode": 10000, result: [...]}
- if (data && typeof data === 'object' && 'errcode' in data) {
- if (data.errcode !== 10000) {
- errorMessage = data.errmsg || '查询返回错误';
- console.error('查询返回错误:', errorMessage);
- } else if (data.result && Array.isArray(data.result)) {
- resultData = data.result;
- }
- }
- // 检查其他可能的格式
- else if (data && Array.isArray(data)) {
- resultData = data;
- } else if (data && typeof data === 'object') {
- // 尝试在对象中找到数组属性
- for (const key in data) {
- if (Array.isArray(data[key])) {
- resultData = data[key];
- break;
- }
- }
- }
- if (errorMessage) {
- console.error('查询返回错误:', errorMessage);
- this.showToastMessage(errorMessage, 'error');
- this.queryResults = [];
- this.tableColumns = [];
- } else if (resultData && Array.isArray(resultData)) {
- this.processQueryResults(resultData);
- } else {
- this.queryResults = [];
- this.tableColumns = [];
- this.showToastMessage('查询未返回数据', 'info');
- }
- this.isQueryLoading = false;
- })
- .catch(error => {
- this.showToastMessage('执行查询失败,请稍后重试', 'error');
- this.isQueryLoading = false;
- });
- },
- // 处理查询结果
- processQueryResults(results) {
- // 确保结果是一个数组
- if (!results || !Array.isArray(results) || results.length === 0) {
- console.warn('结果为空或非数组');
- this.$set(this, 'queryResults', []);
- this.$set(this, 'tableColumns', []);
- this.$set(this, 'allResults', []);
- this.showToastMessage('查询未返回数据', 'info');
- console.groupEnd();
- return;
- }
- // 创建深拷贝避免引用问题
- const safeResults = JSON.parse(JSON.stringify(results));
- try {
-
- // 直接使用原始结果数据
- const formattedResults = results;
-
- // 使用Vue.set确保响应式更新
- this.$set(this, 'allResults', formattedResults);
- // 提取表格列,排除Vue内部属性
- if (formattedResults.length > 0) {
- // 确保所有行有相同的列结构
- const allColumns = new Set();
- formattedResults.forEach(row => {
- Object.keys(row).forEach(key => {
- if (!key.startsWith('__')) {
- allColumns.add(key);
- }
- });
- });
-
- const columns = Array.from(allColumns);
-
- // 验证数据完整性
- const missingData = formattedResults.filter(row => {
- return columns.some(col => !(col in row));
- });
-
- if (missingData.length > 0) {
- console.warn('发现数据不完整:', missingData);
- }
-
- this.$set(this, 'tableColumns', columns);
- } else {
- this.$set(this, 'tableColumns', []);
- }
-
- this.$set(this, 'queryResults', formattedResults);
- this.showToastMessage(`查询成功,返回 ${formattedResults.length} 条记录`, 'success');
- } catch (error) {
- console.error('处理查询结果时出错:', error);
- this.showToastMessage('处理查询结果时出错: ' + error.message, 'error');
- this.queryResults = [];
- this.tableColumns = [];
- this.allResults = [];
- }
- },
- // 格式化表格单元格内容
- formatTableCell(value) {
- if (value === null || value === undefined) {
- return 'NULL';
- }
- if (typeof value === 'object') {
- try {
- return JSON.stringify(value);
- } catch (e) {
- return '[Object]';
- }
- }
- if (typeof value === 'boolean') {
- return value ? '是' : '否';
- }
- return value;
- },
- // 显示完整字段内容
- showCompleteField(row, column) {
- // 检查当前单元格内容是否有省略
- const cellContent = this.formatTableCell(row[column]);
- if (!cellContent.includes('...')) {
- return;
- }
-
- this.currentRow = row;
- this.currentColumn = column;
- this.showCompleteContent = true;
- this.completeContent = '加载中...';
-
- // 查找主键字段 - 优先使用实际存在的列名
- let primaryKey = null;
-
- // 检查当前行是否有id字段
- if ('id' in row) {
- primaryKey = 'id';
- }
- // 检查是否有ID字段(大写)
- else if ('ID' in row) {
- primaryKey = 'ID';
- }
- // 检查表字段列表中是否有id字段
- else if (this.tableColumnsList.some(col => col.name.toLowerCase() === 'id')) {
- primaryKey = 'id';
- }
- // 检查表字段列表中是否有ID字段(大写)
- else if (this.tableColumnsList.some(col => col.name === 'ID')) {
- primaryKey = 'ID';
- }
- // 使用第一个存在的字段作为主键
- else if (this.tableColumnsList.length > 0) {
- const firstCol = this.tableColumnsList[0].name;
- if (firstCol in row) {
- primaryKey = firstCol;
- }
- }
-
- if (!primaryKey || !row[primaryKey]) {
- this.completeContent = '无法确定主键字段或主键值为空';
- return;
- }
-
- // 构建查询SQL
- const sql = `SELECT \`${column}\` FROM \`${this.selectedTable}\` WHERE \`${primaryKey}\`='${row[primaryKey]}';`;
-
- // 调用API获取完整数据
- fetch('/api/RunKylx365DBSql', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- sql: sql,
- IsCompleteField: true
- })
- })
- .then(response => response.json())
- .then(data => {
- if (data && data.result && data.result.length > 0) {
- this.completeContent = this.formatTableCell(data.result[0][column]);
- } else {
- this.completeContent = '未获取到完整数据';
- }
- })
- .catch(error => {
- this.completeContent = '获取完整数据失败: ' + error.message;
- });
- },
-
- // 关闭完整内容弹出层
- closeCompleteContent() {
- this.showCompleteContent = false;
- this.completeContent = '';
- this.currentRow = null;
- this.currentColumn = null;
- },
-
- // 复制到剪贴板
- copyToClipboard(text) {
- navigator.clipboard.writeText(text).then(() => {
- this.showToastMessage('已复制到剪贴板', 'success');
- }).catch(err => {
- this.showToastMessage('复制失败: ' + err, 'error');
- });
- },
-
- // 插入SQL子句(ORDER BY, GROUP BY, HAVING等)
- insertSqlClause(clause) {
- // 检查SQL查询是否为空
- if (!this.sqlQuery.trim()) {
- this.sqlQuery = clause + ' ';
- return;
- }
-
- // 检查子句是否已存在(不区分大小写)
- const sqlUpper = this.sqlQuery.toUpperCase();
- const clauseUpper = clause.toUpperCase();
-
- if (sqlUpper.includes(clauseUpper)) {
- this.showToastMessage(`查询中已存在 "${clause}" 子句`, 'info');
- return;
- }
-
- // 解析SQL查询,识别各个子句的位置
- const sqlParts = {
- select: -1,
- from: -1,
- join: -1,
- where: -1,
- groupBy: -1,
- having: -1,
- orderBy: -1,
- limit: -1
- };
-
- // 查找各个子句的位置
- sqlParts.select = sqlUpper.indexOf('SELECT');
- sqlParts.from = sqlUpper.indexOf('FROM', sqlParts.select);
- sqlParts.join = sqlUpper.indexOf('JOIN', sqlParts.from);
- sqlParts.where = sqlUpper.indexOf('WHERE', sqlParts.from);
- sqlParts.groupBy = sqlUpper.indexOf('GROUP BY', sqlParts.from);
- sqlParts.having = sqlUpper.indexOf('HAVING', sqlParts.from);
- sqlParts.orderBy = sqlUpper.indexOf('ORDER BY', sqlParts.from);
-
- // 查找LIMIT子句(可能在末尾或分号前)
- const limitMatch = sqlUpper.match(/LIMIT\s+\d+/i);
- if (limitMatch) {
- sqlParts.limit = limitMatch.index;
- }
-
- // 确定插入位置
- let insertPosition = -1;
- let insertBefore = '';
-
- switch (clauseUpper) {
- case 'INNER JOIN ON':
- // INNER JOIN ON应该在FROM之后,WHERE/GROUP BY/HAVING/ORDER BY之前
- if (sqlParts.from > -1) {
- // 找到FROM子句后的位置
- const fromEndPos = this.findClauseEndPosition(sqlUpper, sqlParts.from);
- insertPosition = fromEndPos;
-
- // 如果已经有其他JOIN子句,找到最后一个JOIN的位置
- if (sqlParts.join > -1) {
- const lastJoinPos = sqlUpper.lastIndexOf('JOIN', sqlParts.where > -1 ? sqlParts.where : sqlUpper.length);
- if (lastJoinPos > -1) {
- insertPosition = this.findClauseEndPosition(sqlUpper, lastJoinPos);
- }
- }
-
- // 如果有WHERE子句,确保在WHERE之前有换行
- if (sqlParts.where > -1) {
- const beforeWhere = this.sqlQuery.substring(0, sqlParts.where).trimEnd();
- const afterWhere = this.sqlQuery.substring(sqlParts.where);
- if (!beforeWhere.endsWith('\n')) {
- this.sqlQuery = beforeWhere + '\n' + afterWhere;
- // 更新WHERE位置
- sqlParts.where = beforeWhere.length + 1;
- }
- }
- } else {
- // 如果没有FROM子句,显示错误提示
- this.showToastMessage('INNER JOIN ON子句必须在FROM子句之后', 'error');
- return;
- }
- break;
-
- case 'WHERE':
- // WHERE应该在FROM之后,GROUP BY/HAVING/ORDER BY/LIMIT之前
- if (sqlParts.from > -1) {
- // 找到FROM子句后的位置
- const fromEndPos = this.findClauseEndPosition(sqlUpper, sqlParts.from);
- insertPosition = fromEndPos;
-
- // 如果有LIMIT子句,先处理换行
- if (sqlParts.limit > -1) {
- // 检查LIMIT前是否有换行
- const limitLineStart = this.sqlQuery.lastIndexOf('\n', sqlParts.limit);
- if (limitLineStart === -1 || limitLineStart < fromEndPos) {
- // 在LIMIT前插入换行符
- const beforeLimit = this.sqlQuery.substring(0, sqlParts.limit).trimEnd();
- const afterLimit = this.sqlQuery.substring(sqlParts.limit);
- this.sqlQuery = beforeLimit + '\n' + afterLimit;
- // 更新LIMIT位置
- sqlParts.limit = beforeLimit.length + 1;
- }
- }
- } else if (sqlParts.groupBy > -1) {
- // 如果没有FROM但有GROUP BY,插入在GROUP BY之前
- insertPosition = sqlParts.groupBy;
- insertBefore = 'GROUP BY';
- } else if (sqlParts.having > -1) {
- // 如果没有GROUP BY但有HAVING,插入在HAVING之前
- insertPosition = sqlParts.having;
- insertBefore = 'HAVING';
- } else if (sqlParts.orderBy > -1) {
- // 如果没有HAVING但有ORDER BY,插入在ORDER BY之前
- insertPosition = sqlParts.orderBy;
- insertBefore = 'ORDER BY';
- } else if (sqlParts.limit > -1) {
- // 如果只有LIMIT,插入在LIMIT之前
- insertPosition = sqlParts.limit;
- insertBefore = 'LIMIT';
- } else {
- // 如果没有以上子句,插入在查询末尾(可能有分号)
- insertPosition = this.sqlQuery.length;
- if (this.sqlQuery.trim().endsWith(';')) {
- insertPosition = this.sqlQuery.lastIndexOf(';');
- }
- }
- break;
-
- case 'GROUP BY':
- // GROUP BY应该在WHERE之后,HAVING/ORDER BY/LIMIT之前
- if (sqlParts.where > -1) {
- // 找到WHERE子句后的位置
- const whereEndPos = this.findClauseEndPosition(sqlUpper, sqlParts.where);
- insertPosition = whereEndPos;
- } else if (sqlParts.having > -1) {
- // 如果没有WHERE但有HAVING,插入在HAVING之前
- insertPosition = sqlParts.having;
- insertBefore = 'HAVING';
- } else if (sqlParts.orderBy > -1) {
- // 如果没有WHERE和HAVING但有ORDER BY,插入在ORDER BY之前
- insertPosition = sqlParts.orderBy;
- insertBefore = 'ORDER BY';
- } else if (sqlParts.limit > -1) {
- // 如果只有LIMIT,插入在LIMIT之前
- insertPosition = sqlParts.limit;
- insertBefore = 'LIMIT';
- } else {
- // 如果没有以上子句,插入在查询末尾(可能有分号)
- insertPosition = this.sqlQuery.length;
- if (this.sqlQuery.trim().endsWith(';')) {
- insertPosition = this.sqlQuery.lastIndexOf(';');
- }
- }
- break;
-
- case 'HAVING':
- // HAVING应该在GROUP BY之后,ORDER BY/LIMIT之前
- if (sqlParts.groupBy > -1) {
- // 找到GROUP BY子句后的位置
- const groupByEndPos = this.findClauseEndPosition(sqlUpper, sqlParts.groupBy);
- insertPosition = groupByEndPos;
- } else if (sqlParts.orderBy > -1) {
- // 如果没有GROUP BY但有ORDER BY,插入在ORDER BY之前
- insertPosition = sqlParts.orderBy;
- insertBefore = 'ORDER BY';
- } else if (sqlParts.limit > -1) {
- // 如果只有LIMIT,插入在LIMIT之前
- insertPosition = sqlParts.limit;
- insertBefore = 'LIMIT';
- } else {
- // 如果没有以上子句,插入在查询末尾(可能有分号)
- insertPosition = this.sqlQuery.length;
- if (this.sqlQuery.trim().endsWith(';')) {
- insertPosition = this.sqlQuery.lastIndexOf(';');
- }
- }
- break;
-
- case 'ORDER BY':
- // ORDER BY应该在GROUP BY和HAVING之后,LIMIT之前
- if (sqlParts.having > -1) {
- // 找到HAVING子句后的位置
- const havingEndPos = this.findClauseEndPosition(sqlUpper, sqlParts.having);
- insertPosition = havingEndPos;
- } else if (sqlParts.groupBy > -1) {
- // 如果没有HAVING但有GROUP BY,找到GROUP BY子句后的位置
- const groupByEndPos = this.findClauseEndPosition(sqlUpper, sqlParts.groupBy);
- insertPosition = groupByEndPos;
- } else if (sqlParts.limit > -1) {
- // 如果只有LIMIT,插入在LIMIT之前
- insertPosition = sqlParts.limit;
- insertBefore = 'LIMIT';
- } else {
- // 如果没有以上子句,插入在查询末尾(可能有分号)
- insertPosition = this.sqlQuery.length;
- if (this.sqlQuery.trim().endsWith(';')) {
- insertPosition = this.sqlQuery.lastIndexOf(';');
- }
- }
- break;
- }
-
- // 执行插入
- if (insertPosition > -1) {
- let newQuery = '';
- if (insertBefore) {
- // 在特定子句之前插入
- const beforeInsert = this.sqlQuery.substring(0, insertPosition).trimEnd();
- const afterInsert = this.sqlQuery.substring(insertPosition);
-
- // 确保只有一个换行符
- const hasNewline = beforeInsert.endsWith('\n');
- const prefix = hasNewline ? '' : '\n';
-
- // 添加换行符和子句
- newQuery = beforeInsert + prefix + clause + ' ' + afterInsert;
- } else {
- // 在子句末尾插入
- const beforeInsert = this.sqlQuery.substring(0, insertPosition).trimEnd();
- const afterInsert = this.sqlQuery.substring(insertPosition);
-
- // 确保只有一个换行符
- const hasNewline = beforeInsert.endsWith('\n');
- const prefix = hasNewline ? '' : '\n';
-
- // 添加换行符和子句
- newQuery = beforeInsert + prefix + clause + ' ' + afterInsert;
- }
-
- this.sqlQuery = newQuery;
-
- // 对所有子句,确保LIMIT在新行
- // 查找LIMIT位置(可能已改变)
- const newSqlUpper = this.sqlQuery.toUpperCase();
- const newLimitPos = newSqlUpper.indexOf('LIMIT');
-
- if (newLimitPos > -1) {
- // 检查LIMIT前是否有换行
- const beforeLimit = this.sqlQuery.substring(0, newLimitPos).trimEnd();
- const afterLimit = this.sqlQuery.substring(newLimitPos);
-
- // 确保LIMIT前有换行
- if (!beforeLimit.endsWith('\n')) {
- this.sqlQuery = beforeLimit + '\n' + afterLimit;
- }
- }
-
- this.showToastMessage(`已插入 "${clause}" 子句到查询`, 'success');
-
- // 设置光标位置到插入的子句之后
- this.$nextTick(() => {
- const textarea = document.querySelector('.sql-textarea');
- if (textarea) {
- textarea.focus();
- const newPosition = insertPosition + clause.length + 1;
- textarea.selectionStart = newPosition;
- textarea.selectionEnd = newPosition;
- }
- });
- } else {
- // 如果无法确定位置,则在末尾添加
- if (this.sqlQuery.trim().endsWith(';')) {
- this.sqlQuery = this.sqlQuery.replace(/;\s*$/, `\n${clause} ;`);
- } else {
- this.sqlQuery += `\n${clause} `;
- }
- this.showToastMessage(`已插入 "${clause}" 子句到查询末尾`, 'info');
- }
- },
-
- // 查找子句结束位置的辅助方法
- findClauseEndPosition(sqlUpper, clauseStartPos) {
- // 子句可能的结束标记
- const endMarkers = ['GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT', ';'];
- let endPos = sqlUpper.length;
-
- // 查找最近的下一个子句
- for (const marker of endMarkers) {
- const pos = sqlUpper.indexOf(marker, clauseStartPos + 1);
- if (pos > -1 && pos < endPos) {
- endPos = pos;
- }
- }
-
- return endPos;
- },
-
- // 显示提示消息
- showToastMessage(message, type = 'info') {
- this.toastMessage = message;
- this.toastType = type;
- this.showToast = true;
- // 3秒后自动隐藏
- setTimeout(() => {
- this.showToast = false;
- }, 3000);
- },
- }
- });
- </script>
- </body>
- </html>
|