25 lines
14 KiB
JavaScript
25 lines
14 KiB
JavaScript
"use strict";exports.id=2282,exports.ids=[2282],exports.modules={67619:(e,a,t)=>{t.r(a),t.d(a,{default:()=>i});var l=t(29021),r=t.n(l);async function i({user:e,message:a,component:t,noMail:l,req:i}){let n=new Date,d=(()=>{if(!i)return null;try{let e=i.headers["x-forwarded-for"],a=i.headers["x-real-ip"],t=i.headers["cf-connecting-ip"],l=Array.isArray(e)?e[0]:e?.split(",")[0],r=t||l||a||i.socket.remoteAddress;if(!r)return null;return String(r)}catch(e){return null}})();try{let l=`🚀 SERVER ERROR ===========================
|
|
Error Message: ${a}
|
|
Component: ${t}`;e?.id&&e?.first_name&&e?.last_name&&e?.email&&(l+=`
|
|
User Id: ${e?.id}
|
|
User Name: ${e?.first_name} ${e?.last_name}
|
|
User Email: ${e?.email}`),i?.url&&(l+=`
|
|
URL: ${i.url}`),i?.body&&(l+=`
|
|
Request Body: ${JSON.stringify(i.body,null,4)}`),d&&(l+=`
|
|
IP: ${d}`),l+=`
|
|
Date: ${n.toDateString()}
|
|
========================================`,r().existsSync("./.tmp/error.log")||r().writeFileSync("./.tmp/error.log","","utf-8");let o=r().readFileSync("./.tmp/error.log","utf-8");r().writeFileSync("./.tmp/error.log",l),r().appendFileSync("./.tmp/error.log",`
|
|
|
|
|
|
|
|
|
|
${o}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},95969:(e,a,t)=>{t.d(a,{A:()=>i});var l=t(55511),r=t(79428);function i({encryptedString:e,encryptionKey:a,encryptionSalt:t}){if(!e?.match(/./))return console.log("Encrypted string is invalid"),e;let i=a||process.env.DSQL_ENCRYPTION_PASSWORD,n=t||process.env.DSQL_ENCRYPTION_SALT,d=process.env.DSQL_ENCRYPTION_KEY_LENGTH?Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH):24;if(!i?.match(/.{8,}/))return console.log("Decrption key is invalid"),e;if(!n?.match(/.{8,}/))return console.log("Decrption salt is invalid"),e;let o=(0,l.scryptSync)(i,n,d),s=r.Buffer.alloc(16,0),u=(0,l.createDecipheriv)("aes-192-cbc",o,s);try{let a=u.update(e,"hex","utf8");return a+=u.final("utf8")}catch(a){return console.log("Error in decrypting =>",a.message),e}}},76856:(e,a,t)=>{t.d(a,{A:()=>T});var l=t(33873),r=t.n(l),i=t(29021),n=t.n(i),d=t(66866),o=t(41864);async function s({queryString:e,queryValuesArray:a}){let t;try{t=e&&a&&Array.isArray(a)&&a[0]?await (0,o.A)({query:e,values:a}):await (0,o.A)({query:e})}catch(e){console.log("Shell Vardb Error =>",e.message)}return t}function u({columnData:e,primaryKeySet:a}){let{fieldName:t,dataType:l,nullValue:r,primaryKey:i,autoIncrement:n,defaultValue:d,defaultValueLiteral:o,onUpdateLiteral:s,notNullValue:u}=e,E="";return E+=`\`${t}\` ${l}`,r?E+=" DEFAULT NULL":o?E+=` DEFAULT ${o}`:d?String(d).match(/uuid\(\)/i)?E+=" DEFAULT UUID()":E+=` DEFAULT '${d}'`:u&&(E+=" NOT NULL"),s&&(E+=` ON UPDATE ${s}`),i&&!a&&(E+=" PRIMARY KEY",a=!0),n&&(E+=" AUTO_INCREMENT",a=!0),{fieldEntryText:E,newPrimaryKeySet:a||!1}}async function E({dbFullName:e,tableName:a,tableInfoArray:l,tableSchema:r,recordedDbEntry:i}){let n=function({tableInfoArray:e}){let a=t(95610),l=e.filter(e=>e.primaryKey);return a.forEach(a=>{let t=e.filter(e=>e.fieldName===a.fieldName);t&&t[0]||("id"!==a.fieldName||l[0]?e.push(a):e.unshift(a))}),e}({tableInfoArray:l}),d=[];d.push(`CREATE TABLE IF NOT EXISTS \`${e}\`.\`${a}\` (`);try{if(!i)throw Error("Recorded Db entry not found!");let e=await s({queryString:"SELECT * FROM datasquirel.user_database_tables WHERE db_id = ? AND table_slug = ?",queryValuesArray:[i.id,r?.tableName]}),a=e?.[0];a?.id||await (0,o.A)({query:"INSERT INTO datasquirel.user_database_tables SET ?",values:{user_id:i.user_id,db_id:i.id,db_slug:i.db_slug,table_name:r?.tableFullName,table_slug:r?.tableName,child_table:r?.childTable?"1":null,child_table_parent_database:r?.childTableDbFullName||null,child_table_parent_table:r?.childTableName||null,date_created:Date(),date_created_code:Date.now(),date_updated:Date(),date_updated_code:Date.now()}})}catch(e){}let E=!1,c=[];for(let e=0;e<n.length;e++){let a=n[e],{fieldName:t,dataType:l,nullValue:r,primaryKey:i,autoIncrement:o,defaultValue:s,defaultValueLiteral:N,foreignKey:f,updatedField:T,onUpdate:_,onUpdateLiteral:m,onDelete:A,onDeleteLiteral:S,defaultField:b,encrypted:g,json:y,newTempField:D,notNullValue:R,originName:p,plainText:$,pattern:h,patternFlags:O,richText:L}=a;f&&c.push({...a});let{fieldEntryText:I,newPrimaryKeySet:C}=u({columnData:a,primaryKeySet:E});E=C;let M=c[0]?",":e===n.length-1?"":",";d.push(" "+I+M)}c[0]&&c.forEach((e,a,t)=>{let l=e.fieldName,r=e.foreignKey?.destinationTableName,i=e.foreignKey?.destinationTableColumnName,n=e.foreignKey?.cascadeDelete,o=e.foreignKey?.cascadeUpdate,s=e.foreignKey?.foreignKeyName,u=a===c.length-1?"":",";d.push(` CONSTRAINT \`${s}\` FOREIGN KEY (\`${l}\`) REFERENCES \`${r}\`(${i})${n?" ON DELETE CASCADE":""}${o?" ON UPDATE CASCADE":""}${u}`)}),d.push(") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;");let N=d.join("\n");return await s({queryString:N})}let c=/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;async function N({dbFullName:e,tableName:a,tableInfoArray:t,userId:l,dbSchema:r,tableIndexes:i,tableSchema:d,clone:E,childDb:N,tableIndex:f,tableNameFull:T,recordedDbEntry:_}){let m=[],A=t;try{let t=[];if(t.push(`ALTER TABLE \`${e}\`.\`${a}\``),N)try{if(!_)throw Error("Recorded Db entry not found!");let e=await s({queryString:"SELECT * FROM datasquirel.user_database_tables WHERE db_id = ? AND table_slug = ?",queryValuesArray:[_.id,a]}),t=e?.[0];t?.id||await (0,o.A)({query:"INSERT INTO datasquirel.user_database_tables SET ?",values:{user_id:_.user_id,db_id:_.id,db_slug:_.db_slug,table_name:T,table_slug:a,child_table:d?.childTable?"1":null,child_table_parent_database:d?.childTableDbFullName||null,child_table_parent_table:d.childTableName||null,date_created:Date(),date_created_code:Date.now(),date_updated:Date(),date_updated_code:Date.now()}})}catch(e){}let f=await s({queryString:`SHOW INDEXES FROM \`${e}\`.\`${a}\``}),S=await s({queryString:`SHOW COLUMNS FROM \`${e}\`.\`${a}\``}),b=[];for(let t=0;t<S.length;t++){let{Field:i}=S[t];if(i.match(c))continue;let d=A.filter(e=>e.fieldName===i||e.originName===i);if(d&&d[0]){if(d[0].updatedField&&d[0].fieldName){b.push(d[0].fieldName),await s({queryString:`ALTER TABLE \`${e}\`.\`${a}\` RENAME COLUMN \`${d[0].originName}\` TO \`${d[0].fieldName}\``}),console.log(`Column Renamed from "${d[0].originName}" to "${d[0].fieldName}"`);try{let t=r.findIndex(a=>a.dbFullName===e),i=r[t].tables.findIndex(e=>e.tableName===a),o=r[t].tables[i].fields.findIndex(e=>e.fieldName===d[0].fieldName);delete r[t].tables[i].fields[o].originName,delete r[t].tables[i].fields[o].updatedField,A=r[t].tables[i].fields,n().writeFileSync(`${String(process.env.DSQL_USER_DB_SCHEMA_PATH)}/user-${l}/main.json`,JSON.stringify(r),"utf8")}catch(e){console.log("Update table error =>",e.message)}}continue}await s({queryString:`ALTER TABLE \`${e}\`.\`${a}\` DROP COLUMN \`${i}\``})}for(let t=0;t<f.length;t++){let{Key_name:l,Index_comment:r}=f[t];if(r?.match(/schema_index/))try{let e=i?.filter(e=>e.alias===l);if(!e?.[0])throw Error(`This Index(${l}) Has been Deleted!`)}catch(t){await s({queryString:`ALTER TABLE \`${e}\`.\`${a}\` DROP INDEX \`${l}\``})}}if(i&&i[0])for(let t=0;t<i.length;t++){let{indexType:l,indexName:r,indexTableFields:n,alias:d}=i[t];if(d?.match(/./))try{if(!f.filter(e=>e.Key_name===d)[0])throw Error("This Index Does not Exist")}catch(t){await s({queryString:`CREATE${l?.match(/fullText/i)?" FULLTEXT":""} INDEX \`${d}\` ON \`${e}\`.\`${a}\`(${n?.map(e=>e.value).map(e=>`\`${e}\``).join(",")}) COMMENT 'schema_index'`})}}let g=await s({queryString:`SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${e}' AND TABLE_NAME='${a}' AND CONSTRAINT_TYPE='FOREIGN KEY'`});if(g)for(let t=0;t<g.length;t++){let{CONSTRAINT_NAME:l}=g[t];l.match(/PRIMARY/)||await s({queryString:`ALTER TABLE \`${e}\`.\`${a}\` DROP FOREIGN KEY \`${l}\``})}for(let r=0;r<A.length;r++){let i;let n=A[r],d=A[r-1],o=A[r+1],{fieldName:c,dataType:N,nullValue:f,primaryKey:T,autoIncrement:_,defaultValue:b,defaultValueLiteral:g,foreignKey:y,updatedField:D}=n;if(c?.match(/^id$|^date_/))continue;let R="",p=S&&S[0]?S.filter((e,a)=>{if(e.Field===c)return i=a,!0}):null,{fieldEntryText:$}=u({columnData:n});if(p&&p[0]?.Field){let{Field:e,Type:a,Null:t,Key:n,Default:s,Extra:u}=p[0],E=r<i;(e!==c||E||N?.toUpperCase()!==a.toUpperCase())&&l?R+=`MODIFY COLUMN ${$}${E?d?.fieldName?" AFTER `"+d.fieldName+"`":o?.fieldName?" BEFORE `"+o.fieldName+"`":"":""}`:R+=`MODIFY COLUMN ${$}`}else d&&d.fieldName?R+=`ADD COLUMN ${$} AFTER \`${d.fieldName}\``:o&&o.fieldName?R+=`ADD COLUMN ${$} BEFORE \`${o.fieldName}\``:R+=`ADD COLUMN ${$}`;if(t.push(R+","),!E&&y){let{destinationTableName:t,destinationTableColumnName:l,cascadeDelete:r,cascadeUpdate:i,foreignKeyName:n}=y,d=`ADD CONSTRAINT \`${n}\` FOREIGN KEY (\`${c}\`) REFERENCES \`${t}\`(\`${l}\`)${r?" ON DELETE CASCADE":""}${i?" ON UPDATE CASCADE":""}`,o=`ALTER TABLE \`${e}\`.\`${a}\` ${d}`,u=await s({queryString:o});u?.serverStatus||m.push(u)}}let y=t.join(" ").replace(/,$/,"");if(t.length>1)return await s({queryString:y});return"No Changes Made to Table"}catch(e){return console.log('Error in "updateTable" shell function =>',e.message),"Error in Updating Table"}}var f=t(59338);async function T({userId:e,targetDatabase:a,dbSchemaData:t}){console.log("///////////////////////////////"),console.log("///////////////////////////////"),console.log("Rebuilding Database ..."),console.log("process.env.DSQL_DB_HOST",process.env.DSQL_DB_HOST),console.log("process.env.DSQL_DB_USERNAME",process.env.DSQL_DB_USERNAME),console.log("process.env.DSQL_DB_PASSWORD",process.env.DSQL_DB_PASSWORD),console.log("process.env.DSQL_DB_NAME",process.env.DSQL_DB_NAME);let l=e?r().join(String(process.env.DSQL_USER_DB_SCHEMA_PATH),`/user-${e}/main.json`):r().resolve(__dirname,"../../jsonData/dbSchemas/main.json"),i=t||f.A.parse(n().readFileSync(l,"utf8"));if(!i){console.log("Schema Not Found!");return}for(let t=0;t<i.length;t++){let l=i[t],{dbFullName:r,tables:n,dbName:u,dbSlug:c,childrenDatabases:f}=l;if(a&&r!=a)continue;let _=await (0,d.A)(`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${r}'`);_?.[0]?.dbFullName||await (0,d.A)(`CREATE DATABASE IF NOT EXISTS \`${r}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);let m=await (0,d.A)(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${r}'`);for(let a=0;a<m.length;a++){let{TABLE_NAME:t}=m[a];if(!n.filter(e=>e.tableName===t)[0]){let a=n.filter(e=>e.tableNameOld&&e.tableNameOld===t);a&&a[0]?(console.log("Renaming Table"),await s({queryString:`RENAME TABLE \`${r}\`.\`${a[0].tableNameOld}\` TO \`${a[0].tableName}\``})):(console.log(`Dropping Table from ${r}`),await s({queryString:`DROP TABLE \`${r}\`.\`${t}\``}),await (0,o.A)({query:"DELETE FROM datasquirel.user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?",values:[e,c,t]}))}}let A=e?await s({queryString:"SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?",queryValuesArray:[r]}):void 0,S=A?.[0];for(let a=0;a<n.length;a++){let t=n[a],{tableName:d,fields:o,indexes:u}=t,c=await s({queryString:`
|
|
SELECT EXISTS (
|
|
SELECT
|
|
TABLE_NAME
|
|
FROM
|
|
information_schema.TABLES
|
|
WHERE
|
|
TABLE_SCHEMA = ? AND
|
|
TABLE_NAME = ?
|
|
) AS tableExists`,queryValuesArray:[r,t.tableName]});if(c&&c[0]?.tableExists>0){if(await N({dbFullName:r,tableName:d,tableNameFull:t.tableFullName,tableInfoArray:o,userId:e,dbSchema:i,tableIndexes:u,tableIndex:a,childDb:l.childDatabase||void 0,recordedDbEntry:S,tableSchema:t}),t.childrenTables&&t.childrenTables[0])for(let a=0;a<t.childrenTables.length;a++){let r=t.childrenTables[a];await N({dbFullName:r.dbNameFull,tableName:r.tableName,tableNameFull:r.tableNameFull,tableInfoArray:o,userId:e,dbSchema:i,tableIndexes:u,clone:!0,childDb:l.childDatabase||void 0,recordedDbEntry:S,tableSchema:t})}}else if(await E({tableName:d,tableInfoArray:o,dbFullName:r,tableSchema:t,recordedDbEntry:S}),u&&u[0]&&u&&u[0])for(let e=0;e<u.length;e++){let{indexType:a,indexName:t,indexTableFields:l,alias:i}=u[e];if(i?.match(/./))try{if(!(await s({queryString:`SHOW INDEXES FROM \`${r}\`.\`${d}\``})).filter(e=>e.Key_name===i)[0])throw Error("This Index Does not Exist")}catch(e){await s({queryString:`CREATE${a?.match(/fullText/i)?" FULLTEXT":""} INDEX \`${i}\` ON \`${r}\`.\`${d}\`(${l?.map(e=>e.value).map(e=>`\`${e}\``).join(",")}) COMMENT 'schema_index'`})}}}if(f?.[0])for(let a=0;a<f.length;a++){let{dbFullName:t}=f[a];await T({userId:e,targetDatabase:t})}}console.log("Database Successfully Rebuilt!"),console.log("///////////////////////////////"),console.log("///////////////////////////////")}},41864:(e,a,t)=>{t.d(a,{A:()=>d});var l=t(29021),r=t.n(l),i=t(33873),n=t.n(i);async function d({query:e,values:a}){let t,l=global.DSQL_DB_CONN;try{t=e&&a?await l.query(e,a):await l.query(e)}catch(e){if(process.env.FIRST_RUN)return null;console.log("ERROR in dbHandler =>",e.message),console.log(e),console.log(l.config()),r().appendFileSync(n().resolve(__dirname,"../.tmp/dbErrorLogs.txt"),JSON.stringify(e,null,4)+"\n"+Date()+"\n\n\n","utf8"),t=null}finally{await l?.end()}return t?JSON.parse(JSON.stringify(t)):null}},66866:(e,a,t)=>{t.d(a,{A:()=>r});var l=t(41864);async function r(e){let a;try{a=await (0,l.A)({query:e})}catch(e){console.log("ERROR in noDatabaseDbHandler =>",e.message)}return a||null}},59338:(e,a,t)=>{t.d(a,{A:()=>l});let l={parse:function(e,a){if(e){if("object"==typeof e)return e;if("string"==typeof e)try{return JSON.parse(e,a)}catch(e){return}}},stringify:function(e,a,t){try{return JSON.stringify(e,a||void 0,t)}catch(e){return}}}},95610:e=>{e.exports=JSON.parse('[{"fieldName":"id","dataType":"BIGINT","notNullValue":true,"primaryKey":true,"autoIncrement":true},{"fieldName":"uuid","dataType":"UUID","defaultValueLiteral":"UUID()"},{"fieldName":"date_created","dataType":"VARCHAR(250)","nullValue":true},{"fieldName":"date_created_code","dataType":"BIGINT","nullValue":true},{"fieldName":"date_created_timestamp","dataType":"TIMESTAMP","defaultValueLiteral":"CURRENT_TIMESTAMP"},{"fieldName":"date_updated","dataType":"VARCHAR(250)","nullValue":true},{"fieldName":"date_updated_code","dataType":"BIGINT","nullValue":true},{"fieldName":"date_updated_timestamp","dataType":"TIMESTAMP","defaultValueLiteral":"CURRENT_TIMESTAMP","onUpdateLiteral":"CURRENT_TIMESTAMP"}]')}}; |