index.uts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import Cursor from 'android.database.Cursor';
  2. import SQLiteDatabase from 'android.database.sqlite.SQLiteDatabase';
  3. import SQLiteOpenHelper from 'android.database.sqlite.SQLiteOpenHelper';
  4. import Environment from 'android.os.Environment';
  5. import { createSQLiteContextOptions, executeSqlOptions, selectSqlOptions, executeSqlOptionsResult, selectSqlOptionsResult, CreateSQLiteContext, transactionOptions, transactionResult, ICreateSQLiteContextError } from '../interface.uts';
  6. //import { createSQLiteContextOptions, executeSqlOptions, selectSqlOptions, transactionOptions } from '../interface.uts';
  7. import { createSQLiteContextFailImpl } from '../unierror.uts';
  8. class SQLiteContext extends SQLiteOpenHelper {
  9. private dbName: string | null;
  10. private forceRecreateTables: boolean;
  11. constructor(name: string, forceRecreate: boolean = false) {
  12. // 使用应用内部存储路径而不是静态资源路径
  13. const context = UTSAndroid.getAppContext()!!;
  14. // 版本号 - 必须在super调用前定义
  15. const dbPath = context.getDatabasePath(name).getAbsolutePath();
  16. console.log("Creating database at: " + dbPath);
  17. // 只有在明确需要强制重新创建表时,才删除现有数据库
  18. if (forceRecreate) {
  19. console.log("Force recreating tables requested, deleting existing database if exists");
  20. context.deleteDatabase(name);
  21. }
  22. //1版本号
  23. super(UTSAndroid.getAppContext()!!, name, null, 1);
  24. this.dbName = name;
  25. this.forceRecreateTables = forceRecreate;
  26. // 立即获取可写数据库以触发初始化
  27. console.log("Initializing database connection");
  28. this.getWritableDatabase();
  29. }
  30. override onCreate(db: SQLiteDatabase):void {
  31. console.log("SQLiteContext onCreate() called - creating database tables");
  32. // 创建表结构的DDL语句
  33. // 这里可以根据实际需要添加更多的CREATE TABLE语句
  34. const createTableSQLs = [
  35. // app_user表结构
  36. `CREATE TABLE IF NOT EXISTS app_user (
  37. id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  38. username TEXT NOT NULL,
  39. name TEXT,
  40. userno INTEGER,
  41. password TEXT NOT NULL,
  42. token TEXT,
  43. status INTEGER DEFAULT 1,
  44. avatar TEXT,
  45. createtime TEXT,
  46. createuser INTEGER,
  47. updatetime TEXT,
  48. updateuser INTEGER,
  49. role TEXT DEFAULT 'user',
  50. UNIQUE (username ASC),
  51. UNIQUE (userno ASC)
  52. )`,
  53. // 日志表
  54. `CREATE TABLE "app_log" (
  55. "id" INTEGER NOT NULL UNIQUE,
  56. "module" text,
  57. "dataid" INTEGER,
  58. "content" text,
  59. "status" text,
  60. "params" text,
  61. "createtime" text,
  62. "createuser" integer,
  63. "updatetime" text,
  64. "updateuser" integer,
  65. PRIMARY KEY("id" AUTOINCREMENT)
  66. )`,
  67. // 媒体信息表
  68. `CREATE TABLE "app_media_info" (
  69. "pdid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  70. "workorder" TEXT,
  71. "invname" TEXT,
  72. "productno" TEXT,
  73. "cardno" TEXT,
  74. "model" TEXT,
  75. "graphid" TEXT,
  76. "ver" TEXT,
  77. "phase" TEXT,
  78. "processno" TEXT,
  79. "progress" TEXT,
  80. "status" INTEGER,
  81. "createtime" TEXT,
  82. "createuser" text,
  83. "updatetime" TEXT,
  84. "updateuser" text,
  85. "uploadFlag" integer DEFAULT 0,
  86. "uploadtime" text,
  87. UNIQUE ("pdid" ASC)
  88. )`,
  89. // 媒体记录表
  90. `CREATE TABLE "app_media_record" (
  91. "sxid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  92. "senum" TEXT,
  93. "photoitem" TEXT,
  94. "productno" TEXT,
  95. "part" TEXT,
  96. "partno" TEXT,
  97. "pk" TEXT,
  98. "exampleid" text,
  99. "descb" TEXT,
  100. "num" INTEGER,
  101. "status" INTEGER NOT NULL,
  102. "date" TEXT,
  103. "urlspl" TEXT,
  104. "imgname" TEXT,
  105. "urlpdt" TEXT,
  106. "createtime" TEXT,
  107. "createuser" text,
  108. "updatetime" TEXT,
  109. "updateuser" text,
  110. "pid" INTEGER,
  111. "uploadFlag" integer NOT NULL DEFAULT 0,
  112. UNIQUE ("sxid" ASC)
  113. )`,
  114. // 媒体任务表
  115. `CREATE TABLE "app_media_task" (
  116. "id" INTEGER NOT NULL UNIQUE,
  117. "pid" INTEGER NOT NULL,
  118. "name" TEXT,
  119. "num" INTEGER,
  120. "step" INTEGER,
  121. "status" INTEGER NOT NULL DEFAULT 1,
  122. "createtime" TEXT,
  123. "createuser" INTEGER,
  124. "updatetime" TEXT,
  125. "updateuser" INTEGER DEFAULT 1,
  126. PRIMARY KEY("id" AUTOINCREMENT)
  127. )`,
  128. // 操作日志表
  129. `CREATE TABLE "app_operate_log" (
  130. "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  131. "module" text,
  132. "title" text,
  133. "content" text,
  134. "msg" text,
  135. "createtime" text,
  136. "createuser" text,
  137. UNIQUE ("id" ASC)
  138. )`,
  139. // 产品表
  140. `CREATE TABLE "app_product" (
  141. "pdid" integer NOT NULL UNIQUE,
  142. "productno" text,
  143. "cardno" text,
  144. "model" text,
  145. "workorder" text,
  146. "invname" text,
  147. "graphid" text,
  148. "processno" text,
  149. "ver" text,
  150. "phase" text,
  151. "progress" TEXT,
  152. "status" text NOT NULL DEFAULT 1,
  153. "createtime" text,
  154. "createuser" integer NOT NULL DEFAULT 1,
  155. "updatetime" text,
  156. "updateuser" integer NOT NULL DEFAULT 1,
  157. PRIMARY KEY("pdid" AUTOINCREMENT)
  158. )`,
  159. // 产品点位表
  160. `CREATE TABLE "app_product_points" (
  161. "sxid" INTEGER NOT NULL UNIQUE,
  162. "pid" INTEGER NOT NULL,
  163. "senum" INTEGER,
  164. "part" text,
  165. "photoitem" text,
  166. "desb" text,
  167. "partno" text,
  168. "num" INTEGER,
  169. "status" INTEGER NOT NULL DEFAULT 1,
  170. "urlspl" text,
  171. "imgname" text,
  172. "urlpdt" text,
  173. "createtime" TEXT,
  174. "createuser" integer,
  175. "updatetime" TEXT,
  176. "updateuser" integer,
  177. PRIMARY KEY("sxid" AUTOINCREMENT)
  178. )`,
  179. // 产品任务表
  180. `CREATE TABLE "app_product_task" (
  181. "id" INTEGER NOT NULL UNIQUE,
  182. "pid" INTEGER NOT NULL,
  183. "name" TEXT,
  184. "num" INTEGER,
  185. "step" INTEGER,
  186. "status" INTEGER NOT NULL DEFAULT 1,
  187. "createtime" TEXT,
  188. "createuser" INTEGER,
  189. "updatetime" TEXT,
  190. "updateuser" INTEGER DEFAULT 1,
  191. PRIMARY KEY("id" AUTOINCREMENT)
  192. )`,
  193. // 任务信息表
  194. `CREATE TABLE "app_task_info" (
  195. "pdid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  196. "gxpk" text,
  197. "pk_serial" text,
  198. "cardno" text,
  199. "productcode" text,
  200. "model" text,
  201. "workorder" text,
  202. "invname" text,
  203. "graphid" text,
  204. "processno" text,
  205. "gxno" text,
  206. "ver" text,
  207. "lastupdatetime" text,
  208. "updateuser" text,
  209. "uploadFlag" integer DEFAULT 0,
  210. "uploadtime" text
  211. )`,
  212. // 任务关键工序表
  213. `CREATE TABLE "app_task_keyprocess" (
  214. "sxid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  215. "pdid" INTEGER,
  216. "pk" text,
  217. "testapparatus" text,
  218. "tableid" text,
  219. "testrequirelower" text,
  220. "testrequireupper" text,
  221. "parametername" text,
  222. "parameterorder" text,
  223. "measureunit" text,
  224. "parameterinstruction" text,
  225. "parameterid" text,
  226. "fk_creator" text,
  227. "fk_prodcode" text,
  228. "prodno" text,
  229. "processstep" text,
  230. "fk_processtask" text,
  231. "measuredvaluemin" text,
  232. "measuredvaluemax" text,
  233. "result" TEXT,
  234. "memo" TEXT,
  235. "fks_operator" text,
  236. "cs" text,
  237. "ts" text,
  238. "operator" TEXT
  239. )`,
  240. // 任务照片表
  241. `CREATE TABLE "app_task_photo" (
  242. "sxid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  243. "pdid" INTEGER,
  244. "pk" text,
  245. "photographpoint" text,
  246. "photographdescription" text,
  247. "imgname" TEXT,
  248. "photourl" text,
  249. "exampleurl" text,
  250. "photoname" text,
  251. "fk_qcRecord" text,
  252. "fk_prodcode" text,
  253. "prodno" text,
  254. "fk_creator" text,
  255. "fks_operator" text,
  256. "operator" text,
  257. "processStep" text,
  258. "fk_processTask" text,
  259. "cs" text,
  260. "ts" text,
  261. "uploadFlag" integer NOT NULL DEFAULT 0
  262. )`,
  263. // 任务记录表
  264. `CREATE TABLE "app_task_record" (
  265. "sxid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  266. "pdid" INTEGER,
  267. "pk" text,
  268. "fk_invcode" text,
  269. "no" text,
  270. "invcode" text,
  271. "invname" text,
  272. "processStep" text,
  273. "fk_processTask" text,
  274. "checkTarget" text,
  275. "checknum" INTEGER,
  276. "oknum" INTEGER,
  277. "ngnum" INTEGER,
  278. "status" text,
  279. "result" text,
  280. "checkTime" text,
  281. "fk_creator" text,
  282. "cs" text,
  283. "ts" text
  284. )`,
  285. // 任务记录明细表
  286. `CREATE TABLE "app_task_record_item" (
  287. "sxid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  288. "psxid" INTEGER,
  289. "pk" text,
  290. "fk_qcRecord" text,
  291. "fk_prodcode" text,
  292. "prodno" text,
  293. "name" text,
  294. "no" text,
  295. "nature" text,
  296. "unit" text,
  297. "maxNum" text,
  298. "minNum" text,
  299. "status" text,
  300. "memo" text,
  301. "measuredvalue" text,
  302. "measuredvaluemax" TEXT,
  303. "result" text,
  304. "cs" text,
  305. "ts" text,
  306. "recorder" TEXT
  307. )`
  308. ];
  309. // 执行所有建表语句
  310. for (const sql of createTableSQLs) {
  311. try {
  312. db.execSQL(sql);
  313. console.log("Created table with SQL: " + sql.substring(0, 50) + "...");
  314. } catch (e) {
  315. console.error("Error creating table: " + e);
  316. }
  317. }
  318. // 插入初始数据
  319. console.log("Inserting initial data into app_user table");
  320. const insertDataSQLs = [
  321. `INSERT INTO "app_user" ("id", "username", "name", "userno", "password", "token", "status", "avatar", "createtime", "createuser", "updatetime", "updateuser", "role")
  322. VALUES (1, 'admin', '管理员', 1, 'admin123', 'token1', 1, NULL, NULL, 1, NULL, 1, 'admin');`,
  323. `INSERT INTO "app_user" ("id", "username", "name", "userno", "password", "token", "status", "avatar", "createtime", "createuser", "updatetime", "updateuser", "role")
  324. VALUES (2, 'xuyunliang', '许运良', 2, '123456', 'token1', 1, NULL, NULL, 1, NULL, 1, 'user');`
  325. ];
  326. for (const sql of insertDataSQLs) {
  327. try {
  328. // 使用INSERT OR IGNORE避免重复插入
  329. const safeSql = sql.replace("INSERT INTO", "INSERT OR IGNORE INTO");
  330. db.execSQL(safeSql);
  331. console.log("Inserted initial data successfully");
  332. } catch (e) {
  333. console.error("Error inserting initial data: " + e);
  334. }
  335. }
  336. }
  337. override onUpgrade(db: SQLiteDatabase, oldVersion:Int, newVersion:Int):void {
  338. console.log("Upgrading database from version " + oldVersion + " to " + newVersion);
  339. // 数据库版本升级逻辑
  340. if (oldVersion < 2) {
  341. // 版本2的升级操作
  342. }
  343. // 可以添加更多版本升级逻辑
  344. }
  345. public executeSql(options: executeSqlOptions) {
  346. const database: SQLiteDatabase = this.getWritableDatabase();
  347. const SqlArray = options.sql.split(';');
  348. let result: executeSqlOptionsResult = {
  349. data: [] as boolean[],
  350. errMsg: 'ok'
  351. }
  352. try {
  353. for (let i = 0; i < SqlArray.length; i++) {
  354. if (SqlArray[i].length > 0) {
  355. const sql = SqlArray[i].replace(/^\s+/, '');
  356. try {
  357. database.execSQL(sql);
  358. result.data.push(true);
  359. } catch(e:Error) {
  360. result.data.push(false);
  361. }
  362. }
  363. }
  364. options.success?.(result);
  365. } catch (e) {
  366. const err = new createSQLiteContextFailImpl(1000002);
  367. result.errMsg = err.errMsg;
  368. options.fail?.(result);
  369. }
  370. options.complete?.(result);
  371. return result;
  372. }
  373. public selectSql(options: selectSqlOptions) {
  374. const database: SQLiteDatabase = this.getReadableDatabase();
  375. const SqlArray = options.sql.split(';');
  376. let result: selectSqlOptionsResult = {
  377. data: [] as UTSJSONObject[],
  378. errMsg: 'ok',
  379. }
  380. try {
  381. for (let i = 0; i < SqlArray.length; i++) {
  382. if (SqlArray[i].length > 0) {
  383. const sql = SqlArray[i].replace(/^\s+/, '');
  384. try {
  385. const cursor: Cursor = database.rawQuery(sql, null);
  386. //获取查询结果的字符串并push到result.data中
  387. if (cursor.moveToFirst()) {
  388. do {
  389. const row = cursor.getColumnCount();
  390. const utsJsonObject = {} as UTSJSONObject;
  391. for (let j:Int = 0; j < row; j++) {
  392. //rowArray.push(cursor.getString(j)!=null? cursor.getString(j):'');
  393. //let obj = {cursor.getColumnName(j):cursor.getString(j)!=null? cursor.getString(j):''}
  394. //rowArray.push(obj)
  395. utsJsonObject.set(cursor.getColumnName(j).toString(), cursor.getString(j)!=null? cursor.getString(j):'')
  396. }
  397. result.data.push(utsJsonObject);
  398. } while (cursor.moveToNext());
  399. }
  400. cursor.close();
  401. } catch(e:Error) {
  402. console.log(e)
  403. result.data.push({});
  404. }
  405. }
  406. }
  407. options.success?.(result);
  408. } catch (e) {
  409. const err = new createSQLiteContextFailImpl(1000003);
  410. result.errMsg = err.errMsg;
  411. options.fail?.(result);
  412. }
  413. options.complete?.(result);
  414. return result;
  415. }
  416. /*
  417. public close(){
  418. const database: SQLiteDatabase = this.getReadableDatabase();
  419. database.close();
  420. } */
  421. public transaction(options: transactionOptions) {
  422. const database: SQLiteDatabase = this.getReadableDatabase();
  423. const transaction = options.operation;
  424. let result: transactionResult = {
  425. errMsg: 'transaction:ok',
  426. }
  427. try {
  428. if (transaction == 'begin') {
  429. //开启事务
  430. database.execSQL('BEGIN TRANSACTION');
  431. } else if (transaction == 'commit') {
  432. //提交事务
  433. database.execSQL('COMMIT');
  434. } else if (transaction == 'rollback') {
  435. //回滚事务
  436. database.execSQL('ROLLBACK');
  437. }
  438. options.success?.(result);
  439. } catch (e) {
  440. let errCode = 1000008;
  441. if (transaction == 'begin') {
  442. errCode = 1000004;
  443. } else if (transaction == 'commit') {
  444. errCode = 1000005;
  445. } else if (transaction == 'rollback') {
  446. errCode = 1000006;
  447. }
  448. const err = new createSQLiteContextFailImpl(errCode);
  449. const errInfo = {errMsg:err.errMsg } as transactionResult ;
  450. options.fail?.(errInfo);
  451. }
  452. let ret = {
  453. errMsg: result.errMsg as string
  454. } as UTSJSONObject
  455. options.complete?.(result);
  456. return ret;
  457. }
  458. }
  459. export const createSQLiteContext = function (dbName: string): SQLiteContext {
  460. // 确保数据库名称包含.db后缀
  461. const name = dbName.endsWith('.db') ? dbName : dbName + '.db';
  462. // 注意:根据接口定义,只接受一个参数,默认不强制重新创建表
  463. return new SQLiteContext(name, false);
  464. }