This commit is contained in:
yumoqing 2020-05-20 20:36:15 +08:00
parent a52b6a8f05
commit 76c95f3bf0
9 changed files with 111 additions and 103 deletions

View File

@ -31,7 +31,7 @@ NOT NULL
{%- endif -%} {%- endif -%}
{% endmacro %} {% endmacro %}
{% macro primary() %} {% macro primary() %}
,primary key({{summary[0].primary}}) ,primary key({{','.join(summary[0].primary)}})
{% endmacro %} {% endmacro %}
drop table if exists {{summary[0].name}}; drop table if exists {{summary[0].name}};
CREATE TABLE {{summary[0].name}} CREATE TABLE {{summary[0].name}}
@ -45,9 +45,7 @@ engine=innodb
default charset=utf8 default charset=utf8
{% if summary[0].title %}comment '{{summary[0].title}}'{% endif %} {% if summary[0].title %}comment '{{summary[0].title}}'{% endif %}
; ;
{% for v in validation %} {% for v in indexes %}
{% if v.oper=='idx' %} CREATE {% if v.idxtype=='unique' %}UNIQUE{% endif %} INDEX {{summary[0].name}}_{{v.name}} ON {{summary[0].name}}({{",".join(v.idxfields)}});
CREATE {% if v.value.idxtype=='unique' %}UNIQUE{% endif %} INDEX {{summary[0].name}}_{{v.name}} ON {{summary[0].name}}({{",".join(v.value.fields)}});
{% endif %}
{%- endfor -%} {%- endfor -%}
""" """

View File

@ -25,7 +25,7 @@ NOT NULL
{%- endif -%} {%- endif -%}
{% endmacro %} {% endmacro %}
{% macro primary() %} {% macro primary() %}
,primary key({{summary[0].primary}}) ,primary key({{','.join(summary[0].primary)}})
{% endmacro %} {% endmacro %}
drop table {{summary[0].name}}; drop table {{summary[0].name}};
CREATE TABLE {{summary[0].name}} CREATE TABLE {{summary[0].name}}
@ -35,10 +35,8 @@ CREATE TABLE {{summary[0].name}}
{% endfor %} {% endfor %}
{{primary()}} {{primary()}}
); );
{% for v in validation %} {% for v in indexes %}
{% if v.oper=='idx' %} CREATE {% if v.idxtype=='unique' %}UNIQUE{% endif %} INDEX {{summary[0].name}}_{{v.name}} ON {{summary[0].name}}({{",".join(v.idxfields)}});
CREATE {% if v.value.idxtype=='unique' %}UNIQUE{% endif %} INDEX {{summary[0].name}}_{{v.name}} ON {{summary[0].name}}({{",".join(v.value.fields)}});
{% endif %}
{%- endfor -%} {%- endfor -%}
COMMENT ON TABLE {{summary[0].name}} IS '{{summary[0].title}}'; COMMENT ON TABLE {{summary[0].name}} IS '{{summary[0].title}}';
{% for field in fields %} {% for field in fields %}

View File

@ -23,7 +23,7 @@ NOT NULL
{%- endif -%} {%- endif -%}
{% endmacro %} {% endmacro %}
{% macro primary() %} {% macro primary() %}
primary key({{summary[0].primary}}) primary key({{','.join(summary[0].primary)}})
{% endmacro %} {% endmacro %}
DROP TABLE IF EXISTS {{summary[0].name}}; DROP TABLE IF EXISTS {{summary[0].name}};
CREATE TABLE {{summary[0].name}} CREATE TABLE {{summary[0].name}}
@ -33,10 +33,8 @@ CREATE TABLE {{summary[0].name}}
{% endfor %} {% endfor %}
{{primary()}} {{primary()}}
); );
{% for v in validation %} {% for v in indexes %}
{% if v.oper=='idx' %} CREATE {% if v.idxtype=='unique' %}UNIQUE{% endif %} INDEX {{summary[0].name}}_{{v.name}} ON {{summary[0].name}}({{",".join(v.idxfields)}});
CREATE {% if v.value.idxtype=='unique' %}UNIQUE{% endif %} INDEX {{summary[0].name}}_{{v.name}} ON {{summary[0].name}}({{",".join(v.value.fields)}});
{% endif %}
{%- endfor -%} {%- endfor -%}
COMMENT ON TABLE {{summary[0].name}} IS '{{summary[0].title.decode('utf8')}}'; COMMENT ON TABLE {{summary[0].name}} IS '{{summary[0].title.decode('utf8')}}';
{% for field in fields %} {% for field in fields %}

