Browse Source

Merge remote-tracking branch 'origin/master'

nandHyf 1 year ago
parent
commit
443b3b56d2
8 changed files with 193 additions and 110 deletions
  1. 4 5
      Alt.py
  2. 12 16
      Controller.py
  3. 11 52
      Stateful.py
  4. 109 0
      WithSqlite.py
  5. 57 0
      WithToml.py
  6. BIN
      dev.db
  7. 0 37
      dev_config.toml
  8. BIN
      数据库表结构设计.png

+ 4 - 5
Alt.py

@@ -3,10 +3,9 @@
 # err 1: correct DB not found
 # err 1: correct DB not found
 # -----
 # -----
 import Stateful
 import Stateful
-import datetime, base64
+import datetime, base64, uuid
 
 
-def Err(errCode, lang):
-    pass
+def Err(errCode, lang='en'):
     errText = ""
     errText = ""
-    input("error ", errCode, errText)
-    exit()
+    input("err ", errCode, ": ",  errText)
+    exit()

+ 12 - 16
Controller.py

@@ -11,17 +11,18 @@ class Client():
         # rl == 'r'eturn 'l'ist
         # rl == 'r'eturn 'l'ist
         rl = Stateful.MatchTomlKeys("dev_config.toml", configs)
         rl = Stateful.MatchTomlKeys("dev_config.toml", configs)
         
         
-        global lang, listStyle, dbType, dbPath
+        global lang, listStyle, dbType, dbPath, displayTimeZone, currentPath
         dbType = rl[0]
         dbType = rl[0]
         dbPath = rl[1]
         dbPath = rl[1]
         lang = rl[2]
         lang = rl[2]
         listStyle = rl[3]
         listStyle = rl[3]
         displayTimeZone = rl[4]
         displayTimeZone = rl[4]
+        currentPath = ""
 
 
 
 
     # [todo 4]
     # [todo 4]
     def get_help():
     def get_help():
-        print(Stateful.matchTomlKey("clean_config.toml", lang, "command-help"))
+        print(Stateful.MatchTomlKey("clean_config.toml", lang, "command-help"))
 
 
 
 
     # [todo 3]
     # [todo 3]
@@ -30,7 +31,7 @@ class Client():
         return(dt_now_UTC0)
         return(dt_now_UTC0)
     
     
 
 
-    # [todo 0]
+    # [todo 2]
     # 前端只检查输入数量正确, 内容正确统一代回后端检查
     # 前端只检查输入数量正确, 内容正确统一代回后端检查
     def InputCheck(inputs):
     def InputCheck(inputs):
         pass
         pass
@@ -45,29 +46,24 @@ class Client():
             # [todo 1]
             # [todo 1]
             # Client.InputCheck(app_commands)
             # Client.InputCheck(app_commands)
             if len(app_commands) < 5:
             if len(app_commands) < 5:
-                # Add DBType && Path
+                # Add CurrentPath && DBType && Path
+                app_commands.append(currentPath)
                 app_commands.append(dbPath)
                 app_commands.append(dbPath)
                 app_commands.append(dbType)
                 app_commands.append(dbType)
-                Stateful.PackHandler(app_commands)
+
+                Stateful.Handler(app_commands)
 
 
             elif len(app_commands) >= 5:
             elif len(app_commands) >= 5:
-                print(">5 error")
-                break
+                print("app_commands >5 error")
+
 
 
     # [todo 4]
     # [todo 4]
     def start():
     def start():
         # 1. get config
         # 1. get config
         Client.get_config()
         Client.get_config()
 
 
-        global currentPath
-        currentPath = " "
-        # ↓↓↓ test code here ↓↓↓
-
-
-        # ↑↑↑ test code here ↑↑↑
-
-        # 2. Normalized Start Process
-        startState = Stateful.PackHandler(['/', dbPath, dbType])
+        # 2.
+        startState = Stateful.Handler(['/', dbPath, dbType])
         print(startState)
         print(startState)
         Client.TransitCommand()
         Client.TransitCommand()
 
 

+ 11 - 52
Stateful.py

