Просмотр исходного кода

Merge remote-tracking branch 'origin/master'

# Conflicts:
#	src/index.js
Csy817 7 лет назад
Родитель
Сommit
57c4b7acd5

+ 230 - 421
src/components/common/schema/Schema.jsx

@@ -3,462 +3,271 @@ import React, {Component} from 'react';
 import {Row, Col, Input, Icon, Button, Spin} from 'antd';
 import {Row, Col, Input, Icon, Button, Spin} from 'antd';
 import './index.css';
 import './index.css';
 import SchemaChange from './change/SchemaChange';
 import SchemaChange from './change/SchemaChange';
-import gql from "graphql-tag";
 import {Mutation, Query} from "react-apollo";
 import {Mutation, Query} from "react-apollo";
+import {SHOW_SCHEMA, ADD_SCHEMA, DELETE_SCHEMA, SHOW_TABLE} from './gql'
 
 
 const Search = Input.Search;
 const Search = Input.Search;
 
 
 const idGen = (kind) => {
 const idGen = (kind) => {
-  return kind + '_' + Date.now() + '_' + Math.random().toString().slice(-8);
+    return kind + '_' + Date.now() + '_' + Math.random().toString().slice(-8);
 };
 };
 
 
+
 class Schema extends Component {
 class Schema extends Component {
-  constructor(props) {
-    super(props);
-    this.state = {
-      currentSchema: '',
-      currentTable: '',
-      schemas: [
-        {
-          name: 'magazineApp',
-          tables: [
-            {
-              name: 'magazine',
-              remark: 'magazine list',
-              cols: [
-                {
-                  name: 'id',
-                  type: 'ID',
-                  desc: 'key'
-                },
-                {
-                  name: 'name',
-                  type: 'string',
-                  desc: 'non-null'
-                },
-                {
-                  name: 'suitableGrade',
-                  type: 'int',
-                  desc: 'non-null-list'
-                },
-                {
-                  name: 'picture',
-                  type: 'string',
-                  desc: 'description'
-                },
-                {
-                  name: 'magazineIntro',
-                  type: 'string',
-                  desc: 'description'
-                },
-                {
-                  name: 'unitPrice',
-                  type: 'float',
-                  desc: 'description'
-                },
-                {
-                  name: 'enableSub',
-                  type: 'int',
-                  desc: 'list'
-                }
-              ]
-            },
-            {
-              name: 'slideshow',
-              remark: 'slideshow list',
-              cols: [
-                {
-                  name: 'id',
-                  type: 'ID',
-                  desc: 'key'
-                },
-                {
-                  name: 'briefIntro',
-                  type: 'string',
-                  desc: 'description'
-                },
-                {
-                  name: 'picture',
-                  type: 'string',
-                  desc: 'description'
-                }
-              ]
-            }
-          ]
-        },
-        {
-          name: 'onlineApp',
-          tables: [
-            {
-              name: 'database',
-              remark: 'database configs',
-              cols: [
-                {
-                  name: 'dbname',
-                  type: 'string',
-                  desc: 'non-null'
-                },
-                {
-                  name: 'dbConfig',
-                  type: 'string',
-                  desc: 'non-null'
-                },
-                {
-                  name: 'createdAt',
-                  type: 'string',
-                  desc: 'description'
-                },
-                {
-                  name: 'updatedAt',
-                  type: 'string',
-                  desc: 'description'
-                }
-              ]
-            },
-            {
-              name: 'deploy',
-              remark: 'deploy\'s collections ',
-              cols: [
-                {
-                  name: 'cloud_id',
-                  type: 'string',
-                  desc: 'non-null'
-                },
-                {
-                  name: 'schema_id',
-                  type: 'string',
-                  desc: 'non-null'
-                },
-                {
-                  name: 'user_id',
-                  type: 'string',
-                  desc: 'description'
-                }
-              ]
-            }
-          ]
-        }
-      ],
-    };
-    if (this.state.schemas.length !== 0) {
-      this.state.currentSchema = this.state.schemas[0].name;
-      this.state.currentTable = this.state.schemas[0].tables[0].name;
+    constructor(props) {
+        super(props);
+        this.state = {
+            currentSchema: '',
+            currentTable: '',
+            schemaID: 'schema_1542089023472_19873755',
+            userID: 'xy_1'
+        };
     }
     }
-  }
 
 
-  addTable = (columns, remark, tableName, schemaName) => {
-    let schemas = this.state.schemas;
-    let targetSchema = schemas.find(obj => obj.name === schemaName);
-    let targetTable = targetSchema.tables.find(obj => obj.name === tableName);
-    if (targetTable === undefined) {
-      targetSchema.tables.push({name: tableName, remark, cols: columns})
-    } else {
-      targetTable.remark = remark;
-      targetTable.cols = columns;
-    }
-    this.setState({
-      schemas
-    })
-  };
+    findColumns = data => this.state.currentTable === '' ? [] : data.find(table => table.name === this.state.currentTable) ? data.find(table => table.name === this.state.currentTable).cols : [];
 
 
-  deleteTable = (tableName, schemaName) => {
-    let schemas = this.state.schemas;
-    let targetSchemaIndex = schemas.findIndex(obj => obj.name === schemaName);
-    let targetTableIndex = schemas.find(obj => obj.name === schemaName).tables.findIndex(obj => obj.name === tableName);
-    schemas[targetSchemaIndex].tables.splice(targetTableIndex, 1);
-    this.setState({
-      schemas
-    });
+    findRemark = data => this.state.currentTable === '' ? '' : data.find(table => table.name === this.state.currentTable) ? data.find(table => table.name === this.state.currentTable).remark : '';
 
 
-    let tables = this.state.schemas.find(obj => obj.name === this.state.currentSchema).tables;
-    if (tables.length !== 0) {
-      this.setState({
-        currentTable: tables[0].name
-      })
-    } else {
-      this.setState({
-        currentTable: ''
-      })
-    }
-  };
+    switchSchema = (schema) => {
+        this.setState({
+            currentSchema: schema
+        });
+    };
 
 
-  addSchema = (name) => {
-    this.setState({
-      schemas: [...this.state.schemas, {
-        name,
-        tables: []
-      }]
-    });
-  };
+    switchTable = (table) => {
+        this.setState({
+            currentTable: table
+        })
+    };
 
 
-  findColumns = () => {
-    let schema = this.state.schemas.find(schema => schema.name === this.state.currentSchema);
-    if (schema === undefined) return [];
-    //  if user insert a new schema, after merge to schemas with a {name: 'xx', tables: []}
-    //  you can find the following table is undefined.
-    //  so give a state here if you want add a tip!
-    else {
-      let table = schema.tables.find(table => table.name === this.state.currentTable);
-      if (table === undefined) return [];
-      else return table.cols;
-    }
-  };
+    render() {
+        return (
+            <div>
+                <Row>
+                    <Col span={6}>
+                        <div className='wrapper'>
+                            <div className='current'>{this.state.currentSchema}</div>
+                            <AddSchemaInput userID={this.state.userID}/>
+                        </div>
+                        <ShowSchemaList
+                            userID={this.state.userID}
+                            switchTable={this.switchTable}
+                            switchSchema={this.switchSchema}/>
+                    </Col>
 
 
-  findRemark = () => {
-    let schema = this.state.schemas.find(schema => schema.name === this.state.currentSchema);
-    if (schema === undefined) return '';
-    else {
-      let table = schema.tables.find(table => table.name === this.state.currentTable);
-      if (table === undefined) return '';
-      else return table.remark;
+                    <Col span={17} offset={1}>
+                        {
+                            this.state.currentTable === 'add' ?
+                                <SchemaChange
+                                    currentSchema={this.state.currentSchema}
+                                    currentTableIndex={-2}
+                                    columns={[]}
+                                    remark=''
+                                    schemaID={this.state.schemaID}
+                                /> :
+                                <Query query={SHOW_TABLE}
+                                       variables={{schema_id: this.state.schemaID}}>
+                                    {
+                                        ({loading, error, data}) => {
+                                            if (loading)
+                                                return <Spin style={{marginLeft: 30, marginTop: 10}}/>;
+                                            if (error)
+                                                return 'error';
+                                            if (data.schema_by_id === null) data = [];
+                                            else data = JSON.parse(data.schema_by_id.schemaData);
+                                            return (
+                                                <SchemaChange
+                                                    currentSchema={this.state.currentSchema}
+                                                    currentTable={this.state.currentTable}
+                                                    currentTableIndex={this.state.currentTable === '' ? -2 : data.findIndex(obj => obj.name === this.state.currentTable)}
+                                                    columns={this.findColumns(data)}
+                                                    remark={this.findRemark(data)}
+                                                    schemaID={this.state.schemaID}
+                                                    userID={this.state.userID}
+                                                />
+                                            )
+                                        }
+                                    }
+                                </Query>
+                        }
+                    </Col>
+                </Row>
+            </div>
+        )
     }
     }
-  };
-
-  fetchSchemas = (schemas) => {
-    this.setState({
-      schemas
-    })
-  };
-
-  render() {
-    return (
-        <div>
-          <Row>
-            <Col span={6}>
-              <div className='wrapper'>
-                <div className='current'>{this.state.currentSchema}</div>
-                <AddSchemaInput userID={this.props.userID} addSchema={this.addSchema}/>
-              </div>
-              <ShowSchemaList schemas={this.state.schemas} fetchSchemas={this.fetchSchemas}/>
-            </Col>
-
-            <Col span={17} offset={1}>
-              {
-                this.state.currentTable === 'add' ?
-                    <SchemaChange currentSchema={this.state.currentSchema} columns={[]} remark=''
-                                  addTable={this.addTable}
-                                  deleteTable={this.deleteTable}/> :
-                    <SchemaChange currentSchema={this.state.currentSchema} currentTable={this.state.currentTable}
-                                  columns={this.findColumns()} remark={this.findRemark()} addTable={this.addTable}
-                                  deleteTable={this.deleteTable}/>
-              }
-            </Col>
-          </Row>
-        </div>
-    )
-  }
 }
 }
 
 
 export default Schema;
 export default Schema;
 
 
 class AddSchemaInput extends Component {
 class AddSchemaInput extends Component {
 
 
-  render() {
-    let varobj = {
-      id: idGen('schema'),
-      user_id: this.props.userID,
-      createdAt: new Date().getTime(),
-      updatedAt: '',
-      schemaState: 'create',
-    };
-
-    const ADD_SCHEMA = gql`
-            mutation SCHEMA($id: ID!, $user_id: String!, $schemaName: String!, $schemaData: String!, $createdAt: String, $updatedAt: String, $schemaState: String) {
-                create_schema(
-                    id: $id,
-                    user_id: $user_id,
-                    schemaName: $schemaName,
-                    createdAt: $createdAt,
-                    updatedAt: $updatedAt,
-                    schemaData: $schemaData,
-                    schemaState: $schemaState
-                ) {
-                    id,
-                    schemaName
-                }
-            }
-        `;
+    render() {
+        let userID = this.props.userID;
 
 
+        let varobj = {
+            id: idGen('schema'),
+            user_id: userID,
+            createdAt: new Date().getTime(),
+            updatedAt: '',
+            schemaState: 'create',
+            schemaData: JSON.stringify([])
+        };
 
 
-    return (
-        <Mutation mutation={ADD_SCHEMA}>
-          {(create_schema, {loading, error}) => {
-            if (loading)
-              return <Spin style={{marginLeft: 30, marginTop: 10}}/>;
-            if (error)
-              return 'error';
-            return (
-                <div>
-                  <Search
-                      className='add-input'
-                      placeholder="input schema_name"
-                      enterButton="Confirm"
-                      onSearch={value => {
-                        this.setState({
-                          switch: true,
-                          currentSchema: value,
-                          currentTable: ''
-                        });
-                        this.props.addSchema(value);
-                        create_schema({
-                          variables: {
-                            ...varobj,
-                            schemaName: value,
-                            schemaData: JSON.stringify({
-                              name: value,
-                              tables: []
-                            })
-                          }
-                        });
-                      }}
-                  />
-                </div>)
-          }}
-        </Mutation>
-    )
-  }
-}
 
 
-class ShowSchemaList extends Component {
+        return (
+            <Mutation
+                mutation={ADD_SCHEMA}
+                update={(cache, {data: {create_schema}}) => {
+                    let data = cache.readQuery({query: SHOW_SCHEMA, variables: {user_id: userID}});
 
 
-  switchSchema = (schema) => {
-    return () => {
-      this.setState({
-        currentSchema: schema
-      });
-      // when this schema has no table, show new
-      if (this.state.schemas.find(obj => obj.name === schema).tables.length === 0) {
-        this.setState({
-          currentTable: ''
-        })
-      }
-    }
-  };
+                    data.schema_by_props.push(create_schema);
+                    cache.writeQuery({
+                        query: SHOW_SCHEMA,
+                        variables: {user_id: userID},
+                        data
+                    });
+                }}
+            >
 
 
-  deleteSchema = (e, schemaName) => {
-    e.stopPropagation();
-    let schemas = this.state.schemas;
-    let targetSchemaIndex = schemas.findIndex(obj => obj.name === schemaName);
-    if (targetSchemaIndex !== -1) {
-      schemas.splice(targetSchemaIndex, 1);
-      this.setState({
-        schemas
-      });
+                {(create_schema, {loading, error}) => {
+                    if (loading)
+                        return <Spin style={{marginLeft: 30, marginTop: 10}}/>;
+                    if (error)
+                        return 'error';
+                    return (
+                        <div>
+                            <Search
+                                className='add-input'
+                                placeholder="input schema_name"
+                                enterButton="Confirm"
+                                onSearch={value => {
+                                    this.setState({
+                                        switch: true,
+                                        currentSchema: value,
+                                        currentTable: ''
+                                    });
+                                    create_schema({
+                                        variables: {
+                                            ...varobj,
+                                            schemaName: value
+                                        }
+                                    });
+                                }}
+                            />
+                        </div>)
+                }}
+            </Mutation>
+        )
     }
     }
-    if (this.state.schemas.length !== 0) {
-      this.setState({
-        currentSchema: this.state.schemas[0].name,
-        currentTable: this.state.schemas[0].tables[0] ? this.state.schemas[0].tables[0].name : ''
-      })
-    } else {
-      this.setState({
-        currentSchema: '',
-        currentTable: ''
-      })
-    }
-
-  };
+}
 
 
-  switchTable = (table) => {
-    return () => {
-      this.setState({
-        currentTable: table
-      })
-    };
-  };
+class ShowSchemaList extends Component {
+    render() {
+        let userID = this.props.userID;
+        return (
+            <Query query={SHOW_SCHEMA} variables={{user_id: userID}}>
 
 
-  render() {
-    const SHOW_SCHEMA = gql`
-            query SCHEMA($user_id: String) {
-                schema_by_props(user_id: $user_id) {
-                    schemaData
-                    schemaName
-                }
-            }
-        `;
-    return (
-        <Query query={SHOW_SCHEMA} variables={{user_id: this.props.userID}}>
-          {
-            ({loading, error, data}) => {
-              if (loading) {
-                return <Spin style={{marginLeft: 3}}/>
-              }
-              if (error) {
-                return 'error!';
-              }
-              if (data.schema_by_props.length === 0)
-                return (
-                    <div>
-                      <span>no schemas, create one</span>
-                    </div>
-                );
-              else {
-                console.log('getttttttttt', data);
-                let schemas = data.schema_by_props.map(dataSchema =>
-                  JSON.parse(dataSchema.schemaData)
-                );
-                console.log(schemas);
-                // this.props.fetchSchemas(schemas);
+                {
+                    ({loading, error, data}) => {
+                        if (loading) {
+                            return <Spin style={{marginLeft: 3}}/>
+                        }
+                        if (error) {
+                            return 'error!';
+                        }
+                        if (data.schema_by_props.length === 0)
+                            return (
+                                <div>
+                                    <span>no schemas, create one</span>
+                                </div>
+                            );
+                        else {
+                            return (
+                                <div>
+                                    {
+                                        data.schema_by_props.map((schema) => {
+                                            return <div key={schema.schemaName} className='title'
+                                                        onClick={() => {
+                                                            this.props.switchSchema(schema.schemaName)
 
 
-                return (
-                    <div>
-                      {
-                        this.props.schemas.map((schema) => {
-                          return <div key={schema.name} className='title' onClick={this.switchSchema(schema.name)}>
-                            <Row>
-                              <Col span={20}>{schema.name}</Col>
-                              <Col span={4}>
-                                <Button onClick={() => this.setState({currentTable: 'add'})} type="primary"
-                                        shape="circle" icon="plus" size='small'/>
-                                <DeleteSchemaButton schemaName={schema.name} deleteSchema={this.deleteSchema}/>
-                              </Col>
-                            </Row>
+                                                        }}>
+                                                <Row>
+                                                    <Col span={20}>{schema.schemaName}</Col>
+                                                    <Col span={4}>
+                                                        <Button onClick={() => this.props.switchTable('add')}
+                                                                type="primary"
+                                                                shape="circle" icon="plus" size='small'/>
+                                                        <DeleteSchemaButton
+                                                            schemaName={schema.schemaName}
+                                                            userID={this.props.userID}
+                                                        />
+                                                    </Col>
+                                                </Row>
 
 
 
 
-                            {
-                              schema.tables.map((table) =>
-                                  <p onClick={this.switchTable(table.name)} key={table.name} className='show'>
-                                    <Icon type="ordered-list" theme="outlined"/> {table.name}
-                                    <span className='remark'><i>   {table.remark}</i></span>
-                                  </p>
-                              )
-                            }
-                          </div>
-                        })
-                      }
-                    </div>
-                );
-              }
-            }
-          }
-        </Query>
-    )
-  }
+                                                {
+                                                    JSON.parse(schema.schemaData).map(table => (
+                                                        <p
+                                                            onClick={() => {
+                                                                this.props.switchTable(table.name)
+                                                            }}
+                                                            key={table.name}
+                                                            className='show'>
+                                                            <Icon type="ordered-list" theme="outlined"/> {table.name}
+                                                            <span className='remark'><i>   {table.remark}</i></span>
+                                                        </p>
+                                                    ))
+                                                }
+                                            </div>
+                                        })
+                                    }
+                                </div>
+                            );
+                        }
+                    }
+                }
+            </Query>
+        )
+    }
 }
 }
 
 
 class DeleteSchemaButton extends Component {
 class DeleteSchemaButton extends Component {
-  render() {
-    const DELETE_SCHEMA = gql`
-            mutation SCHEMA($schemaName: String) {
-                delete_schema(schemaName: $schemaName)
-            }
-        `;
-    return (
-        <Mutation mutation={DELETE_SCHEMA}>
-          {(delete_schema, {loading, error}) => {
-            if (error)
-              return 'error';
-            if (loading)
-              return <Spin style={{marginLeft: 3}}/>;
-            return (
-                <Button onClick={(e) => {
-                  this.props.deleteSchema(e, this.props.schemaName);
-                  delete_schema({variables: {schemaName: this.props.schemaName}});
-                }} type="danger" shape="circle" icon="delete" size='small' style={{marginLeft: 3}}/>
-            )
-          }}
-        </Mutation>
-    )
-  }
+    constructor(props) {
+        super(props);
+        this.state = {
+            schemaName: props.schemaName
+        }
+    }
+
+    render() {
+        let userID = this.props.userID;
+        return (
+            <Mutation
+                mutation={DELETE_SCHEMA}
+                update={(cache) => {
+                    let data = cache.readQuery({query: SHOW_SCHEMA, variables: {user_id: userID}});
+
+                    data.schema_by_props.splice(data.schema_by_props.findIndex(obj => obj.schemaName === this.state.schemaName), 1);
+                    cache.writeQuery({
+                        query: SHOW_SCHEMA,
+                        variables: {user_id: userID},
+                        data
+                    });
+                }}
+            >
+                {(delete_schema, {loading, error}) => {
+                    if (error)
+                        return 'error';
+                    if (loading)
+                        return <Spin style={{marginLeft: 3}}/>;
+                    return (
+                        <Button onClick={(e) => {
+                            delete_schema({variables: {schemaName: this.props.schemaName}});
+                        }} type="danger" shape="circle" icon="delete" size='small' style={{marginLeft: 3}}/>
+                    )
+                }}
+            </Mutation>
+        )
+    }
 }
 }
 
 

