Sfoglia il codice sorgente

好消息: 第一个跑通的版本!
坏消息: 还有很多需要重写

NandHyf 1 anno fa
parent
commit
25621ddffc
9 ha cambiato i file con 231 aggiunte e 189 eliminazioni
  1. 4 5
      Alt.py
  2. 11 15
      Controller.py
  3. 10 53
      Stateful.py
  4. 149 0
      WithSqlite.py
  5. 57 0
      WithToml.py
  6. BIN
      dev.db
  7. 0 37
      dev_config.toml
  8. 0 79
      sqlite.py
  9. BIN
      数据库表结构设计.png

+ 4 - 5
Alt.py

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

+ 11 - 15
Controller.py

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

+ 10 - 53
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):
     try:
         with open(tomlName, "rb") as t:
@@ -64,57 +61,17 @@ def MatchTomlKeys(tomlName, keys, table=None) -> list:
         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 -----
 def Handler(app_commands):
     dbType = app_commands[-1]
     dbPath = app_commands[-2]
+    # 检查dbPath是否是dbType, 否的话报错并exit()
+
+    exec_commands = app_commands[0:-2]
 
     if dbType == "sqlite3":
-        # IsExist()
-        # Operated_sqlite3()
-        return Operate_sqlite3(dbPath, app_commands)
+        WithSqlite.Regular(dbPath, exec_commands)
+
 
     elif dbType == "csv":
         pass
@@ -141,5 +98,5 @@ if __name__ == "__main__":
     e_c = ['add', 'board']
 
     # Operate_sqlite3("test.db", a_c1)
-    PackHandler(a_c2)
+    Handler(a_c2)
     

+ 149 - 0
WithSqlite.py

@@ -0,0 +1,149 @@
+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 KB():
+    pass
+
+class CL():
+    pass
+
+class EV():
+    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:
+            if exec_commands[0] == 'select':
+                sqls = "SELECT name FROM {table} WHERE name='{name}';".format(table=tableName, name=itemName)
+                exec_flag = True
+
+            elif exec_commands[0] == 'add':
+                print("err <Code>: existed")
+
+            elif exec_commands[0] == 'delete':
+                sqls = "UPDATE {table} SET status='deleted' WHERE name='{name}';".format(table=tableName, name=itemName)
+                exec_flag = True
+
+            elif exec_commands[0] == 'edit':
+                sqls = ""
+                exec_flag = True
+
+            elif exec_commands[0] == 'move':
+                sqls = ""
+                exec_flag = True
+
+            elif exec_commands[0] == '..':
+                sqls = ""
+                exec_flag = True
+
+            elif exec_commands[0] == '/':
+                sqls = ""
+                exec_flag = True
+
+            elif exec_commands[0] == 'wipe':
+                sqls = ""
+                exec_flag = True
+
+        elif ie == False:
+            if exec_commands[0] == 'select':
+                print("err <Code>: not exist")
+
+            elif exec_commands[0] == 'add':
+                sqls = "INSERT INTO {table} VALUES(null, '{name}', 'live')".format(table=tableName, name=itemName)
+                exec_flag = True
+
+            elif exec_commands[0] == 'delete':
+                sqls = ""
+                exec_flag = True
+
+            elif exec_commands[0] == 'edit':
+                sqls = ""
+                exec_flag = True
+
+            elif exec_commands[0] == 'move':
+                print("err <Code>: not exist")
+
+            elif exec_commands[0] == '..':
+                sqls = ""
+                exec_flag = True
+
+            elif exec_commands[0] == '/':
+                print("err <Code>: not exist")
+
+            elif exec_commands[0] == 'wipe':
+                sqls = ""
+                exec_flag = True
+
+        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"
 listStyle = "tree"
 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"

+ 0 - 79
sqlite.py

@@ -1,79 +0,0 @@
-import sqlite3
-import Stateful
-
-deType = "sqlite3"
-dbPath = "dev.db"
-
-
-# [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. 执行
-
-
-class Op_sqlite3():
-    def __init__(self, commands) -> None:
-        self.dbPath = dbPath
-        self.commands = commands
-        self.tableName = str(commands[1]).capitalize()
-        self.columnName = str(commands[2])
-        # "to" condition need a "if"
-        self.ItemName = str(commands[])
-    
-
-    def Exec(self):
-        con = sqlite3.connect(dbPath)
-        cur = con.cursor()
-
-        cur.execute(self.commands)
-        con.commit()
-        re = cur.fetchall()
-        con.close()
-
-        return re
-        
-
-    def IsExist(self, returnBool=True):
-        sqls = "SELECT {coumn} FROM {table} WHERE name='{name}'".format(column=self.columnName, table=self.tableName, name=self.ItemName)
-        ie = Op_sqlite3.Exec(sqls)
-
-        if ie != None and returnBool == False:
-            return ie
-        
-        elif ie != None and returnBool == True:
-            return True
-
-        elif ie == None:
-            return False
-        
-        else:
-            print("unexpected processing error")
-
-
-    def Secondary_response(self):
-        pass
-
-    # Regular Start
-    def Regular(self):
-        try:
-            ie = Op_sqlite3.IsExist()
-
-            if ie != None:
-                Op_sqlite3.Exec(dbPath, sy_i)
-
-        except:
-            print("not exist")
-
-
-if __name__ == "__main__":
-
-    while(1):
-        sy_i = input("sql: ").split(" ")
-        Op_sqlite3.Regular(dbPath, sy_i)
-
-        

BIN
数据库表结构设计.png