@@ -1,12 +1,9 @@
-import Alt
-import uuid
-import tomlkit, sqlite3
+import Alt, WithSqlite
+import tomlkit
 
 
-# Place for uid
+# Placeholder for uid related
 
 
-
-# ----- Methods binding app command to model -----
-# Toml
+# Toml Methods
 def GetTomlDoc(tomlName):
 def GetTomlDoc(tomlName):
     try:
     try:
         with open(tomlName, "rb") as t:
         with open(tomlName, "rb") as t:
@@ -64,55 +61,17 @@ def MatchTomlKeys(tomlName, keys, table=None) -> list:
         return rl
         return rl
 
 
 
 
-# Sqlite3
-def Exist_in_sqlite3(tableName, columnName=None, recordName=None):
-    if columnName == None:
-        s = "SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}';".format(tableName = tableName)
-
-    if columnName != None:
-        s = "SELECT * FROM {tableName} WHERE {columnName}={recordName}".format(tableName = tableName, columnName = columnName, recordName = recordName)
-
-
-def Operate_sqlite3(dbPath, match_commands):
-    matchedSyntax = MatchTomlKeys("dev_config.toml", match_commands, "sqlite3")
-
-    # 需要检查的类型
-    # Board, 禁止重复
-    # Class, 重复就update一个引用关系
-    # Event, 同一个Board里面不允许重复, 不同Board里可以重复
-
-    s = "".join(matchedSyntax).format(tableName = match_commands[1], objName = match_commands[2])
-   
-
-    con = sqlite3.connect(dbPath)
-    cur = con.cursor()
-    
-    # is_exist()
-    res = cur.execute(s).fetchall()
-    # ret = res.fetchall()
-    # if res = None:
-    
-
-    con.close()
-    return res
-
-
-# Markdown
-
-
-# csv
-
-
-# MongoDB
-
-
 # ----- Transit Command Handler -----
 # ----- Transit Command Handler -----
-def PackHandler(app_commands):
+def Handler(app_commands):
     dbType = app_commands[-1]
     dbType = app_commands[-1]
     dbPath = app_commands[-2]
     dbPath = app_commands[-2]
+    # 检查dbPath是否是dbType, 否的话报错并exit()
+
+    exec_commands = app_commands[0:-2]
 
 
     if dbType == "sqlite3":
     if dbType == "sqlite3":
-        return Operate_sqlite3(dbPath, app_commands)
+        WithSqlite.Regular(dbPath, exec_commands)
+
 
 
     elif dbType == "csv":
     elif dbType == "csv":
         pass
         pass
@@ -139,5 +98,5 @@ if __name__ == "__main__":
     e_c = ['add', 'board']
     e_c = ['add', 'board']
 
 
     # Operate_sqlite3("test.db", a_c1)
     # Operate_sqlite3("test.db", a_c1)
-    PackHandler(a_c2)
+    Handler(a_c2)
     
     

+ 109 - 0
WithSqlite.py

@@ -0,0 +1,109 @@
+import sqlite3
+
+
+# [todo 1]
+# 1. 检查commands[5]是否为dbPath, 不是话报错(syntax error)
+# ↑↑↑ 但是总感觉输入检查应该放在Controller里面(也就是放在前端去检查)...
+# 前端检查语法, 冲突代回到后端去检查, 然后顺便就执行了
+# 2. 命令里面的<KB>, <CL>, <EV>都代入检查是否存在, 区分add/edit(INSERT INTO/UPDATE)
+# 3. 匹配SQL关键字
+# 4. 拼完以后进行to和in的判断
+# 5. 按正确的顺序拼SQL语句
+# 6. 执行
+dbPath = "dev.db"
+
+
+def Exec_one(dbPath, commands):
+    con = sqlite3.connect(dbPath)
+    cur = con.cursor()
+
+    cur.execute(commands)
+    con.commit()
+    re = cur.fetchall()
+    con.close()
+
+    return re
+
+
+def Exec_many():
+    pass
+        
+
+def IsExist(exec_commands, returnBool=True):
+    tableName = str(exec_commands[1]).capitalize()
+
+    ItemName = str(exec_commands[2])
+
+    sqls = "SELECT name FROM {table} WHERE name='{name}'".format(table=tableName, name=ItemName)
+    ie = Exec_one(dbPath, sqls)
+
+    if ie != [] and returnBool == False:
+        return ie
+    
+    elif ie != [] and returnBool == True:
+        return True
+
+    elif ie == []:
+        return False
+    
+    else:
+        # Alt.Err(errCode)
+        print("err <Code>: unexpected error in existence check")
+
+
+# [todo 4]
+def Secondary_response():
+    pass
+
+
+class Sqls():
+    objType = ""
+    def select():
+        # DISTINCT
+        sqls = "SELECT FROM {table}".format(table=tableName)
+
+    def add():
+        pass
+
+    def delete():
+        pass
+
+    def edit():
+        pass
+
+    def move():
+        pass
+
+    def bp():
+        pass
+
+    def home():
+        pass
+
+
+# Regular Start
+def Regular(dbPath, exec_commands):
+    
+    # try:
+        ie = IsExist(exec_commands)
+        print("is exist: ", ie)
+        tableName = str(exec_commands[1]).capitalize()
+        # to的情况待处理
+        itemName = str(exec_commands[2])
+        exec_flag = False
+
+        if ie == True:
+            pass
+
+        elif ie == False:
+            pass
+
+        elif exec_flag == True:
+            # 有个数据库锁定的异常待处理(Multi-user)
+            Exec_one(dbPath, sqls)
+
+if __name__ == "__main__":
+
+    while(1):
+        sy_i = input("sql: ").split(" ")
+        Regular(dbPath, sy_i)

