|
- '==============================================================
- ' GenerateRepo.vbs (AxonASP CLI + G3DB edition)
- '
- ' Usage (runs under the AxonASP CLI in the container):
- ' scripts\gen.cmd repo /table:Products /pk:Id
- '
- ' Reads the connection string from public\web.config (<appSettings> ConnectionString = "<driver>:<dsn>"),
- ' discovers the table schema, and generates into app/models/:
- ' POBO_<Table>.asp (class with typed Property Let/Get)
- ' <Table>Repository.asp (parameterized CRUD + filter + paging + search, via DAL())
- '
- ' Schema discovery currently supports SQLite (PRAGMA table_info). Templates live in scripts/templates/.
- '==============================================================
-
- Option Explicit
-
- ' AxonASP CLI: provide the WScript object (see _cli.vbs)
- Dim shimFso
- Set shimFso = CreateObject("Scripting.FileSystemObject")
- ExecuteGlobal shimFso.OpenTextFile(Server.MapPath("/scripts/_cli.vbs"), 1).ReadAll
-
- '---------------- Args & paths ----------------
- Dim fso, args, i, arg, parts
- Dim tableName, primaryKey, csKey, configPath, outDir
-
- Set fso = CreateObject("Scripting.FileSystemObject")
- Set args = WScript.Arguments
-
- csKey = "ConnectionString"
- configPath = Server.MapPath("/public/web.config")
- outDir = Server.MapPath("/app/models")
-
- For i = 0 To args.Count - 1
- arg = args(i)
- If InStr(arg, ":") > 0 Then
- parts = Split(arg, ":", 2)
- Select Case LCase(Replace(parts(0), "/", ""))
- Case "table": tableName = parts(1)
- Case "pk": primaryKey = parts(1)
- Case "cs": csKey = parts(1)
- Case "config": configPath = parts(1)
- End Select
- End If
- Next
-
- If Len(tableName) = 0 Or Len(primaryKey) = 0 Then
- WScript.Echo "Usage: scripts\gen.cmd repo /table:<TableName> /pk:<PrimaryKey>"
- WScript.Quit 1
- End If
-
- If Not IsValidIdentifier(tableName) Then
- WScript.Echo "Error: Invalid table name format. Only letters, numbers, and underscores are allowed."
- WScript.Quit 1
- End If
-
- If Not IsValidIdentifier(primaryKey) Then
- WScript.Echo "Error: Invalid primary key format. Only letters, numbers, and underscores are allowed."
- WScript.Quit 1
- End If
-
- '---------------- Config & connection ----------------
- Dim connStr, p, driver, dsn
- connStr = GetAppSetting(csKey, configPath)
- If connStr = "nothing" Then
- WScript.Echo "Error: Key '" & csKey & "' not found in " & configPath
- WScript.Quit 1
- End If
-
- p = InStr(connStr, ":")
- If p < 2 Then
- WScript.Echo "Error: ConnectionString must look like '<driver>:<dsn>'. Got: " & connStr
- WScript.Quit 1
- End If
- driver = LCase(Left(connStr, p - 1))
- dsn = Mid(connStr, p + 1)
-
- If driver <> "sqlite" And driver <> "sqlite3" Then
- WScript.Echo "Error: schema discovery is implemented for SQLite only (driver is '" & driver & "')."
- WScript.Quit 1
- End If
-
- Dim db
- Set db = Server.CreateObject("G3DB")
- If Not db.Open("sqlite", dsn) Then
- WScript.Echo "DB connection failed: " & db.LastError
- WScript.Quit 1
- End If
-
- '---------------- Discover schema ----------------
- Dim cols(), kinds(), idx, rs
- idx = -1
- Set rs = db.Query("PRAGMA table_info(" & tableName & ")")
- If IsEmpty(rs) Then
- WScript.Echo "Error reading table [" & tableName & "]: " & db.LastError
- WScript.Quit 1
- End If
-
- Do Until rs.EOF
- idx = idx + 1
- ReDim Preserve cols(idx), kinds(idx)
- cols(idx) = CStr(rs(1)) ' name
- kinds(idx) = TypeKind(rs(2)) ' declared type -> string/number/bool/date
- rs.MoveNext
- Loop
- rs.Close
- db.Close
-
- If idx < 0 Then
- WScript.Echo "No columns found for table [" & tableName & "]. Run the migrations first."
- WScript.Quit 1
- End If
-
- If Not InArrayInsensitive(cols, primaryKey) Then
- WScript.Echo "Primary key '" & primaryKey & "' not found in table [" & tableName & "]."
- WScript.Quit 1
- End If
-
- '---------------- Generate files from templates ----------------
- If Not fso.FolderExists(outDir) Then fso.CreateFolder outDir
-
- Dim poboPath, repoPath
- poboPath = outDir & "/POBO_" & tableName & ".asp"
- repoPath = outDir & "/" & tableName & "Repository.asp"
-
- WriteFile poboPath, BuildPOBO(cols, kinds, tableName, primaryKey)
- WScript.Echo "POBO class written to: " & poboPath
-
- WriteFile repoPath, BuildRepository(cols, tableName, primaryKey)
- WScript.Echo "Repository written to: " & repoPath
-
- WScript.Echo ""
- WScript.Echo "Next steps:"
- WScript.Echo "1. Include both files from app/models/autoload_models.asp:"
- WScript.Echo " <!--#include file=""POBO_" & tableName & ".asp""-->"
- WScript.Echo " <!--#include file=""" & tableName & "Repository.asp""-->"
-
- Set fso = Nothing
-
- '==============================================================
- ' Generators
- '==============================================================
- Function ReadTemplate(name)
- Dim ts
- Set ts = fso.OpenTextFile(Server.MapPath("/scripts/templates/" & name), 1)
- ReadTemplate = ts.ReadAll
- ts.Close
- End Function
-
- Sub WriteFile(path, text)
- Dim tf
- Set tf = fso.CreateTextFile(path, True)
- tf.Write text
- tf.Close
- End Sub
-
- Function BuildPOBO(colsArr, kindsArr, tName, pk)
- Dim fields, defaults, propList, props, k, name, kind
- fields = "" : defaults = "" : propList = "" : props = ""
-
- For k = 0 To UBound(colsArr)
- name = colsArr(k)
- kind = kindsArr(k)
-
- fields = fields & " Private p" & name & vbCrLf
-
- Select Case kind
- Case "string": defaults = defaults & " p" & name & " = """"" & vbCrLf
- Case "number": defaults = defaults & " p" & name & " = 0" & vbCrLf
- Case "bool": defaults = defaults & " p" & name & " = False" & vbCrLf
- Case Else: defaults = defaults & " p" & name & " = Null" & vbCrLf
- End Select
-
- If k > 0 Then propList = propList & ","
- propList = propList & """" & name & """"
-
- props = props & " Public Property Get " & name & "()" & vbCrLf
- props = props & " " & name & " = p" & name & vbCrLf
- props = props & " End Property" & vbCrLf & vbCrLf
- props = props & " Public Property Let " & name & "(val)" & vbCrLf
- props = props & " On Error Resume Next" & vbCrLf
- Select Case kind
- Case "string"
- props = props & " p" & name & " = CStr(val)" & vbCrLf
- Case "bool"
- props = props & " p" & name & " = CBool(val)" & vbCrLf
- Case "date"
- props = props & " p" & name & " = CDate(val)" & vbCrLf
- Case Else
- props = props & " If IsNumeric(val) Then" & vbCrLf
- props = props & " p" & name & " = CDbl(val)" & vbCrLf
- props = props & " Else" & vbCrLf
- props = props & " p" & name & " = val" & vbCrLf
- props = props & " End If" & vbCrLf
- End Select
- props = props & " If Err.Number <> 0 Then" & vbCrLf
- props = props & " Err.Raise Err.Number, ""POBO_" & tName & "." & name & """, ""Invalid value for " & name & ": "" & Err.Description" & vbCrLf
- props = props & " End If" & vbCrLf
- props = props & " On Error GoTo 0" & vbCrLf
- props = props & " End Property" & vbCrLf & vbCrLf
- Next
-
- Dim t
- t = ReadTemplate("POBO.tpl.asp")
- t = Replace(t, "{{TABLE}}", tName)
- t = Replace(t, "{{PK}}", pk)
- t = Replace(t, "{{DATE}}", CStr(Now()))
- t = Replace(t, "{{FIELDS}}", fields)
- t = Replace(t, "{{DEFAULTS}}", defaults)
- t = Replace(t, "{{PROPLIST}}", propList)
- t = Replace(t, "{{PROPERTIES}}", props)
- BuildPOBO = t
- End Function
-
- Function BuildRepository(colsArr, tName, pk)
- Dim selectList, colList, mapLines, insCols, insPh, insParams, updSet, updParams, k, c
- selectList = "" : colList = "" : mapLines = "" : insCols = "" : insPh = "" : insParams = "" : updSet = "" : updParams = ""
-
- For k = 0 To UBound(colsArr)
- c = colsArr(k)
- If k > 0 Then
- selectList = selectList & ", "
- colList = colList & "|"
- End If
- selectList = selectList & QI(c)
- colList = colList & c
- mapLines = mapLines & " If Not IsNull(rs(" & k & ")) Then m." & c & " = rs(" & k & ")" & vbCrLf
-
- If Not StrEqualCI(c, pk) Then
- If Len(insCols) > 0 Then
- insCols = insCols & ", "
- insPh = insPh & ", "
- insParams = insParams & ", "
- updSet = updSet & ", "
- updParams = updParams & ", "
- End If
- insCols = insCols & QI(c)
- insPh = insPh & "?"
- insParams = insParams & "model." & c
- updSet = updSet & QI(c) & " = ?"
- updParams = updParams & "model." & c
- End If
- Next
-
- Dim t
- t = ReadTemplate("Repository.tpl.asp")
- t = Replace(t, "{{TABLE}}", tName)
- t = Replace(t, "{{PK}}", pk)
- t = Replace(t, "{{QTABLE}}", QI(tName))
- t = Replace(t, "{{QPK}}", QI(pk))
- t = Replace(t, "{{DATE}}", CStr(Now()))
- t = Replace(t, "{{COLUMN_LIST}}", colList)
- t = Replace(t, "{{SELECT_LIST}}", selectList)
- t = Replace(t, "{{MAP_LINES}}", mapLines)
- t = Replace(t, "{{INSERT_COLS}}", insCols)
- t = Replace(t, "{{INSERT_PLACEHOLDERS}}", insPh)
- t = Replace(t, "{{INSERT_PARAMS}}", "Array(" & insParams & ")")
- t = Replace(t, "{{UPDATE_SET}}", updSet)
- t = Replace(t, "{{UPDATE_PARAMS}}", "Array(" & updParams & ", model." & pk & ")")
- BuildRepository = t
- End Function
-
- '==============================================================
- ' Helpers (generator side)
- '==============================================================
- ' Quoted identifier for use inside the generated VBScript string literals: "Col" -> ""Col""
- Function QI(name)
- QI = """""" & Replace(CStr(name), """", """""""""") & """"""
- End Function
-
- ' SQLite declared type -> simple kind (follows SQLite's affinity rules, roughly)
- Function TypeKind(declType)
- Dim t
- t = UCase("" & declType)
- If InStr(t, "BOOL") > 0 Then
- TypeKind = "bool"
- ElseIf InStr(t, "DATE") > 0 Or InStr(t, "TIME") > 0 Then
- TypeKind = "date"
- ElseIf InStr(t, "CHAR") > 0 Or InStr(t, "CLOB") > 0 Or InStr(t, "TEXT") > 0 Then
- TypeKind = "string"
- ElseIf InStr(t, "INT") > 0 Or InStr(t, "REAL") > 0 Or InStr(t, "FLOA") > 0 Or InStr(t, "DOUB") > 0 Or InStr(t, "NUM") > 0 Or InStr(t, "DEC") > 0 Then
- TypeKind = "number"
- ElseIf Len(t) = 0 Then
- TypeKind = "string"
- Else
- TypeKind = "string"
- End If
- End Function
-
- Function GetAppSetting(key, configFilePath)
- Dim xml, nodes, node, j
- If Not fso.FileExists(configFilePath) Then
- GetAppSetting = "nothing"
- Exit Function
- End If
- Set xml = CreateObject("Microsoft.XMLDOM")
- xml.Async = False
- xml.Load(configFilePath)
- Set nodes = xml.selectNodes("//appSettings/add")
- For j = 0 To nodes.Length - 1
- Set node = nodes.Item(j)
- If node.getAttribute("key") = key Then
- GetAppSetting = node.getAttribute("value")
- Exit Function
- End If
- Next
- GetAppSetting = "nothing"
- End Function
-
- Function InArrayInsensitive(a, val)
- Dim z
- InArrayInsensitive = False
- For z = 0 To UBound(a)
- If StrEqualCI(a(z), val) Then
- InArrayInsensitive = True
- Exit Function
- End If
- Next
- End Function
-
- Function StrEqualCI(a, b)
- StrEqualCI = (LCase(CStr(a)) = LCase(CStr(b)))
- End Function
-
- ' Validate identifier (table name, column name, etc.)
- Function IsValidIdentifier(name)
- Dim n, ch
- If IsEmpty(name) Then
- IsValidIdentifier = False
- Exit Function
- End If
- If Len(name) = 0 Then
- IsValidIdentifier = False
- Exit Function
- End If
- For n = 1 To Len(name)
- ch = Mid(name, n, 1)
- If Not ((ch >= "a" And ch <= "z") Or (ch >= "A" And ch <= "Z") Or (ch >= "0" And ch <= "9") Or ch = "_") Then
- IsValidIdentifier = False
- Exit Function
- End If
- Next
- IsValidIdentifier = True
- End Function
|