Skip to content

Instantly share code, notes, and snippets.

@groundwater
Created August 27, 2012 08:29
Show Gist options
  • Save groundwater/3486682 to your computer and use it in GitHub Desktop.
Save groundwater/3486682 to your computer and use it in GitHub Desktop.
Protobuf Schema Generator
message Client {
required string uuid = 5;
optional string accountid = 1;
optional string email = 2;
optional string status = 3;
optional AccessToken token = 4;
required int64 amount = 6;
}
object ProtobufSchemaGenerator {
def schemaForMessage[P<:Message](message:Class[P])={
val getDescriptor = message.getMethod("getDescriptor")
val descriptor = getDescriptor.invoke(null).asInstanceOf[Descriptors.Descriptor]
val fields = descriptor.getFields
val table = descriptor.getName
print("CREATE TABLE %s (\n" format table)
for(i<-0 until fields.size){
val field = fields.get(i)
val exten = if (field.isRequired){
" NOT NULL"
} else {
""
}
val fieldtype = field.getType.toString match {
case "STRING" => "TEXT" + exten
case "MESSAGE" => "VARCHAR(255) REFERENCES %s (uuid)" format field.getMessageType.getName
case "BYTES" => "BYTEA"
case "DOUBLE" => "DOUBLE"
case "FLOAT" => "DOUBLE PRECISION"
case "BOOL" => "BOOLEAN"
case "INT32" => "INTEGER"
case "INT64" => "BIGINT"
}
if(field.getName equals "uuid"){
print(" %10s %s,\n" format ("uuid","VARCHAR(255)"))
}else{
print(" %10s %s,\n" format (field.getName,fieldtype))
}
}
print(" PRIMARY KEY (uuid)\n);")
}
}
CREATE TABLE Client (
uuid VARCHAR(255),
accountid TEXT,
email TEXT,
status TEXT,
token VARCHAR(255) REFERENCES AccessToken (uuid),
amount BIGINT,
PRIMARY KEY (uuid)
);
@groundwater
Copy link
Author

message Client {
required string uuid = 5;
optional string accountid = 1;
optional string email = 2;
optional string status = 3;
optional AccessToken token = 4;
required int64 amount = 6;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment