Package: pip-services3-sqlserver
SQLServer components for PythonThis module is a part of thePip.Servicespolyglot microservices toolkit.The module contains the following packages:Build- a standard factory for constructing componentsConnect- instruments for configuring connections to the database.Persistence- abstract classes for working with the database that can be used for connecting to collections and performing basic CRUD operationsQuick links:ODBC Driver for SQL ServerConfigurationAPI ReferenceChange LogGet HelpContributeUseInstall the Python package aspipinstallpip-services3-sqlserverAs an example, lets create persistence for the following data object.classMyObject(IStringIdentifiable):def__init__(self,id:str=None,key:str=None,content:str=None):self.id=idself.key=keyself.content=contentThe persistence component shall implement the following interface with a basic set of CRUD operations.fromabcimportABCfromtypingimportUnion,Listfrompip_services3_commons.dataimportIIdentifiable,PagingParams,FilterParams,DataPageclassIMyPersistence(ABC):defget_page_by_filter(self,correlation_id:Optional[str],filter:Any,paging:Any)->DataPage:raiseNotImplemented()defget_one_by_id(self,correlation_id:Optional[str],id:str)->MyObject:raiseNotImplemented()defget_one_by_key(self,correlation_id:Optional[str],key:List[str])->MyObject:raiseNotImplemented()defcreate(self,correlation_id:Optional[str],item:MyObject)->MyObject:raiseNotImplemented()defupdate(self,correlation_id:Optional[str],item:MyObject)->MyObject:raiseNotImplemented()defdelete_by_id(self,correlation_id:Optional[str],id:str):raiseNotImplemented()To implement sql server persistence component you shall inheritIdentifiableSqlServerPersistence.
Most CRUD operations will come from the base class. You only need to overrideget_page_by_filtermethod with a custom filter function.
And implement aget_one_by_keycustom persistence method that doesn't exist in the base class.classMySqlServerPersistence(IdentifiableSqlServerPersistence):def__init__(self):super(MySqlServerPersistence,self).__init__('myobjects')self._auto_create_object("CREATE TABLE [myobjects] ([id] VARCHAR(32) PRIMARY KEY, [key] VARCHAR(50), [value] NVARCHAR(255)")self._ensure_index("myobjects_key",{'[key]':1},{'unique':True})def__compose_filter(self,filter):filter=filterorFilterParams()criteria=[]id=filter.get_as_nullable_string('id')ifidisnotNone:criteria.append("[id]='"+id+"'")temp_ids=filter.get_as_nullable_string('ids')iftemp_idsisnotNone:ids=temp_ids.split(',')criteria.append("[id] IN ('"+"','".join(ids)+"')")key=filter.get_as_nullable_string('key')ifkeyisnotNone:criteria.append("[key]='"+key+"'")return" AND ".join(criteria)iflen(criteria)>0elseNonedefget_page_by_filter(self,correlation_id,filter,paging,sort,select):returnsuper().get_page_by_filter(correlation_id,self.__compose_filter(filter),paging,'id',None)defget_one_by_key(self,correlation_id,key):query="SELECT * FROM "+self._quoted_table_name()+" WHERE [key]=?"params=[key]result=self._request(query,params)item=result[0]orNoneifresultandresult[0]elseNoneifitemisNone:self._logger.trace(correlation_id,"Nothing found from%swith key =%s",self._table_name,key)else:self._logger.trace(correlation_id,"Retrieved from%swith key =%s",self._table_name,key)item=self._convert_to_public(item)returnitemAlternatively you can store data in non-relational format usingIdentificableJsonSqlServerPersistence.
It stores data in tables with two columns -idwith unique object id anddatawith object data serialized as JSON.
To access data fields you shall useJSON_VALUE([data],'$.field')expression.frompip_services3_sqlserver.persistence.IdentifiableJsonSqlServerPersistenceimportIdentifiableJsonSqlServerPersistenceclassMySqlServerPersistence(IdentifiableJsonSqlServerPersistence):def__init__(self):super(MySqlServerPersistence,self).__init__('myobjects')self._ensure_table()self._auto_create_object("ALTER TABLE [myobjects] ADD [data_key] AS JSON_VALUE([data],'$.key')")self._ensure_index("myobjects_key",{'data_key':1},{'unique':True})def__compose_filter(self,filter):filter=filterorFilterParams()criteria=[]id=filter.get_as_nullable_string('id')ifidisnotNone:criteria.append("JSON_VALUE([data],'$.id')='"+id+"'")temp_ids=filter.get_as_nullable_string('ids')iftemp_idsisnotNone:ids=temp_ids.split(',')criteria.append("JSON_VALUE([data],'$.id') IN ('"+"','".join(ids)+"')")key=filter.get_as_nullable_string('key')ifkeyisnotNone:criteria.append("JSON_VALUE([data],'$.key')='"+key+"'")return" AND ".join(criteria)iflen(criteria)>0elseNonedefget_page_by_filter(self,correlation_id,filter,paging,sort,select):returnsuper().get_page_by_filter(correlation_id,self.__compose_filter(filter),paging,'id',None)defget_one_by_key(self,correlation_id,key):query="SELECT * FROM "+self._quoted_table_name()+" WHERE JSON_VALUE([data],'$.key')=?"params=[key]result=self._request(query,params)item=result[0]orNoneifresultandresult[0]elseNoneifitemisNone:self._logger.trace(correlation_id,"Nothing found from%swith key =%s",self._table_name,key)else:self._logger.trace(correlation_id,"Retrieved from%swith key =%s",self._table_name,key)item=self._convert_to_public(item)returnitemConfiguration for your microservice that includes sqlserver persistence may look the following way....{{#if SQLSERVER_ENABLED}}- descriptor:pip-services:connection:sqlserver:con1:1.0table:{{SQLSERVER_TABLE}}{{#unless SQLSERVER_TABLE}}myobjects{{/unless}}connection:uri:{{{SQLSERVER_SERVICE_URI}}}host:{{{SQLSERVER_SERVICE_HOST}}}{{#unless SQLSERVER_SERVICE_HOST}}localhost{{/unless}}port:{{SQLSERVER_SERVICE_PORT}}{{#unless SQLSERVER_SERVICE_PORT}}1433{{/unless}}database:{{SQLSERVER_DB}}{{#unless SQLSERVER_DB}}app{{/unless}}credential:username:{{SQLSERVER_USER}}password:{{SQLSERVER_PASS}}- descriptor:myservice:persistence:sqlserver:default:1.0dependencies:connection:pip-services:connection:sqlserver:con1:1.0{{/if}}...DevelopFor development you shall install the following prerequisites:Python 3.7+Visual Studio Code or another IDE of your choiceDockerInstall dependencies:pipinstall-rrequirements.txtRun automated tests:pythontest.pyGenerate API documentation:./docgen.ps1Before committing changes run dockerized build and test as:./build.ps1
./test.ps1
./clear.ps1ContactsThe library is created and maintained by:Sergey SeroukhovDanil PrisiazhnyiThe documentation is written byMark Makarychev.