index.uts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. `INSERT INTO "app_user" ("id", "username", "name", "userno", "password", "token", "status", "avatar", "createtime", "createuser", "updatetime", "updateuser", "role")
  326. VALUES (3, 'chenpeng', '陈朋', 3, '123456', 'token1', 1, NULL, NULL, 1, NULL, 1, 'user');`,
  327. `INSERT INTO "app_user" ("id", "username", "name", "userno", "password", "token", "status", "avatar", "createtime", "createuser", "updatetime", "updateuser", "role")
  328. VALUES (4, 'lubing', '鲁兵', 4, '123456', 'token1', 1, NULL, NULL, 1, NULL, 1, 'user');`,
  329. `INSERT INTO "app_user" ("id", "username", "name", "userno", "password", "token", "status", "avatar", "createtime", "createuser", "updatetime", "updateuser", "role")
  330. VALUES (5, 'tianzhenyou', '田振友', 5, '123456', 'token1', 1, NULL, NULL, 1, NULL, 1, 'user');` ,
  331. `INSERT INTO "app_user" ("id", "username", "name", "userno", "password", "token", "status", "avatar", "createtime", "createuser", "updatetime", "updateuser", "role")
  332. VALUES (6, 'luyongjun', '陆永俊', 6, '123456', 'token1', 1, NULL, NULL, 1, NULL, 1, 'user');`
  333. ];
  334. for (const sql of insertDataSQLs) {
  335. try {
  336. // 使用INSERT OR IGNORE避免重复插入
  337. const safeSql = sql.replace("INSERT INTO", "INSERT OR IGNORE INTO");
  338. db.execSQL(safeSql);
  339. console.log("Inserted initial data successfully");
  340. } catch (e) {
  341. console.error("Error inserting initial data: " + e);
  342. }
  343. }
  344. }
  345. override onUpgrade(db : SQLiteDatabase, oldVersion : Int, newVersion : Int) : void {
  346. console.log("Upgrading database from version " + oldVersion + " to " + newVersion);
  347. // 数据库版本升级逻辑
  348. if (oldVersion < 2) {
  349. // 版本2的升级操作
  350. }
  351. // 可以添加更多版本升级逻辑
  352. }
  353. public executeSql(options : executeSqlOptions) {
  354. const database : SQLiteDatabase = this.getWritableDatabase();
  355. const SqlArray = options.sql.split(';');
  356. let result : executeSqlOptionsResult = {
  357. data: [] as boolean[],
  358. errMsg: 'ok'
  359. }
  360. try {
  361. for (let i = 0; i < SqlArray.length; i++) {
  362. if (SqlArray[i].length > 0) {
  363. const sql = SqlArray[i].replace(/^\s+/, '');
  364. try {
  365. database.execSQL(sql);
  366. result.data.push(true);
  367. } catch (e : Error) {
  368. result.data.push(false);
  369. }
  370. }
  371. }
  372. options.success?.(result);
  373. } catch (e) {
  374. const err = new createSQLiteContextFailImpl(1000002);
  375. result.errMsg = err.errMsg;
  376. options.fail?.(result);
  377. }
  378. options.complete?.(result);
  379. return result;
  380. }
  381. public selectSql(options : selectSqlOptions) {
  382. const database : SQLiteDatabase = this.getReadableDatabase();
  383. const SqlArray = options.sql.split(';');
  384. let result : selectSqlOptionsResult = {
  385. data: [] as UTSJSONObject[],
  386. errMsg: 'ok',
  387. }
  388. try {
  389. for (let i = 0; i < SqlArray.length; i++) {
  390. if (SqlArray[i].length > 0) {
  391. const sql = SqlArray[i].replace(/^\s+/, '');
  392. try {
  393. const cursor : Cursor = database.rawQuery(sql, null);
  394. //获取查询结果的字符串并push到result.data中
  395. if (cursor.moveToFirst()) {
  396. do {
  397. const row = cursor.getColumnCount();
  398. const utsJsonObject = {} as UTSJSONObject;
  399. for (let j : Int = 0; j < row; j++) {
  400. //rowArray.push(cursor.getString(j)!=null? cursor.getString(j):'');
  401. //let obj = {cursor.getColumnName(j):cursor.getString(j)!=null? cursor.getString(j):''}
  402. //rowArray.push(obj)
  403. utsJsonObject.set(cursor.getColumnName(j).toString(), cursor.getString(j) != null ? cursor.getString(j) : '')
  404. }
  405. result.data.push(utsJsonObject);
  406. } while (cursor.moveToNext());
  407. }
  408. cursor.close();
  409. } catch (e : Error) {
  410. console.log(e)
  411. result.data.push({});
  412. }
  413. }
  414. }
  415. options.success?.(result);
  416. } catch (e) {
  417. const err = new createSQLiteContextFailImpl(1000003);
  418. result.errMsg = err.errMsg;
  419. options.fail?.(result);
  420. }
  421. options.complete?.(result);
  422. return result;
  423. }
  424. /*
  425. public close(){
  426. const database: SQLiteDatabase = this.getReadableDatabase();
  427. database.close();
  428. } */
  429. public transaction(options : transactionOptions) {
  430. const database : SQLiteDatabase = this.getReadableDatabase();
  431. const transaction = options.operation;
  432. let result : transactionResult = {
  433. errMsg: 'transaction:ok',
  434. }
  435. try {
  436. if (transaction == 'begin') {
  437. //开启事务
  438. database.execSQL('BEGIN TRANSACTION');
  439. } else if (transaction == 'commit') {
  440. //提交事务
  441. database.execSQL('COMMIT');
  442. } else if (transaction == 'rollback') {
  443. //回滚事务
  444. database.execSQL('ROLLBACK');
  445. }
  446. options.success?.(result);
  447. } catch (e) {
  448. let errCode = 1000008;
  449. if (transaction == 'begin') {
  450. errCode = 1000004;
  451. } else if (transaction == 'commit') {
  452. errCode = 1000005;
  453. } else if (transaction == 'rollback') {
  454. errCode = 1000006;
  455. }
  456. const err = new createSQLiteContextFailImpl(errCode);
  457. const errInfo = { errMsg: err.errMsg } as transactionResult;
  458. options.fail?.(errInfo);
  459. }
  460. let ret = {
  461. errMsg: result.errMsg as string
  462. } as UTSJSONObject
  463. options.complete?.(result);
  464. return ret;
  465. }
  466. }
  467. export const createSQLiteContext = function (dbName : string) : SQLiteContext {
  468. // 确保数据库名称包含.db后缀
  469. const name = dbName.endsWith('.db') ? dbName : dbName + '.db';
  470. // 注意:根据接口定义,只接受一个参数,默认不强制重新创建表
  471. return new SQLiteContext(name, false);
  472. }