+ 57 - 0
WithToml.py

@@ -0,0 +1,57 @@
+# Toml
+def GetTomlDoc(tomlName):
+    try:
+        with open(tomlName, "rb") as t:
+            doc = tomlkit.load(t)
+
+            if doc == {}:
+                input("error 0: could not found correct config file") 
+                exit()
+
+            return doc
+        
+    except:
+        input("error 0: could not found correct config file") 
+        exit()
+    
+
+def MatchTomlKey(tomlName, key, table=None) -> str:
+    doc = GetTomlDoc(tomlName)
+
+    if table == None:
+        return str(doc.item(key))
+    
+    elif table != None:
+        d = doc.unwrap()
+        return str(d[table][key])
+
+
+# no differernt between ↑ MatchTomlKey() ↑ except receives and returns in list
+def MatchTomlKeys(tomlName, keys, table=None) -> list:
+    doc = GetTomlDoc(tomlName)
+
+    if table == None:
+        # rl == 'r'eturn 'l'ist
+        rl = []
+
+        for key in keys:
+            try:
+                rl.append(doc.item(key))
+            except:
+                pass
+
+        return rl
+    
+
+    elif table != None:
+        rl = []
+        d = doc.unwrap()
+
+        for key in keys:
+            try:
+                rl.append(d[table][key])
+            except:
+                pass
+
+        return rl
+

BIN
dev.db


+ 0 - 37
dev_config.toml

@@ -5,40 +5,3 @@ DBPath = "dev.db"
 lang = "en"
 lang = "en"
 listStyle = "tree"
 listStyle = "tree"
 displayTimeZone = "utc+8"
 displayTimeZone = "utc+8"
-
-
-# ----- App Command to DB Syntax Translation -----
-[sqlite3.init]
-DBType = "sqlite3"
-# Table name
-Board = ""
-Class = ""
-Event = ""
-Stuck = ""
-Alert = ""
-DDL = ""
-
-[sqlite3]
-# app_command[0]
-"/" = "SELECT name FROM Board;"
-select = "SELECT "
-add = "INSERT INTO "
-edit = "UPDATE "
-delete = "UPDATE " # change stauts to "deleted"
-wipe="DROP WHERE"
-
-# app_command[1]
-# board = "({uid}, {name}, {status}).format(uid='', name='', status='live')"
-current_board_id = 3
-# class = "({uid}, {name}, {usedBoard}, {status})"
-current_class_id = 0
-# event = "({uid}, {name}, {dscrp}, {createdTime}, {belongBoard}, {classCreated}, {currentClas}, {status})"
-current_event_id = 0
-
-# "/" -> " " in Stateful
-stucked = "Stucked "
-
-# app_command[3] && [4]
-"-d" = ""
-"-ddl" = ""
-to = "here is to"

BIN
数据库表结构设计.png