View File

@ -26,7 +26,7 @@ NOT NULL
{% endmacro %} {% endmacro %}
{% macro primary() %} {% macro primary() %}
,primary key({{summary[0].primary}}) ,primary key({{','.join(summary[0].primary)}})
{% endmacro %} {% endmacro %}
drop table dbo.{{summary[0].name}}; drop table dbo.{{summary[0].name}};
@ -37,10 +37,8 @@ CREATE TABLE dbo.{{summary[0].name}}
{% endfor %} {% endfor %}
{{primary()}} {{primary()}}
) )
{% for v in validation %} {% for v in indexes %}
{% if v.oper=='idx' %} CREATE {% if v.idxtype=='unique' %}UNIQUE{% endif %} INDEX {{summary[0].name}}_{{v.name}} ON {{summary[0].name}}({{",".join(v.idxfields)}});
CREATE {% if v.value.idxtype=='unique' %}UNIQUE{% endif %} INDEX {{summary[0].name}}_{{v.name}} ON {{summary[0].name}}({{",".join(v.value.fields)}});
{% endif %}
{%- endfor -%} {%- endfor -%}
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'{{summary[0].title}}' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'{{summary[0].name}}' EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'{{summary[0].title}}' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'{{summary[0].name}}'
{% for field in fields %} {% for field in fields %}

View File

@ -153,8 +153,7 @@ from
def indexesSQL(self,tablename=None): def indexesSQL(self,tablename=None):
sqlcmd = """SELECT sqlcmd = """SELECT
index_name=lower(IDX.Name), index_name=lower(IDX.Name),
index_type=case when KC.type_desc is null then 'primary' WHEN IDX.is_unique=1 THEN 'unique' ELSE 'ununique' END, index_type=IDX.is_unique,
table_name=lower(O.Name),
column_name=lower(C.Name) column_name=lower(C.Name)
FROM sys.indexes IDX FROM sys.indexes IDX
INNER JOIN sys.index_columns IDXC INNER JOIN sys.index_columns IDXC

View File

