| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165 |
- <!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;
- border-bottom: 1px solid #EEEEEE;
- background: white;
- width: 100%;
- justify-content: center;
- }
- .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: 300px;
- 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: column;
- }
-
- .column-item:hover {
- background-color: #F0F7FF;
- }
-
- .column-name {
- font-weight: bold;
- }
-
- .column-type {
- font-size: 12px;
- color: #666;
- }
-
- .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;
- }
- .table-container {
- width: 100%;
- overflow-x: auto;
- }
- .data-table {
- width: 100%;
- border-collapse: collapse;
- font-size: 14px;
- }
- .data-table th {
- background: #F5F5F5;
- padding: 10px;
- text-align: left;
- border: 1px solid #DDDDDD;
- position: sticky;
- top: 0;
- z-index: 10;
- }
- .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;
- }
- .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;
- 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;
- }
- </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" @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-left">
- <textarea class="sql-textarea" v-model="sqlQuery" placeholder="输入SQL查询语句..."></textarea>
- <div class="btn-group">
- <button type="button" class="btn btn-default" @click="clearQuery">清空</button>
- <button type="button" class="btn btn-primary" @click="executeQuery">执行</button>
- </div>
- </div>
-
- <!-- 右侧字段列表 -->
- <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="insertColumnName(column.name)">
- <div class="column-name">{{ column.name }}</div>
- <div class="column-type">{{ column.type }}</div>
- <div class="column-comment" v-if="column.comment">{{ column.comment }}</div>
- </div>
- </div>
- <div v-else class="no-data">
- 请选择表格查看字段列表
- </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="queryResults && queryResults.length > 0" class="table-container">
- <table class="data-table">
- <thead>
- <tr>
- <th v-for="(column, index) in tableColumns" :key="index">{{ column }}</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="(row, rowIndex) in queryResults" :key="rowIndex">
- <td v-for="(column, colIndex) in tableColumns" :key="colIndex">
- {{ row[column] }}
- </td>
- </tr>
- </tbody>
- </table>
-
- <!-- 分页控件 -->
- <div class="pagination" v-if="totalPages > 1">
- <button class="pagination-btn"
- :class="{ disabled: currentPage === 1 }"
- @click="changePage(1)">
- 首页
- </button>
- <button class="pagination-btn"
- :class="{ disabled: currentPage === 1 }"
- @click="changePage(currentPage - 1)">
- 上一页
- </button>
- <button v-for="page in displayedPages"
- :key="page"
- class="pagination-btn"
- :class="{ active: currentPage === page }"
- @click="changePage(page)">
- {{ page }}
- </button>
- <button class="pagination-btn"
- :class="{ disabled: currentPage === totalPages }"
- @click="changePage(currentPage + 1)">
- 下一页
- </button>
- <button class="pagination-btn"
- :class="{ disabled: currentPage === totalPages }"
- @click="changePage(totalPages)">
- 末页
- </button>
- </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>
- <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,
- currentPage: 1,
- pageSize: 100,
- totalPages: 1,
- allResults: [],
- tableColumnsList: [] // 存储表格字段列表
- },
- computed: {
- displayedPages() {
- const pages = [];
- const maxVisiblePages = 5;
-
- let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
- let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
-
- if (endPage - startPage + 1 < maxVisiblePages) {
- startPage = Math.max(1, endPage - maxVisiblePages + 1);
- }
-
- for (let i = startPage; i <= endPage; i++) {
- pages.push(i);
- }
-
- return pages;
- }
- },
- 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;
-
- // 检查是否在本地环境
- if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
- //console.log('在本地环境中使用模拟数据');
- // 模拟数据用于开发测试
- this.tables = [
- 'users', 'products', 'orders', 'categories',
- 'customers', 'suppliers', 'inventory', 'payments',
- 'shipping', 'reviews', 'logs', 'settings'
- ];
-
- // 模拟表格注释
- this.tableComments = {
- 'users': '用户信息表',
- 'products': '产品信息表',
- 'orders': '订单信息表',
- 'categories': '分类信息表',
- 'customers': '客户信息表'
- };
-
- this.filteredTables = [...this.tables];
- }
- });
- },
-
- // 搜索表格
- 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;
- this.sqlQuery = `SELECT * FROM ${table} LIMIT 100;`;
-
- // 获取表格字段列表
- this.loadTableColumns(table);
- },
-
- // 加载表格字段列表
- 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;
-
- // 模拟数据用于开发测试
- if (tableName === 'users') {
- this.tableColumnsList = [
- { name: 'id', type: 'int(11)', comment: '用户ID' },
- { name: 'username', type: 'varchar(50)', comment: '用户名' },
- { name: 'email', type: 'varchar(100)', comment: '电子邮箱' },
- { name: 'password', type: 'varchar(255)', comment: '密码' },
- { name: 'created_at', type: 'datetime', comment: '创建时间' },
- { name: 'status', type: 'tinyint(1)', comment: '状态' }
- ];
- } else if (tableName === 'products') {
- this.tableColumnsList = [
- { name: 'id', type: 'int(11)', comment: '产品ID' },
- { name: 'name', type: 'varchar(100)', comment: '产品名称' },
- { name: 'price', type: 'decimal(10,2)', comment: '价格' },
- { name: 'category_id', type: 'int(11)', comment: '分类ID' },
- { name: 'stock', type: 'int(11)', comment: '库存' },
- { name: 'description', type: 'text', comment: '产品描述' }
- ];
- } else {
- this.tableColumnsList = [
- { name: 'id', type: 'int(11)', comment: '主键ID' },
- { name: 'name', type: 'varchar(100)', comment: '名称' },
- { name: 'description', type: 'text', comment: '描述' },
- { name: 'created_at', type: 'datetime', comment: '创建时间' }
- ];
- }
- });
- },
-
- // 清空查询
- clearQuery() {
- this.sqlQuery = '';
- },
-
- // 插入字段名称到SQL查询
- insertColumnName(columnName) {
- // 获取文本框元素
- const textarea = document.querySelector('.sql-textarea');
-
- // 如果文本框存在
- 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 + columnName + textAfter;
-
- // 设置新的光标位置
- this.$nextTick(() => {
- textarea.focus();
- textarea.selectionStart = startPos + columnName.length;
- textarea.selectionEnd = startPos + columnName.length;
- });
- } else {
- // 如果无法获取文本框元素,则直接在末尾添加
- this.sqlQuery += ' ' + columnName;
- }
- },
-
- // 执行查询
- executeQuery() {
- if (!this.sqlQuery.trim()) {
- this.showToastMessage('请输入SQL查询语句', 'info');
- return;
- }
-
- this.isQueryLoading = true;
- this.queryExecuted = true;
- this.currentPage = 1;
-
- // 这里应该调用后端API执行SQL查询
- fetch('/api/ExecuteSqlQuery', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- query: this.sqlQuery
- })
- })
- .then(response => response.json())
- .then(data => {
- if (data && data.result) {
- this.processQueryResults(data.result);
- } else {
- this.queryResults = [];
- this.tableColumns = [];
- this.showToastMessage('查询未返回数据', 'info');
- }
- this.isQueryLoading = false;
- })
- .catch(error => {
- this.showToastMessage('执行查询失败,请稍后重试', 'error');
- this.isQueryLoading = false;
-
- // 模拟数据用于开发测试
- if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
- console.log('在本地环境中使用模拟数据');
-
- // 根据选择的表格生成模拟数据
- let mockData = [];
-
- if (this.selectedTable === 'users') {
- mockData = [
- { id: 1, username: 'admin', email: 'admin@example.com', password: '******', created_at: '2023-01-01 00:00:00', status: 1 },
- { id: 2, username: 'user1', email: 'user1@example.com', password: '******', created_at: '2023-01-02 10:30:00', status: 1 },
- { id: 3, username: 'user2', email: 'user2@example.com', password: '******', created_at: '2023-01-03 15:45:00', status: 0 }
- ];
- } else if (this.selectedTable === 'products') {
- mockData = [
- { id: 1, name: '产品A', price: '99.99', category_id: 1, stock: 100, description: '这是产品A的描述' },
- { id: 2, name: '产品B', price: '199.99', category_id: 2, stock: 50, description: '这是产品B的描述' },
- { id: 3, name: '产品C', price: '299.99', category_id: 1, stock: 75, description: '这是产品C的描述' }
- ];
- } else {
- // 生成通用模拟数据
- for (let i = 1; i <= 10; i++) {
- mockData.push({
- id: i,
- name: `示例名称 ${i}`,
- description: `这是示例描述 ${i}`,
- created_at: new Date().toISOString().slice(0, 19).replace('T', ' ')
- });
- }
- }
-
- this.processQueryResults(mockData);
- }
- });
- },
-
- // 处理查询结果
- processQueryResults(results) {
- if (!results || !Array.isArray(results) || results.length === 0) {
- this.queryResults = [];
- this.tableColumns = [];
- this.allResults = [];
- this.totalPages = 1;
- return;
- }
-
- // 存储所有结果
- this.allResults = [...results];
-
- // 提取表格列
- this.tableColumns = Object.keys(results[0]);
-
- // 计算总页数
- this.totalPages = Math.ceil(results.length / this.pageSize);
-
- // 显示第一页数据
- this.changePage(1);
-
- this.showToastMessage(`查询成功,返回 ${results.length} 条记录`, 'success');
- },
-
- // 切换页面
- changePage(page) {
- if (page < 1 || page > this.totalPages || page === this.currentPage) {
- return;
- }
-
- this.currentPage = page;
-
- // 计算当前页的数据
- const startIndex = (page - 1) * this.pageSize;
- const endIndex = Math.min(startIndex + this.pageSize, this.allResults.length);
-
- this.queryResults = this.allResults.slice(startIndex, endIndex);
- },
-
- // 显示提示消息
- showToastMessage(message, type = 'info') {
- this.toastMessage = message;
- this.toastType = type;
- this.showToast = true;
-
- // 3秒后自动隐藏
- setTimeout(() => {
- this.showToast = false;
- }, 3000);
- }
- }
- });
- </script>
- </body>
- </html>
|