开发者

php DAL out of a schema

I developed a web platform in PHP a year ago, and I was kinda proud of the data access layer I wrote for it. Since then, I started re-using the same concept over and over. But now I'm thinking to take it to the next level, instead of re-writing the whole database access code I'd like to create a tool that will parse my SQL schema and generate the DAL classes by itself.

The information needed from the SQL schema in order to generate the code is:

* Tables
* Fields
* Fields types
* Foreign keys

Indeed, I looked up for some SQL parser and found some stuff but I ended up by deciding to do this differently. Instead of generating the code from the SQL schema itself, I'd generate it from a meta data that I'd create according to t开发者_开发技巧he database real schema.

I thought of something like:

TableName[
   FieldA : Type;
   FieldB:  Type;
]
TableName2[
   FieldA : Type, FK(TableName.FieldA);
   FieldZ:  Type;
]

This is not a spec at all, it's just a quick thinking result that says what kind of stuff I'd like to achieve.

The question now is: Does python have some built-in API, or maybe some 3rd party library I could use to parse some format that'd let me define my schema as stated above? I don't want to reinvent the wheel, and I'm not interested at all in writing my own parser, all I want is getting a basic and working tool ASAP.

Thanks


The immitiate thought would be to simply use regular python syntax to define your tables:

{
    'TableName': {'FieldA': ['Type', FK(..)], 'FieldB': ['type']}
}

and so on.

You could however have a look at how django does it: you define a class and add properties to that class, which will then represent your model. This model can then be used to generate the SQL statements, and is also valid - and easily extendable - Python code.

Other suggestions could be to use a JSON structure to represent your data, and then write some code to parse that one. This would be similar to using the existing python syntax, but would be easier to parse in other languages (the example given above would be almost valid JSON syntax out of the box (replace ' with ").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