@ -50,7 +50,12 @@ class MySqlor(SQLor):
} }
@classmethod @classmethod
def isMe(self,name): def isMe(self,name):
return name=='mysql.connector' print('*********name=',name,'*************')
if name=='mysql.connector':
return True
if name=='aiomysql':
return True
return False
def grammar(self): def grammar(self):
return { return {
@ -149,26 +154,14 @@ limit $[from_line]$,$[rows]$"""
return sqlcmd return sqlcmd
def pkSQL(self,tablename=None): def pkSQL(self,tablename=None):
sqlcmd = """SELECT sqlcmd = """SELECT column_name as name FROM INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` WHERE table_name='%s' AND constraint_name='PRIMARY'
lower(c.table_name) as table_name, """ % tablename.lower()
lower(c.COLUMN_NAME) as field_name
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS t,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS c
WHERE
t.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND t.TABLE_SCHEMA = '%s'
AND t.TABLE_NAME = c.TABLE_NAME
""" % self.dbdesc.get('dbname','unknown').lower()
if tablename is not None:
sqlcmd = sqlcmd + " AND c.TABLE_NAME = '%s'" % tablename.lower()
return sqlcmd return sqlcmd
def indexesSQL(self,tablename=None): def indexesSQL(self,tablename=None):
sqlcmd = """SELECT DISTINCT sqlcmd = """SELECT DISTINCT
lower(index_name) as index_name, lower(index_name) as index_name,
lower(index_type) as index_type, NON_UNIQUE as is_unique,
lower(table_name) as table_name,
lower(column_name) as column_name lower(column_name) as column_name
FROM FROM
information_schema.statistics information_schema.statistics

View File

@ -120,8 +120,7 @@ where
def indexesSQL(self,tablename=None): def indexesSQL(self,tablename=None):
sqlcmd = """select sqlcmd = """select
lower(a.index_name) index_name, lower(a.index_name) index_name,
lower(a.UNIQUENESS) index_type, lower(a.UNIQUENESS) is_unique,
lower(a.table_name) table_name,
lower(b.column_name) column_name lower(b.column_name) column_name
from user_indexes a, user_ind_columns b from user_indexes a, user_ind_columns b
where a.index_name = b.index_name""" where a.index_name = b.index_name"""

View File

@ -139,57 +139,9 @@ where
return sqlcmd return sqlcmd
def indexesSQL(self,tablename=None): def indexesSQL(self,tablename=None):
"""
SELECT
A.SCHEMANAME,
A.TABLENAME,
A.INDEXNAME,
A.TABLESPACE,
A.INDEXDEF,
B.AMNAME,
C.INDEXRELID,
C.INDNATTS,
C.INDISUNIQUE,
C.INDISPRIMARY,
C.INDISCLUSTERED,
D.DESCRIPTION
FROM
PG_AM B
LEFT JOIN PG_CLASS F ON B.OID = F.RELAM
LEFT JOIN PG_STAT_ALL_INDEXES E ON F.OID = E.INDEXRELID
LEFT JOIN PG_INDEX C ON E.INDEXRELID = C.INDEXRELID
LEFT OUTER JOIN PG_DESCRIPTION D ON C.INDEXRELID = D.OBJOID,
PG_INDEXES A
WHERE
A.SCHEMANAME = E.SCHEMANAME AND A.TABLENAME = E.RELNAME AND A.INDEXNAME = E.INDEXRELNAME
AND E.SCHEMANAME = 'public' AND E.RELNAME = 'table_name'
"""
sqlcmd = """select sqlcmd = """select
lower(a.index_name) index_name, lower(a.index_name) index_name,
lower(a.UNIQUENESS) index_type, lower(a.UNIQUENESS) is_unique,
lower(a.table_name) table_name,
lower(b.column_name) column_name lower(b.column_name) column_name
from user_indexes a, user_ind_columns b from user_indexes a, user_ind_columns b
where a.index_name = b.index_name""" where a.index_name = b.index_name"""

View File

@ -9,9 +9,9 @@ from appPublic.myImport import myImport
from appPublic.dictObject import DictObject,dictObjectFactory from appPublic.dictObject import DictObject,dictObjectFactory
from appPublic.unicoding import uDict from appPublic.unicoding import uDict
from appPublic.myTE import MyTemplateEngine from appPublic.myTE import MyTemplateEngine
from appPublic.objectAction import ObjectAction
from appPublic.argsConvert import ArgsConvert,ConditionConvert from appPublic.argsConvert import ArgsConvert,ConditionConvert
from .filter import DBFilter
class SQLorException(Exception,object): class SQLorException(Exception,object):
def __int__(self,**kvs): def __int__(self,**kvs):
@ -65,7 +65,18 @@ class SQLor(object):
self.convfuncs = {} self.convfuncs = {}
self.cc = ConditionConvert() self.cc = ConditionConvert()
self.dataChanged = False self.dataChanged = False
self.metadatas={}
def setMeta(self,tablename,meta):
self.metadatas[tablename.lower()] = meta
def getMeta(self,tablename):
return self.metadatas.get(tablename.lower(),None)
def removeMeta(self,tablename):
if getMeta(self.tablename):
del self.metadatas[tablename.lower()]
def setCursor(self,async_mode,conn,cur): def setCursor(self,async_mode,conn,cur):
self.async_mode = async_mode self.async_mode = async_mode
self.conn = conn self.conn = conn
@ -455,28 +466,36 @@ class SQLor(object):
return await self.sqlExecute(desc,{}) return await self.sqlExecute(desc,{})
async def getTableDesc(self,tablename): async def getTableDesc(self,tablename):
desc = self.getMeta(tablename)
if desc:
return desc
desc = {} desc = {}
summary = [ i for i in await self.tables() if tablename.lower() == i.name ] summary = [ i for i in await self.tables() if tablename.lower() == i.name ]
primary = [i.field_name for i in await self.primary(tablename) ] print('summary=',summary)
summary['primary'] = primary pris = await self.primary(tablename)
print('primary key=',pris)
primary = [i.name for i in pris ]
summary[0]['primary'] = primary
desc['summary'] = summary desc['summary'] = summary
desc['fields'] = await self.fields(tablename=tablename) desc['fields'] = await self.fields(tablename=tablename)
desc['validation'] = [] desc['indexes'] = []
idx = {} idx = {}
async for idxrec in self.indexes(tablename=tablename): idxrecs = await self.indexes(tablename)
for idxrec in idxrecs:
if idxrec.index_name == 'primary':
continue
if idxrec.index_name != idx.get('name',None): if idxrec.index_name != idx.get('name',None):
if idx != {}: if idx != {}:
desc['validation'].append(idx) desc['indexes'].append(idx)
idx = { idx = {
'fields':[]
} }
else:
idx['fields'] = []
idx['name'] = idxrec.index_name idx['name'] = idxrec.index_name
idx['oper'] = 'idx' idx['idxtype'] = 'unique' if idxrec.is_unique else 'index'
idx['fields'].append(idxrec.field_name) idx['idxfields'] = []
idx['idxfields'].append(idxrec.column_name)
if idx != {}: if idx != {}:
desc['validation'].append(idx) desc['indexes'].append(idx)
self.setMeta(tablename,desc)
return desc return desc
async def rollback(self): async def rollback(self):
@ -492,3 +511,57 @@ class SQLor(object):
else: else:
self.conn.commit() self.conn.commit()
self.datachanged = False self.datachanged = False
async def I(self,tablename):
return await self.getTableDesc(tablename)
async def C(self,tablename,ns):
desc = await self.I(tablename)
fields = [ i['name'] for i in desc['fields']]
fns = ','.join(fields)
vfns = ','.join(['${%s}$' % n for n in fields ])
sql = 'insert into %s (%s) values (%s)' % (tablename,fns,vfns)
await self.runSQL({'sql_string':sql},ns,None)
async def R(self,tablename,ns,filters=None):
desc = await self.I(tablename)
sql = 'select * from %s where 1=1' % tablename.lower()
if filters:
dbf = DBFilter(filters)
sql = '%s and %s' % (sql, dbf.genFilterString())
else:
fields = [ i['name'] for i in desc['fields'] ]
c = [ '%s=${%s}$' % (k,k) for k in ns.keys() if k in fields ]
if len(c) > 0:
sql = '%s and %s' % (sql,' and '.join(c))
if 'page' in ns.keys():
if not 'sort' in ns.keys():
ns['sort'] = desc['summary'][0]['primary'][0]
return await self.pagingdata({'sql_string':sql},ns)
else:
return await self.sqlExe(sql,ns)
async def U(self,tablename,ns):
desc = await self.I(tablename)
fields = [ i['name'] for i in desc['fields']]
condi = [ i for i in desc['summary'][0]['primary']]
newData = [ i for i in ns.keys() if i not in condi and i in fields]
c = [ '%s = ${%s}$' % (i,i) for i in condi ]
u = [ '%s = ${%s}$' % (i,i) for i in newData ]
c_str = ','.join(c)
u_str = ','.join(u)
sql = 'update %s set %s where %s' % (tablename,
u_str,c_str)
await self.runSQL({'sql_string':sql},ns,None)
pass
async def D(self,tablename,ns):
desc = await self.I(tablename)
fields = [ i['name'] for i in desc['fields']]
condi = [ i for i in desc['summary'][0]['primary']]
c = [ '%s = ${%s}$' % (i,i) for i in condi ]
c_str = ','.join(c)
sql = 'delete from %s where %s' % (tablename,c_str)
await self.runSQL({'sql_string':sql},ns,None)