+ 300 - 102
src/components/common/schema/change/SchemaChange.jsx

@@ -1,7 +1,9 @@
 import React, {Component} from 'react';
 import React, {Component} from 'react';
 
 
-import {Select, Input, Icon, Button, notification} from 'antd';
-import gql from "graphql-tag";
+import {Select, Input, Icon, Button, notification, Spin} from 'antd';
+import {UPDATE_SCHEMA, SHOW_SCHEMA, SHOW_TABLE} from "../gql";
+
+import {Mutation, Query} from "react-apollo";
 
 
 const Option = Select.Option;
 const Option = Select.Option;
 
 
@@ -21,6 +23,9 @@ class SchemaChange extends Component {
     }
     }
 
 
 
 
+    // 下面的 handlexxxx 全是 state 内部方法,用于操作视图
+    // cache 仅在提交删除整体使用
+
     handleNameChange = (index) => {
     handleNameChange = (index) => {
         return (e) => {
         return (e) => {
             let columns = this.state.columns;
             let columns = this.state.columns;
@@ -51,7 +56,7 @@ class SchemaChange extends Component {
     handleTypeNew = (value) => {
     handleTypeNew = (value) => {
         if (this.state.newColName !== '') {
         if (this.state.newColName !== '') {
             let columns = this.state.columns;
             let columns = this.state.columns;
-            columns.push({name: this.state.newColName, type: value, desc: 'description'});
+            columns.push({name: this.state.newColName, type: value, description: 'description'});
             this.setState({
             this.setState({
                 columns,
                 columns,
                 newColName: '',
                 newColName: '',
@@ -68,7 +73,7 @@ class SchemaChange extends Component {
     handleDescChange = (index) => {
     handleDescChange = (index) => {
         return (value) => {
         return (value) => {
             let columns = this.state.columns;
             let columns = this.state.columns;
-            columns[index].desc = value;
+            columns[index].description = value;
             this.setState({
             this.setState({
                 columns
                 columns
             });
             });
@@ -97,74 +102,88 @@ class SchemaChange extends Component {
     render() {
     render() {
         return (
         return (
             <div style={{margin: 20}}>
             <div style={{margin: 20}}>
-              <div style={{marginBottom: 20}}>
-                <span className='table-title'> Table name</span>
-                <Input value={this.state.currentTable} placeholder="table_name" style={{width: 120}} onChange={(e) => {
-                    this.setState({currentTable: e.target.value})
-                }}/>
-
-              </div>
-
-              <div style={{marginBottom: 20}}>
-                <span className='table-title'> Table remark</span>
-                <Input value={this.state.remark} placeholder="table_remark" style={{width: 250}} onChange={(e) => {
-                    this.setState({remark: e.target.value})
-                }}/>
-              </div>
-
-              <div>
-                <span className='table-title'> Table columns</span>
-                <span className='column-title'>name</span>
-                <span className='column-title'>type</span>
-                <span className='column-title'>description</span>
-                  {
-                      this.state.columns.map((col, index) =>
-                          <div key={index} style={{marginBottom: 3}}>
-                            <Input style={{width: 120, marginRight: 10}} value={col.name} onChange={this.handleNameChange(index)}/>
-                            <Select defaultValue={col.type} style={{width: 120, marginRight: 10}}
-                                    onChange={this.handleTypeChange(index)}>
-                                {
-                                    this.state.types.map((value) =>
-                                        <Option key={Math.random()} value={value.toLowerCase()}>{value}</Option>
-                                    )
-                                }
-                            </Select>
-                            <Select defaultValue={col.desc} style={{width: 120, marginRight: 10}}
-                                    onChange={this.handleDescChange(index)}>
-                                {
-                                    this.state.descriptions.map((value) =>
-                                        <Option key={Math.random()} value={value.toLowerCase()}>{value}</Option>
-                                    )
-                                }
-                            </Select>
-                            <Icon type="delete" theme="outlined" style={{cursor: 'pointer'}}
-                                  onClick={this.handleColDelete(index)}/>
-                          </div>
-                      )
-                  }
+                <div style={{marginBottom: 20}}>
+                    <span className='table-title'> Table name</span>
+                    <Input value={this.state.currentTable} placeholder="table_name" style={{width: 120}}
+                           onChange={(e) => {
+                               this.setState({currentTable: e.target.value})
+                           }}/>
+
+                </div>
+
+                <div style={{marginBottom: 20}}>
+                    <span className='table-title'> Table remark</span>
+                    <Input value={this.state.remark} placeholder="table_remark" style={{width: 250}} onChange={(e) => {
+                        this.setState({remark: e.target.value})
+                    }}/>
+                </div>
+
                 <div>
                 <div>
-                  <Input placeholder="column_name" style={{width: 120, marginRight: 10}} onChange={this.handleNameNew}
-                         value={this.state.newColName}/>
-                  <Select defaultValue="type" style={{width: 120, marginRight: 10}} onChange={this.handleTypeNew}
-                          value={this.state.newColType}>
-                      {
-                          this.state.types.map((value) =>
-                              <Option key={Math.random()} value={value.toLowerCase()}>{value}</Option>
-                          )
-                      }
-                  </Select>
+                    <span className='table-title'> Table columns</span>
+                    <span className='column-title'>name</span>
+                    <span className='column-title'>type</span>
+                    <span className='column-title'>description</span>
+                    {
+                        this.state.columns.map((col, index) =>
+                            <div key={index} style={{marginBottom: 3}}>
+                                <Input style={{width: 120, marginRight: 10}} value={col.name}
+                                       onChange={this.handleNameChange(index)}/>
+                                <Select defaultValue={col.type} style={{width: 120, marginRight: 10}}
+                                        onChange={this.handleTypeChange(index)}>
+                                    {
+                                        this.state.types.map((value) =>
+                                            <Option key={Math.random()} value={value.toLowerCase()}>{value}</Option>
+                                        )
+                                    }
+                                </Select>
+                                <Select defaultValue={col.description} style={{width: 120, marginRight: 10}}
+                                        onChange={this.handleDescChange(index)}>
+                                    {
+                                        this.state.descriptions.map((value) =>
+                                            <Option key={Math.random()} value={value.toLowerCase()}>{value}</Option>
+                                        )
+                                    }
+                                </Select>
+                                <Icon type="delete" theme="outlined" style={{cursor: 'pointer'}}
+                                      onClick={this.handleColDelete(index)}/>
+                            </div>
+                        )
+                    }
+                    <div>
+                        <Input placeholder="column_name" style={{width: 120, marginRight: 10}}
+                               onChange={this.handleNameNew}
+                               value={this.state.newColName}/>
+                        <Select defaultValue="type" style={{width: 120, marginRight: 10}} onChange={this.handleTypeNew}
+                                value={this.state.newColType}>
+                            {
+                                this.state.types.map((value) =>
+                                    <Option key={Math.random()} value={value.toLowerCase()}>{value}</Option>
+                                )
+                            }
+                        </Select>
+                    </div>
+                </div>
+                <div style={{marginTop: 20}}>
+                    <UpdateTableButton
+                        currentTable={this.state.currentTable}
+                        columns={this.state.columns}
+                        remark={this.state.remark}
+                        currentTableIndex={this.props.currentTableIndex}
+                        schemaID={this.props.schemaID}
+                        userID={this.props.userID}
+                    />
+                    {
+                        // undefined的时候 上层未传进来 currentTable === 'add',为的是输入框内不默认显示 add
+                        this.state.currentTable === ''? '' : this.state.currentTable === undefined ? '' :
+                        <DeleteTableButton
+                            currentTable={this.state.currentTable}
+                            currentTableIndex={this.props.currentTableIndex}
+                            schemaID={this.props.schemaID}
+                            userID={this.props.userID}
+                        />
+                    }
+
                 </div>
                 </div>
-              </div>
-              <div style={{marginTop: 10}}>
-                <Button type="primary" onClick={() => {
-                    this.props.addTable(this.state.columns, this.state.remark, this.state.currentTable, this.state.currentSchema);
-                }}>
-                  SUBMIT
-                </Button>
-                <Button style={{marginLeft: 10}} type="danger" onClick={() => {
-                    this.props.deleteTable(this.state.currentTable, this.state.currentSchema);
-                }}>DELETE</Button>
-              </div>
             </div>
             </div>
         )
         )
     }
     }
@@ -173,47 +192,226 @@ class SchemaChange extends Component {
 export default SchemaChange;
 export default SchemaChange;
 
 
 
 
-// 先搞定 showSchema 再来搞这个
+class UpdateTableButton extends Component {
+
+    render() {
+        let schemaID = this.props.schemaID;
+        let userID = this.props.userID;
+
+        let varobj = {
+            id: schemaID,
+            updatedAt: new Date().getTime(),
+            schemaState: 'updated-update-table',
+        };
+
+        return (
+            <Query query={SHOW_TABLE} variables={{schema_id: schemaID}}>
+
+                {
+                    ({loading, error, data}) => {
+                        if (loading)
+                            return <Spin style={{marginLeft: 30, marginTop: 10}}/>;
+                        if (error)
+                            return 'error';
+
+                        let schemaData = data;
+
+                        return (
+                            <Mutation
+                                mutation={UPDATE_SCHEMA}
+                                update={(cache, {data: {update_schema}}) => {
+                                    let data = cache.readQuery({
+                                        query: SHOW_TABLE,
+                                        variables: {schema_id: schemaID}
+                                    });
+                                    data.schema_by_id = update_schema;
+
+                                    let showSchemaData = cache.readQuery({
+                                        query: SHOW_SCHEMA,
+                                        variables: {user_id: userID}
+                                    });
+                                    let index = showSchemaData.schema_by_props.findIndex(obj => obj.schemaName === update_schema.schemaName);
+                                    showSchemaData.schema_by_props.splice(index, 1, update_schema);
 
 
-class UpdateSchemaButtons extends Component {
+                                    cache.writeQuery(
+                                        {
+                                            query: SHOW_TABLE,
+                                            variables: {schema_id: schemaID},
+                                            data
+                                        },
+                                        {
+                                            query: SHOW_SCHEMA,
+                                            variables: {user_id: userID},
+                                            showSchemaData
+                                        }
+                                    );
+                                }}
+                            >
 
 
-//   update_schema(
-//     createdAt: String
-//   id: ID!
-//   schemaData: String
-//   schemaName: String
-//   schemaState: String
-//   updatedAt: String
-//   user_id: String
-// ): Schema
+                                {(update_schema, {loading, error}) => {
+                                    if (loading)
+                                        return <Spin style={{marginLeft: 30, marginTop: 10}}/>;
+                                    if (error)
+                                        return 'error';
 
 
+                                    // 更新代码
+                                    // 先 query 再 mutation,然后替换,做一个判断
+                                    let schemaCols;
+                                    if (schemaData.schema_by_id === null) schemaCols = [];
+                                    else schemaCols = JSON.parse(schemaData.schema_by_id.schemaData);
+                                    let newTable = {
+                                        name: this.props.currentTable,
+                                        remark: this.props.remark,
+                                        cols: this.props.columns
+                                    };
+
+                                    const index = this.props.currentTableIndex;
+                                    if (index === -2) {
+                                        schemaCols.push(newTable);
+                                    } else if (index === -1) {
+                                        console.log('进行了一次删除操作 或 未知错误,数据库信息不匹配');
+                                    } else {
+                                        schemaCols.splice(index, 1, newTable);
+                                    }
+
+                                    return (
+                                        <div style={{display: 'inline-block'}}>
+                                            <Button type="primary" onClick={() => {
+                                                update_schema({
+                                                    variables: {
+                                                        ...varobj,
+                                                        schemaData: JSON.stringify(schemaCols)
+                                                    }
+                                                });
+                                            }}>
+                                                SUBMIT
+                                            </Button>
+                                        </div>
+                                    )
+                                }}
+                            </Mutation>
+                        )
+                    }
+                }
+
+            </Query>
+        )
+    }
+}
+
+class DeleteTableButton extends Component {
+    render() {
+        let schemaID = this.props.schemaID;
+        let userID = this.props.userID;
 
 
-    render(){
         let varobj = {
         let varobj = {
-            user_id: this.props.userID,
+            id: schemaID,
             updatedAt: new Date().getTime(),
             updatedAt: new Date().getTime(),
-            schemaState: 'updated',
-            id: this.props.schemaID
+            schemaState: 'updated-delete-table',
         };
         };
 
 
-        const ADD_SCHEMA = gql`
-            mutation SCHEMA($id: ID!, $user_id: String!, $schemaName: String!, $schemaData: String!, $createdAt: String, $updatedAt: String, $schemaState: String) {
-                update_schema(
-                    id: $id,
-                    user_id: $user_id,
-                    schemaName: $schemaName,
-                    createdAt: $createdAt,
-                    updatedAt: $updatedAt,
-                    schemaData: $schemaData,
-                    schemaState: $schemaState
-                ) {
-                    id,
-                    schemaName
-                }
-            }
-        `;
         return (
         return (
-            <div>1</div>
+            <Query query={SHOW_TABLE} variables={{schema_id: schemaID}}>
+
+                {
+                    ({loading, error, data}) => {
+                        if (loading)
+                            return <Spin style={{marginLeft: 30, marginTop: 10}}/>;
+                        if (error)
+                            return 'error';
+
+                        let schemaData = data;
+
+                        return (
+                            <Mutation
+                                mutation={UPDATE_SCHEMA}
+                                update={(cache, {data: {update_schema}}) => {
+                                    let data = cache.readQuery({
+                                        query: SHOW_TABLE,
+                                        variables: {schema_id: schemaID}
+                                    });
+                                    data.schema_by_id = update_schema;
+
+                                    let showSchemaData = cache.readQuery({
+                                        query: SHOW_SCHEMA,
+                                        variables: {user_id: userID}
+                                    });
+                                    let schemas = showSchemaData.schema_by_props;
+                                    // console.log('schemas', schemas);
+                                    let targetSchema = schemas.find(obj => obj.schemaName === update_schema.schemaName);
+                                    // console.log('targetSchema', targetSchema);
+                                    let targetSchemaIndex = schemas.findIndex(obj => obj.schemaName === update_schema.schemaName);
+                                    // console.log('targetSchemaIndex', targetSchemaIndex);
+                                    let targetTables = JSON.parse(schemas[targetSchemaIndex].schemaData);
+                                    // console.log('targetTables', targetTables);
+                                    let targetTableIndex = targetTables.findIndex(obj=> obj.name===this.props.currentTable);
+                                    // console.log('targetTableIndex', targetTableIndex);
+                                    targetTables.splice(targetTableIndex, 1);
+                                    // console.log('targetTablesAfterDelete', targetTables);
+                                    let temp = {schemaData: JSON.stringify(targetTables)};
+                                    // console.log('temp', temp);
+                                    let tempSchema = {...targetSchema, ...temp};
+                                    // console.log('tempSchema', tempSchema);
+                                    showSchemaData.schema_by_props.splice(targetSchemaIndex, 1, tempSchema);
+
+                                    cache.writeQuery(
+                                        {
+                                            query: SHOW_TABLE,
+                                            variables: {schema_id: schemaID},
+                                            data
+                                        },
+                                        {
+                                            query: SHOW_SCHEMA,
+                                            variables: {user_id: userID},
+                                            showSchemaData
+                                        }
+                                    );
+                                }}
+                            >
+
+                                {(update_schema, {loading, error}) => {
+                                    if (loading)
+                                        return <Spin style={{marginLeft: 30, marginTop: 10}}/>;
+                                    if (error)
+                                        return 'error';
+
+                                    // 先 query 再 mutation,然后删除
+                                    let schemaCols;
+                                    if (schemaData.schema_by_id === null) schemaCols = [];
+                                    else schemaCols = JSON.parse(schemaData.schema_by_id.schemaData);
+
+                                    const index = this.props.currentTableIndex;
+                                    // 设置-2 标志为新建页面,防止通过 tablename 被修改导致每次 index 都为 -1 从而修改最后一个
+                                    if (index === -2) {
+                                        console.log('初始页面')
+                                    } else if (index === -1) {
+                                        console.log('进行了一次删除操作 或 未知错误,数据库信息不匹配');
+                                    } else {
+                                        schemaCols.splice(index, 1);
+                                    }
+
+                                    return (
+                                        <div style={{display: 'inline-block'}}>
+                                            <Button type="danger"
+                                                    onClick={() => {
+                                                        update_schema({
+                                                            variables: {
+                                                                ...varobj,
+                                                                schemaData: JSON.stringify(schemaCols)
+                                                            }
+                                                        });
+                                                    }}>
+                                                DELETE
+                                            </Button>
+                                        </div>
+                                    )
+                                }}
+                            </Mutation>
+                        )
+                    }
+                }
+
+            </Query>
         )
         )
     }
     }
 }
 }

+ 58 - 0
src/components/common/schema/gql.js

@@ -0,0 +1,58 @@
+import gql from "graphql-tag";
+const SHOW_SCHEMA = gql`
+            query SCHEMA($user_id: String) {
+                schema_by_props(user_id: $user_id) {
+                    schemaData
+                    schemaName
+                    
+                }
+            }
+        `;
+
+const ADD_SCHEMA = gql`
+            mutation SCHEMA($id: ID!, $user_id: String!, $schemaName: String!, $schemaData: String!, $createdAt: String, $updatedAt: String, $schemaState: String) {
+                create_schema(
+                    id: $id,
+                    user_id: $user_id,
+                    schemaName: $schemaName,
+                    createdAt: $createdAt,
+                    updatedAt: $updatedAt,
+                    schemaData: $schemaData,
+                    schemaState: $schemaState
+                ) {
+                    schemaName,
+                    schemaData
+                }
+            }
+        `;
+
+const DELETE_SCHEMA = gql`
+            mutation SCHEMA($schemaName: String) {
+                delete_schema(schemaName: $schemaName)
+            }
+        `;
+
+const UPDATE_SCHEMA = gql`
+            mutation SCHEMA($id: ID!, $schemaData: String!, $updatedAt: String, $schemaState: String) {
+                update_schema(
+                    id: $id,
+                    updatedAt: $updatedAt,
+                    schemaData: $schemaData,
+                    schemaState: $schemaState
+                ) {
+                    schemaName,
+                    schemaData
+                }
+            }
+        `;
+
+
+const SHOW_TABLE = gql`
+            query TABLE($schema_id: ID!) {
+                schema_by_id(id: $schema_id) {
+                    schemaData
+                }
+            }
+        `;
+
+export {SHOW_SCHEMA, ADD_SCHEMA, DELETE_SCHEMA, UPDATE_SCHEMA, SHOW_TABLE}