Skip to content

Commit

Permalink
Prepare for more db component
Browse files Browse the repository at this point in the history
  • Loading branch information
enums committed Jun 23, 2017
1 parent ba33133 commit 41e75fa
Show file tree
Hide file tree
Showing 12 changed files with 96 additions and 112 deletions.
61 changes: 37 additions & 24 deletions Source/Pjango/DB/Base/PCDataBase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ public enum PCDataBaseState {

open class PCDataBase {

open var schema: String? {
return nil
}

open let config: PCDataBaseConfig
open var state: PCDataBaseState

Expand Down Expand Up @@ -57,14 +61,14 @@ open class PCDataBase {
guard state == .connected else {
return nil
}
_pjango_core_log.debug("Exc sql: \(sql)")
_pjango_core_log.debug("Query: \(sql)")
return doQuery(sql)
}

open func doQuery(_ sql: PCSqlStatement) -> [PCDataBaseRecord]? { return nil }

open func isSchemeExist(_ scheme: String) -> Bool {
guard let ret = query(PCSqlUtility.selectScheme(scheme)) else {
open func isSchemaExist(_ scheme: String) -> Bool {
guard let ret = query(PCSqlUtility.selectSchema(scheme)) else {
return false
}
if ret.count >= 1 {
Expand All @@ -74,51 +78,60 @@ open class PCDataBase {
}
}


open func isTableExist(_ table: String) -> Bool {
return query(PCSqlUtility.selectTable(config.name, table)) != nil ? true : false
return query(PCSqlUtility.selectTable(schema, table)) != nil ? true : false
}

open func createScheme() {
guard query(PCSqlUtility.createScheme(config.name)) != nil else {
_pjango_core_log.error("Failed on creating scheme `\(config.name)`")
open func createSchema() {
guard let schema = schema else {
_pjango_core_log.error("Failed on creating schema. Schema value is nil.")
return
}
_pjango_core_log.info("Success on creating scheme `\(config.name)`")
guard query(PCSqlUtility.createSchema(schema)) != nil else {
_pjango_core_log.error("Failed on creating schema `\(schema)`")
return
}
_pjango_core_log.info("Success on creating schema `\(schema)`")
}

open func dropScheme() {
guard query(PCSqlUtility.dropScheme(config.name)) != nil else {
_pjango_core_log.error("Failed on droping scheme `\(config.name)`")
open func dropSchema() {
guard let schema = schema else {
_pjango_core_log.error("Failed on droping schema. Schema value is nil.")
return
}
guard query(PCSqlUtility.dropSchema(schema)) != nil else {
_pjango_core_log.error("Failed on droping schema `\(schema)`")
return
}
_pjango_core_log.info("Sucess on droping scheme `\(config.name)`")
_pjango_core_log.info("Sucess on droping schema `\(schema)`")
}

open func createTable(_ model: PCModel) {
guard query(PCSqlUtility.createTable(config.name, model.tableName, model._pjango_core_model_fields)) != nil else {
_pjango_core_log.error("Failed on creating table `\(config.name).\(model.tableName)`")
open func createTable(model: PCModel) {
guard query(PCSqlUtility.createTable(schema, model.tableName, model._pjango_core_model_fields)) != nil else {
_pjango_core_log.error("Failed on creating table \(PCSqlUtility.schemeAndTableToStr(schema, model.tableName))")
return
}
_pjango_core_log.info("Success on creating table `\(config.name).\(model.tableName)`")
_pjango_core_log.info("Success on creating table \(PCSqlUtility.schemeAndTableToStr(schema, model.tableName))")
}

open func dropTable(_ model: PCMetaModel) {
open func dropTable(model: PCMetaModel) {
dropTable(model.tableName)
}

open func dropTable(_ table: String) {
guard query(PCSqlUtility.dropTable(config.name, table)) != nil else {
_pjango_core_log.error("Failed on droping table `\(config.name).\(table)`")
guard query(PCSqlUtility.dropTable(schema, table)) != nil else {
_pjango_core_log.error("Failed on droping table \(PCSqlUtility.schemeAndTableToStr(schema, table))")
return
}
_pjango_core_log.info("Success on droping table `\(config.name).\(table)`")
_pjango_core_log.info("Success on droping table \(PCSqlUtility.schemeAndTableToStr(schema, table))")
}

open func selectTable(_ model: PCMetaModel) -> [PCDataBaseRecord]? {
return selectTable(model.tableName)
open func selectTable(model: PCMetaModel) -> [PCDataBaseRecord]? {
return selectTable(table: model.tableName)
}

open func selectTable(_ table: String) -> [PCDataBaseRecord]? {
return query(PCSqlUtility.selectTable(config.name, table))
open func selectTable(table: String) -> [PCDataBaseRecord]? {
return query(PCSqlUtility.selectTable(schema, table))
}
}
43 changes: 4 additions & 39 deletions Source/Pjango/DB/Base/PCDataBaseConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,45 +8,10 @@

import Foundation

public enum PCDataBaseEnginType: String {
case mysql = "mysql"
}

public struct PCDataBaseConfig {

public var engine = PCDataBaseEnginType.mysql
public var name = "default"
public var user = "root"
public var password = ""
public var host = "127.0.0.1"
public var port = UInt16(3306)

open class PCDataBaseConfig {

public init() { }

public init?(param: Dictionary<String, Any>) {
guard let engine = param["ENGINE"] as? PCDataBaseEnginType else {
return nil
}
guard let name = param["NAME"] as? String else {
return nil
}
guard let user = param["USER"] as? String else {
return nil
}
guard let password = param["PASSWORD"] as? String else {
return nil
}
guard let host = param["HOST"] as? String else {
return nil
}
guard let port = param["PORT"] as? UInt16 else {
return nil
}
self.engine = engine
self.name = name
self.user = user
self.password = password
self.host = host
self.port = port
}
public init?(param: Dictionary<String, Any>) { }

}
2 changes: 1 addition & 1 deletion Source/Pjango/Model/PCModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ open class PCModel: PCObject, PCViewable {
guard let meta = PjangoRuntime._pjango_runtime_models_name2meta[_pjango_core_class_name] else {
return nil
}
guard let records = PjangoRuntime._pjango_runtime_database.selectTable(meta) else {
guard let records = PjangoRuntime._pjango_runtime_database.selectTable(model: meta) else {
return nil
}
return records.map { record in
Expand Down
9 changes: 4 additions & 5 deletions Source/Pjango/Pjango/Settings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ public var WORKSPACE_PATH = ""

public var DEBUG_LOG = true

public var ERROR_MSG_INTERNAL = "INTERNAL ERROR"
public var ERROR_TEMPLATE_INTERNAL: PCView? = nil
public var ERROR_INTERNAL_MSG = "INTERNAL ERROR"
public var ERROR_INTERNAL_VIEW: PCView? = nil

public var ERROR_MSG_NOTFOUND = "404"
public var ERROR_TEMPLATE_NOTFOUND: PCView? = nil
public var ERROR_NOTFOUND_MSG = "404"
public var ERROR_NOTFOUND_VIEW: PCView? = nil

// Django
public var BASE_DIR = ""
Expand All @@ -27,4 +27,3 @@ public var TEMPLATES_DIR = "templates"

public var STATIC_URL = "static"

public var DATABASE = PCDataBaseConfig.init()
4 changes: 1 addition & 3 deletions Source/Pjango/Plugin/Base/PCPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ open class PCPlugin: PCObject, PCRunable {

required override public init() { }

public var taskQueue: DispatchQueue {
return DispatchQueue.init(label: _pjango_core_class_name)
}
public var taskQueue: DispatchQueue = DispatchQueue.init(label: _pjango_core_class_name)

open var task: PCTask? {
return nil
Expand Down
24 changes: 12 additions & 12 deletions Source/Pjango/Runtime/PjangoDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,38 @@ public protocol PjangoDelegate {

func setSettings()

func setUrls() -> [PCUrlConfig]
func setUrls() -> [PCUrlConfig]?

func registerPlugins() -> [PCPlugin]
func registerPlugins() -> [PCPlugin]?

func registerModels() -> [PCModel]
func registerModels() -> [PCModel]?

func setDB() -> PCDataBase
func setDB() -> PCDataBase?

func setRequestFilter() -> [(HTTPRequestFilter, HTTPFilterPriority)]
func setRequestFilter() -> [(HTTPRequestFilter, HTTPFilterPriority)]?

func setResponseFilter() -> [(HTTPResponseFilter, HTTPFilterPriority)]
func setResponseFilter() -> [(HTTPResponseFilter, HTTPFilterPriority)]?
}

public extension PjangoDelegate {

func setSettings() { }

func setUrls() -> [PCUrlConfig] { return [] }
func setUrls() -> [PCUrlConfig]? { return nil }

func registerPlugins() -> [PCPlugin] { return [] }
func registerPlugins() -> [PCPlugin]? { return nil }

func registerModels() -> [PCModel] { return [] }
func registerModels() -> [PCModel]? { return nil }

func setDB() -> PCDataBase { return PCDataBase.empty }
func setDB() -> PCDataBase? { return nil }

func setRequestFilter() -> [(HTTPRequestFilter, HTTPFilterPriority)] {
func setRequestFilter() -> [(HTTPRequestFilter, HTTPFilterPriority)]? {
return [
(PCLogFilter.init(), .high)
]
}

func setResponseFilter() -> [(HTTPResponseFilter, HTTPFilterPriority)] {
func setResponseFilter() -> [(HTTPResponseFilter, HTTPFilterPriority)]? {
return [
(PCLogFilter.init(), .high),
(PCNotFoundFilter.init(), .low)
Expand Down
23 changes: 12 additions & 11 deletions Source/Pjango/Runtime/PjangoRuntime.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public class PjangoRuntime {

internal static func _pjango_runtime_setUrls(delegate: PjangoDelegate) {

_pjango_runtime_url = delegate.setUrls()
_pjango_runtime_url = delegate.setUrls() ?? []

_pjango_runtime_url.forEach { config in
_pjango_runtime_urls_url2config[config.url] = config
Expand All @@ -93,16 +93,15 @@ public class PjangoRuntime {

internal static func _pjango_runtime_registerPlugins(delegate: PjangoDelegate) {

_pjango_runtime_plugin = delegate.registerPlugins()
_pjango_runtime_plugin = delegate.registerPlugins() ?? []

_pjango_runtime_plugin.forEach { $0.run() }

}

internal static func _pjango_runtime_setDB(delegate: PjangoDelegate) {

let config = DATABASE
let database = delegate.setDB()
let database = delegate.setDB() ?? PCDataBase.empty

_pjango_runtime_database = database

Expand All @@ -113,21 +112,23 @@ public class PjangoRuntime {
database.setup()
database.connect()

if !database.isSchemeExist(config.name) {
_pjango_runtime_log.info("Scheme `\(config.name)` is not exist! Create it.")
database.createScheme()
if let schema = database.schema {
if !database.isSchemaExist(schema) {
_pjango_runtime_log.info("Schema `\(schema)` is not exist! Create it.")
database.createSchema()
}
}

}

internal static func _pjango_runtime_registerModels(delegate: PjangoDelegate) {

let metas = delegate.registerModels()
let metas = delegate.registerModels() ?? []

metas.forEach { meta in
if !_pjango_runtime_database.isTableExist(meta.tableName) {
_pjango_runtime_log.info("Table `\(meta.tableName)` is not exist! Create it.")
_pjango_runtime_database.createTable(meta)
_pjango_runtime_database.createTable(model: meta)
}
_pjango_runtime_models_name2meta[meta._pjango_core_class_name] = meta
}
Expand All @@ -146,8 +147,8 @@ public class PjangoRuntime {
server.serverPort = port
server.addRoutes(routes)

server.setRequestFilters(delegate.setRequestFilter())
server.setResponseFilters(delegate.setResponseFilter())
server.setRequestFilters(delegate.setRequestFilter() ?? [])
server.setResponseFilters(delegate.setResponseFilter() ?? [])

_pjango_runtime_server = server
}
Expand Down
2 changes: 1 addition & 1 deletion Source/Pjango/Server/Filter/PCNotFoundFilter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ internal class PCNotFoundFilter: HTTPResponseFilter {

func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
if case .notFound = response.status {
let body = ERROR_TEMPLATE_NOTFOUND?.getTemplate() ?? ERROR_MSG_NOTFOUND
let body = ERROR_NOTFOUND_VIEW?.getTemplate() ?? ERROR_NOTFOUND_MSG
response._pjango_safe_setBody(body)
callback(.done)
} else {
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion Source/Pjango/Utility/Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public extension Date {
public extension HTTPResponse {

func _pjango_safe_setBody(_ body: String?, _ setContentLength: Bool = true) {
self.setBody(string: body ?? (ERROR_TEMPLATE_INTERNAL?.getTemplate() ?? ERROR_MSG_INTERNAL))
self.setBody(string: body ?? (ERROR_INTERNAL_VIEW?.getTemplate() ?? ERROR_INTERNAL_MSG))
if setContentLength {
self.setHeader(.contentLength, value: "\(self.bodyBytes.count)")
}
Expand Down
30 changes: 19 additions & 11 deletions Source/Pjango/Utility/PCSqlUtility.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,46 @@ public typealias PCDataBaseRecord = [String?]

final public class PCSqlUtility {

public static func createScheme(_ name: String) -> PCSqlStatement {
public static func createSchema(_ name: String) -> PCSqlStatement {
return "CREATE SCHEMA `\(name)` ;"
}

public static func dropScheme(_ name: String) -> PCSqlStatement {
public static func dropSchema(_ name: String) -> PCSqlStatement {
return "DROP DATABASE `\(name)`;"
}

public static func selectScheme(_ name: String) -> PCSqlStatement {
public static func selectSchema(_ name: String) -> PCSqlStatement {
return "SELECT * FROM information_schema.SCHEMATA where SCHEMA_NAME='\(name)';"
}

public static func createTable(_ scheme: String, _ table: String, _ fields: Array<PCDataBaseField>) -> PCSqlStatement {
internal static func schemeAndTableToStr(_ schema: String? = nil, _ table: String) -> String {
if let schema = schema {
return "`\(schema)`.`\(table)`"
} else {
return "`\(table)`"
}
}

public static func createTable(_ schema: String? = nil, _ table: String, _ fields: Array<PCDataBaseField>) -> PCSqlStatement {
let fieldsStr = fields.reduce("") {
$0 + ", " + $1._pjango_core_toSql()
}
return "CREATE TABLE `\(scheme)`.`\(table)` (`_pjango_id` INT AUTO_INCREMENT \(fieldsStr), PRIMARY KEY (`_pjango_id`));"
return "CREATE TABLE \(schemeAndTableToStr(schema, table)) (`_pjango_id` INT AUTO_INCREMENT \(fieldsStr), PRIMARY KEY (`_pjango_id`));"
}

public static func dropTable(_ scheme: String, _ table: String) -> PCSqlStatement {
return "DROP TABLE `\(scheme)`.`\(table)`;"
public static func dropTable(_ schema: String? = nil, _ table: String) -> PCSqlStatement {
return "DROP TABLE \(schemeAndTableToStr(schema, table));"
}

public static func selectTable(_ scheme: String, _ table: String, _ fields: String = "*") -> PCSqlStatement {
return "SELECT \(fields) FROM \(scheme).\(table);"
public static func selectTable(_ schema: String? = nil, _ table: String, _ fields: String = "*") -> PCSqlStatement {
return "SELECT \(fields) FROM \(schemeAndTableToStr(schema, table));"
}

public static func insertRecord(_ scheme: String, _ table: String, _ record: PCDataBaseRecord) -> PCSqlStatement {
public static func insertRecord(_ schema: String, _ table: String, _ record: PCDataBaseRecord) -> PCSqlStatement {
let recordStr = record.reduce("'0'") {
$0 + ", " + ($1 ?? "")
}
return "INSERT INTO `\(scheme)`.`\(table)` VALUES (\(recordStr))"
return "INSERT INTO \(schemeAndTableToStr(schema, table)) VALUES (\(recordStr))"
}

}
Loading

0 comments on commit 41e75fa

Please sign in to comment.